⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pgpelgkey.c

📁 著名的加密软件的应用于电子邮件中
💻 C
📖 第 1 页 / 共 3 页
字号:
 *  6+u+v+w          1    Encryption algorithm (0 for none, 1 for IDEA)
 *  7+u+v+w          t    Encryption IV: 0 or 8 bytes
 *  7+t+u+v+w        2+x  MPI for x (discrete log of public key)
 *  9+t+u+v+w+x      2    Checksum
 * 11+t+u+v+w+x
 *
 * The Encryption algorithm is the cipher algorithm for the old-style
 * string-to-key conversion.  For the new type, it's 255, then a cipher
 * algorithm, then a string-to-key algorithm (variable-length),
 * then the encryption IV.  That's 16 bytes plus the string-to-key
 * conversion length.
 *
 * On initial key generation we rely on calling this with env=NULL being
 * OK if phrase=NULL.
 */

static int
elgChangeLock(struct PgpSecKey *seckey, struct PgpEnv const *env,
	struct PgpRandomContext const *rc, char const *phrase, size_t plen)
{
	struct ELGsecPlus *sec = (struct ELGsecPlus *)seckey->priv;
	struct PgpStringToKey *s2k = NULL;	/* Shut up warnings */
	struct PgpCipher const *cipher = NULL;	/* Shut up warnings */
	struct PgpCfbContext *cfb = NULL;	/* This is realy needed */
	byte *p;
	int oldf = 0;				/* Shut up warnings */
	unsigned len;
	unsigned checksum;

	ASSERTELG(seckey->pkAlg);
	if (sec->locked)
		return PGPERR_KEY_ISLOCKED;

	len = bnBytes(&sec->s.p) + bnBytes(&sec->s.g) +
	      bnBytes(&sec->s.y) + bnBytes(&sec->s.x) + 11;
	if (phrase) {
		s2k = pgpS2Kdefault(env, rc);
		if (!s2k)
			return PGPERR_NOMEM;
		cipher = pgpCipherDefaultKey(env);
		pgpAssert(cipher);
		if (!cipher) {
			pgpS2Kdestroy(s2k);
			return PGPERR_NOMEM;
		}
		len += cipher->blocksize;
		cfb = pgpCfbCreate(cipher);
		if (!cfb) {
			pgpS2Kdestroy(s2k);
			return PGPERR_NOMEM;
		}
		oldf = pgpS2KisOldVers(s2k);
		if (!oldf)
			len += 1 + s2k->encodelen;
	}
	p = sec->cryptkey;
	if (len > sec->ckalloc) {
		p = (byte *)pgpMemRealloc(p, len);
		if (!p) {
			pgpCfbDestroy(cfb);
			pgpS2Kdestroy(s2k);
			return PGPERR_NOMEM;
		}
		sec->cryptkey = p;
		sec->ckalloc = (size_t)len;
	}
	sec->cklen = len;

	/* Okay, no more errors possible!   Start installing data */
	p += pgpBnPutPlain(&sec->s.p, p);
	p += pgpBnPutPlain(&sec->s.g, p);
	p += pgpBnPutPlain(&sec->s.y, p);

	/* Encryption parameters */
	if (!phrase) {
		*p++ = 0;	/* Unencrypted */
	} else {
		if (oldf) {
			*p++ = cipher->type;
		} else {
			*p++ = 255;
			*p++ = cipher->type;
			memcpy(p, s2k->encoding, s2k->encodelen);
			p += s2k->encodelen;
		}
		/* Create IV */
		pgpRandomGetBytes(rc, p, cipher->blocksize);
		/* Use data buffer as temp holding space for key */
		pgpAssert(sec->ckalloc-cipher->blocksize >= cipher->keysize);
		pgpStringToKey(s2k, phrase, plen, p+cipher->blocksize,
			cipher->keysize);
		pgpCfbInit(cfb, p+cipher->blocksize, p);
		pgpS2Kdestroy(s2k);
		p += cipher->blocksize;
		/* Wipe key *immediately* */
		memset(p, 0, cipher->keysize);
	}

	/* Now install x, encrypted */
	checksum = 0;
	p += pgpBnPutNew(&sec->s.x, p, cfb, &checksum);
	pgpChecksumPutNew(checksum, p, cfb);
	p += 2;
	pgpAssert((ptrdiff_t)len == p - sec->cryptkey);

	if (cfb)
		pgpCfbDestroy(cfb);
	return 0;	/* Success */
}

