  In the minimal supersymmetric Standard Model with seesaw neutrino masses we
show how R-parity can emerge naturally as a discrete gauge symmetry. The same
discrete symmetry explains the smallness of the \mu-term (the Higgsino mass
parameter) via the Giudice--Masiero mechanism. The discrete gauge anomalies are
cancelled by a discrete version of the Green--Schwarz mechanism. The simplest
symmetry group is found to be Z_4 with a charge assignment that is compatible
with grand unification. Several other Z_N gauge symmetries are found for
N=10,12,18,36 etc, with some models employing discrete anomaly cancellation at
higher Kac-Moody levels. Allowing for a flavor structure in Z_N, we show that
the same gauge symmetry can also explain the observed hierarchy in the fermion
masses and mixings.