static size_t
elgSecBufferLength(struct PgpSecKey const *seckey)
{
	struct ELGsecPlus const *sec = (struct ELGsecPlus *)seckey->priv;

	return sec->cklen;
}

static void
elgSecToBuffer(struct PgpSecKey const *seckey, byte *buf)
{
	struct ELGsecPlus const *sec = (struct ELGsecPlus *)seckey->priv;

	memcpy(buf, sec->cryptkey, sec->cklen);

	/* Return only algorithm-dependent portion */
}


/* Fill in secret key structure */
static void
elgFillSecKey(struct PgpSecKey *seckey, struct ELGsecPlus *sec)
{
	seckey->pkAlg	     = PGP_PKALG_ELGAMAL;
	seckey->priv	     = sec;
	seckey->destroy      = elgSecDestroy;
#if 0
	seckey->id8          = elgSecId8;
#endif
	seckey->pubkey       = elgPubkey;
	seckey->islocked     = elgIslocked;
	seckey->unlock       = elgUnlock;
	seckey->lock         = elgLock;
	seckey->maxdecrypted = elgMaxdecrypted;
	seckey->decrypt      = elgDecrypt;
	seckey->maxsig       = elgMaxsig;
	seckey->sign         = elgSign;
	seckey->changeLock   = elgChangeLock;
	seckey->bufferLength = elgSecBufferLength;
	seckey->toBuffer     = elgSecToBuffer;
}


struct PgpSecKey *
elgSecFromBuf(byte const *buf, size_t size, int *error)
{
	struct PgpSecKey *seckey;
	struct ELGsecPlus *sec;
	byte *cryptk;

	bnInit();
	cryptk = (byte *)pgpMemAlloc(size);
	if (cryptk) {
		sec = (struct ELGsecPlus *)pgpMemAlloc(sizeof(*sec));
		if (sec) {
			seckey = (struct PgpSecKey *)
				pgpMemAlloc(sizeof(*seckey));
			if (seckey) {
				memcpy(cryptk, buf, size);
				bnBegin(&sec->s.p);
				bnBegin(&sec->s.g);
				bnBegin(&sec->s.y);
				bnBegin(&sec->s.x);
				sec->cryptkey = cryptk;
				sec->cklen = sec->ckalloc = size;
				sec->locked = 1;
				/* We only need this to try unlocking... */
				seckey->pkAlg = PGP_PKALG_ELGAMAL;
				seckey->priv = sec;
				
				if (elgUnlock(seckey, NULL, NULL, 0) >= 0) {
					elgFillSecKey(seckey, sec);
					*error = 0;
					return seckey;	/* Success! */
				}

				/* Ka-boom.  Delete and free everything. */
				memset(cryptk, 0, size);
				memset(sec, 0, sizeof(*sec));
				pgpMemFree(seckey);
			}
			pgpMemFree(sec);
		}
		pgpMemFree(cryptk);
	}
	*error = PGPERR_NOMEM;
	return NULL;
}

/* Generate super-strong primes? (Warning: slow!) */
#ifndef ELG_GERMAIN
#define ELG_GERMAIN 0
#endif

/*
 * Generate an ELG secret key with prime of the specified number of bits.
 * Make callbacks to progress function periodically.
 * Secret key is returned in the unlocked form, with no passphrase set.
 * fastgen tells us to use canned primes if available.
 *
 * If ELG_GERMAIN is set to 1, we generate p such that (p-1)/2 is also
 * prime.  This takes long time.  (Pseudoprimality tests take time
 * cubic in the number of bits, and the number of tests needed is
 * linear in the number of bits, so it's quartic overall.  Searching
 * for Sophier Germain primes makes it quintic(!), although the constant
 * factor improves to make up for a lot of that.
 *
 * The alternative (which is really just as safe, really) is to generate
 * primes which have a large prime factor q about 10 bits shorter than
 * the requested length.  We will guarantee that 2 is a generator of a
 * subgroup with period at least q.
 *
 * If it is OK, we could speed it up more by generating multiple primes
 * qi such that p = 2*k*q1*q2*q3*...*qn + 1, and where each qi is greater
 * than 2**160 (or whatever exponent value we are using).  Again, once we
 * verify that 2's period is > 2k we know it as at least min(qi), which
 * should be long enough for prevention of discrete log attacks.
 *
 * A bit of theory: the average density of primes around n is 1/ln(n),
 * so the average gap between primes is ln(n).  However, the maximum
 * gap is ln(n)^2.  The fact that we're searching in steps other than
 * 1 doesn't matter - it'll take an average of ln(n) steps.
 *
 * So to produce a prime of the desired size, we should have p/q at
 * least ln(p) and to guarantee it, we need p/q = ln(p)^2.  This
 * means that we want
 * log2(ln(p))           < log2(p/q)         < log2(ln(p)^2)
 * log2(0.693*log2(p))   < log2(p) - log2(q) < 2 * log2(0.693 * log2(p))
 * log2(log2(p)) - 0.529 < log2(p) - log2(q) < 2 * log2(log2(p)) - 1.058
 *
 * At this point, it's safe to start getting crude, because if we're
 * only counting bits, 2^(bits(x)-1) <= x < 2^bits(x) <= 2*x, or
 * bits(x)-1 <= log2(x) < bits(x) <= log2(x)+1.  Another way of looking
 * at all this is that log2(x) is bits(x) - 0.5 +/- 0.5.
 * So let's split the difference and use 1.5 * bits(bits(p)) - 1 as the
 * difference in bits between p and q.
 *
 * See the discussion preceding the DSA keygen routine dsaSecGenerate
 * in pgpDSAKey.c for an explanation of the rcdummy random number
 * generator below.  It serves to limit leakage of the state of the
 * randpool into the public values generated as part of the key.
 */
struct PgpSecKey *
elgSecGenerate(unsigned bits, Boolean fastgen,
	struct PgpRandomContext const *rc,
	int progress(void *arg, int c), void *arg, int *error)
{
	struct PgpSecKey *seckey;
	struct ELGsecPlus *sec;
	struct PgpRandomContext *rcdummy = NULL;
	unsigned bits2;
#if !ELG_GERMAIN
	unsigned lengthdiff;
	struct BigNum q, h, e;
	int i;
#endif
	byte dummyseed[ELGDUMMYBITS/8];

	*error = 0;

	/* Initialize local pointers (simplify cleanup below) */
	seckey = NULL;
	sec = NULL;

	/* Allocate data structures */
	seckey = (struct PgpSecKey *)pgpMemAlloc(sizeof(*seckey));
	if (!seckey)
		goto memerror;
	sec = (struct ELGsecPlus *)pgpMemAlloc(sizeof(*sec));
	if (!sec)
		goto memerror;
	
	bnBegin(&sec->s.p);
	bnBegin(&sec->s.g);
	bnBegin(&sec->s.y);
	bnBegin(&sec->s.x);

	/* Use a fixed prime and generator if in our table */
	if (fastgen) {
		byte const *fixedp, *fixedg;
		size_t fixedplen, fixedglen;
		if (pgpElGfixed (bits, &fixedp, &fixedplen, &fixedg, &fixedglen) > 0) {
			if (progress)
				progress(arg, ' ');
			bnInsertBigBytes (&sec->s.p, fixedp, 0, fixedplen);
			if (progress)
				progress(arg, ' ');
			bnInsertBigBytes (&sec->s.g, fixedg, 0, fixedglen);
			goto choose_x;
		}
	}

	/* Set up local random number generator for p and q */
	rcdummy = pgpPseudoRandomCreate ();
	if (!rcdummy)
		goto memerror;
	pgpRandomGetBytes (rc, dummyseed, sizeof(dummyseed));
	pgpRandomAddBytes (rcdummy, dummyseed, sizeof(dummyseed));

#if ELG_GERMAIN
	/* Strong ("sophie germain") prime search */

	/* Find p - choose a starting place */
	if (pgpBnGenRand(&sec->s.p, rcdummy, bits, 0xC0, 3, bits-4) < 0)
		goto nomem;

	/* And search for a prime */
	if (bnGermainPrimeGen(&sec->s.p, 1, progress, arg) < 0)
		goto nomem;

	/* We have chosen p so 2 is a good choice for generator */
	if (bnSetQ(&sec->s.g, 2) < 0)
		goto nomem;

	/* Choose a random x of reasonable size as secret key */
	expbits = elgExpBits(bits);
	if (pgpBnGenRand(&sec->s.x, rc, expbits, 0, 0, expbits) < 0)
		goto nomem;

	/* And calculate g**x as public key */
	if (bnTwoExpMod(&sec->s.y, &sec->s.x, &sec->s.p) < 0)
		goto nomem;
#else /* !ELG_GERMAIN - the faster version */
	bnBegin(&q);
	bnBegin(&h);
	bnBegin(&e);

	/*
	 * Choose a random starting place for q, a bit less than p.
	 * (See function header comment above for the theory behind this.)
	 */
	lengthdiff = 0;
	for (bits2 = bits; bits2; bits2 >>= 1)
		lengthdiff++;
	lengthdiff += (lengthdiff+1)/2;
	bits2 = bits - lengthdiff;

	if (pgpBnGenRand(&q, rcdummy, bits2, 0x80, 1, bits2-2) < 0)
		goto nomem;
	/* And search for a prime */
	i = bnPrimeGen(&q, NULL, progress, arg, 0);
	if (i < 0)
		goto nomem;
	if (progress)
		progress(arg, ' ');

	/* ...and now a random start for p */
	(void)bnSetQ(&sec->s.p, 0);
	if (pgpBnGenRand(&sec->s.p, rcdummy, bits, 0xC0, 1, bits-bits2-3) < 0)
		goto nomem;

	/* Double q to make it a suitable stride */
	if (bnLShift(&q, 1) < 0)
		goto nomem;

	/* Set p = p - (p mod 2q) + 1, i.e. congruent to 1 mod 2q */
	if (bnMod(&h, &sec->s.p, &q) < 0)
		goto nomem;
	if (bnSub(&sec->s.p, &h) < 0 || bnAddQ(&sec->s.p, 1) < 0)
		goto nomem;

	/* This loop is very rarely executed */
retry:
	/* And search for a prime, 1+2kq for some k */
	i = bnPrimeGenStrong(&sec->s.p, &q, progress, arg);
	if (i < 0)
		goto nomem;
	if (progress)
		progress(arg, ' ');

	/* Now check two as g: first, find (p-1)/q = 2*((p-1)/(2*q)) */
	if (bnDivMod(&e, &h, &sec->s.p, &q) < 0 || bnLShift(&e, 1) < 0)
		goto nomem;
	/* e is now (p-1)/q, and h is the remainder (one!) */
	pgpAssert (bnBits(&h) == 1);

	/*
	 * Make sure 2**((p-1)/q) mod p is not small.  This should imply
	 * that the period of 2 as a generator has at least q as a factor,
	 * meaning it is very big.
	 * With (p-1)/q as small as it is, the chances are *excellent*
	 * that it will work.  If (p-1)/q were less than a few hundred
	 * 2**((p-1)/q) would be less than p and coundn't possibly be 1.
	 */
	if (bnTwoExpMod(&h, &e, &sec->s.p) < 0)
		goto nomem;
	if (bnBits(&h) < 2) {
		if (progress)
			progress(arg, ' ');
		goto retry;
	}
	bnEnd(&e);
	bnEnd(&h);
	bnEnd(&q);
#endif
	/* We have done things so 2 is a good choice for generator */
	if (bnSetQ(&sec->s.g, 2) < 0)
		goto nomem;

	/* May get here directly from above if fixed primes are used */
choose_x:

	/* Choose a random x of reasonable size as secret key */
	bits2 = pgpDiscreteLogExponentBits(bits)*3/2;
	if (pgpBnGenRand(&sec->s.x, rc, bits2, 0, 0, bits2) < 0)
		goto nomem;

	/* And calculate g**x as public key */
	if (bnExpMod(&sec->s.y, &sec->s.g, &sec->s.x, &sec->s.p) < 0)
		goto nomem;
	

	/* And that's it... success! */

	/* Fill in structs */
	sec->cryptkey = NULL;
	sec->ckalloc = sec->cklen = 0;
	sec->locked = 0;
	elgFillSecKey(seckey, sec);

	/* Fill in cryptkey structure, unencrypted */
	elgChangeLock (seckey, NULL, NULL, NULL, 0);

	goto done;

nomem:
#if !ELG_GERMAIN
	bnEnd(&e);
	bnEnd(&h);
	bnEnd(&q);
#endif
	bnEnd(&sec->s.p);
	bnEnd(&sec->s.g);
	bnEnd(&sec->s.y);
	bnEnd(&sec->s.x);
	/* Fall through */
memerror:
	pgpMemFree(seckey);
	pgpMemFree(sec);
	seckey = NULL;
	*error = PGPERR_NOMEM;

done:
	if (rcdummy)
		pgpRandomDestroy (rcdummy);
		
	return seckey;
}


/*
 * Local Variables:
 * tab-width: 4
 * End:
 * vi: ts=4 sw=4
 * vim: si
 */

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -