pgpdsakey.c

来自「著名的加密软件的应用于电子邮件中」· C语言 代码 · 共 1,290 行 · 第 1/3 页

C
1,290
字号
		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.q, 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
dsaSecBufferLength(struct PgpSecKey const *seckey)
{
	struct DSAsecPlus const *sec = (struct DSAsecPlus *)seckey->priv;

	return sec->cklen;
}

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

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

	/* Return only algorithm-dependent portion */
}


/* Fill in secret key structure */
static void
dsaFillSecKey(struct PgpSecKey *seckey, struct DSAsecPlus *sec)
{
	seckey->pkAlg	     = PGP_PKALG_DSA;
	seckey->priv	     = sec;
	seckey->destroy      = dsaSecDestroy;
#if 0
	seckey->id8          = dsaSecId8;
#endif
	seckey->pubkey       = dsaPubkey;
	seckey->islocked     = dsaIslocked;
	seckey->unlock       = dsaUnlock;
	seckey->lock         = dsaLock;
	seckey->maxdecrypted = dsaMaxdecrypted;
	seckey->decrypt      = dsaDecrypt;
	seckey->maxsig       = dsaMaxsig;
	seckey->sign         = dsaSign;
	seckey->changeLock   = dsaChangeLock;
	seckey->bufferLength = dsaSecBufferLength;
	seckey->toBuffer     = dsaSecToBuffer;
}


struct PgpSecKey *
dsaSecFromBuf(byte const *buf, size_t size, int *error)
{
	struct PgpSecKey *seckey;
	struct DSAsecPlus *sec;
	int err = PGPERR_NOMEM;
	byte *cryptk;

	bnInit();
	cryptk = (byte *)pgpMemAlloc(size);
	if (cryptk) {
		sec = (struct DSAsecPlus *)pgpMemAlloc(sizeof(*sec));
		if (sec) {
			seckey = (struct PgpSecKey *)
				pgpMemAlloc(sizeof(*seckey));
			if (seckey) {
				memcpy(cryptk, buf, size);
				bnBegin(&sec->s.p);
				bnBegin(&sec->s.q);
				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_DSA;
				seckey->priv = sec;
				
				if (dsaUnlock(seckey, NULL, NULL, 0) >= 0) {
					if (dsaKeyTooBig (NULL, &sec->s)) {
						err = PGPERR_KEY_UNSUPP;
					} else {
						dsaFillSecKey(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 = err;
	return NULL;
}

#if 0	/* Disabled to avoid use of libm */
/*
 * Heuristic algorithm to estimate the size of the prime order for the
 * generator for DSA signatures.
 *
 * slowfactor is ln(ln(n))**(2/3).
 * Formula for work factor is exp(2.08*(ln n)**(1/3)*slowfactor), where
 * that 2.08 is sensitive to the algorithm.  This assumes some pretty good
 * version of NFS.
 * Change to use base 2 and we get:
 * 2**(2.656*(log2 n)**(1/3)*slowfactor).
 * We assume a DH exponent of 160 is about right for n of about 2**1000.
 * When we change the DH exponent by n bits we get 2**(n/2) increase in
 * work factor, so to find out how much we should change it, take the
 * power of 2 in the formula above, double it, and subtract the value
 * for n=1000, then add 160.
 * This leads to 5.3 * slowfactor * (log2 n)**(1/3) all minus 25 (-185.5+160).
 *
 * A simpler approximation holds slowfactor constant.  Varies from 3.5 at
 * bitsize of 1000 to 4.0 at 4000 bits, so I found that 4.5 made a good
 * conservative approximation for values in this range.  Then heuristic
 * formula becomes cube root of size of prime in bits, times 24, minus 80.
 * This can be calculated pretty well in int arithmetic if we want to.
 */
static unsigned
dsaOrderBits (unsigned primebits)
{
	unsigned size;
	double slowfactor;
	double logbits;
	
	logbits = log((double)primebits);
	slowfactor = exp((2./3.)*log(-.366 + logbits));
	size = 5.3 * slowfactor * exp(logbits/3.) - 25;

	return size >= 160 ? size : 160;
}
#endif


/*
 * Generate an DSA 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.
 *
 * PGP attempts to acquire enough true random entropy in the randpool to
 * make the keys it generates fully random and unpredictable, even if the
 * RNG used to generate them were later found to have some weaknesses.  With
 * RSA keys it gets as many bits as the size of the modulus since the sizes
 * of the secret primes p and q will add up to the size of the modulus.
 * (This is slight overkill since the entropy in a random prime is less
 * than the entropy of a random number because not all numbers are prime.)
 *
 * With discrete log based keys, DSA and ElGamal, only the private exponent
 * x needs to be kept secret.  However, the public values are generated at
 * the same time as x, and are seeded ultimately from the same randpool.
 * These values could theoretically leak information about the state of the
 * randpool when they were generated, and therefore about x.  This would
 * require a very powerful attack which will probably never be possible,
 * but we want to defend against it.  One approach would simply be to acquire
 * as much additional entropy as is needed for the public values, but that
 * is wasteful.  The public values don't need to be random, we just want them
 * to be different among users.
 *
 * Instead, we create a "firewall" between the randpool and the public
 * key values.  We instantiate a second PgpRandomContext which is not
 * based on the randpool but is a simple pseudo RNG, and seed it with
 * a fixed number of bits from the true RNG.  We choose enough bits
 * for the seeding that different keys will not share the same public
 * values.  Only this fixed number of bits reflects the state of the
 * randpool, so we acquire that many bits of additional entropy before
 * beginning the keygen.  This second RNG, rcdummy below and in the
 * ElGamal keygen, is used to generate the public values for the discrete
 * log key.
 */
struct PgpSecKey *
dsaSecGenerate(unsigned bits, Boolean fastgen,
	struct PgpRandomContext const *rc,
	int progress(void *arg, int c), void *arg, int *error)
{
	struct PgpSecKey *seckey = NULL;
	struct DSAsecPlus *sec;
	struct PgpRandomContext *rcdummy = NULL;
	struct BigNum h;
	struct BigNum e;
	unsigned qbits;
	int i;
	byte dummyseed[DSADUMMYBITS/8];

	*error = 0;

	/* Initialize local pointers (simplify cleanup below) */
	seckey = NULL;
	sec = NULL;
	bnBegin(&h);
	bnBegin(&e);

	/* Limit the size we will generate at this time */
	if (bits > MAX_DSA_PRIME_BITS) {
		*error = PGPERR_PUBKEY_TOOBIG;
		goto done;
	}

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

	/* Use fixed primes and generator if in our table */
	if (fastgen) {
		byte const *fixedp, *fixedq;
		size_t fixedplen, fixedqlen;
		if (pgpDSAfixed (bits, &fixedp, &fixedplen, &fixedq, &fixedqlen) > 0) {
			bnInsertBigBytes (&sec->s.q, fixedq, 0, fixedqlen);
			if (progress)
				progress(arg, ' ');
			bnInsertBigBytes (&sec->s.p, fixedp, 0, fixedplen);
			if (progress)
				progress(arg, ' ');
			qbits = bnBits (&sec->s.q);
			goto choose_g;
		}
	}

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

	/*
	 * Choose a random starting place for q, in the high end of the range
	 */
	if (bits <= 1024)
		qbits = 160;	/* Follow the published standard */
	else
		qbits = pgpDiscreteLogExponentBits(bits);
	if (pgpBnGenRand(&sec->s.q, rcdummy, qbits, 0xFF, 1, qbits-9) < 0)
		goto nomem;
	/* And search for a prime */
	i = bnPrimeGen(&sec->s.q, NULL, progress, arg, 0);
	if (i < 0)
		goto nomem;
	if (progress)
		progress(arg, ' ');

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

	/* Temporarily double q */
	if (bnLShift(&sec->s.q, 1) < 0)
		goto nomem;

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

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

	/* Reduce q again */
	bnRShift(&sec->s.q, 1);

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

	/* Now hunt for a suitable g - first, find (p-1)/q */
	if (bnDivMod(&e, &h, &sec->s.p, &sec->s.q) < 0)
		goto nomem;
	/* e is now the exponent (p-1)/q, and h is the remainder (one!) */
	pgpAssert(bnBits(&h)==1);

	if (progress)
		progress(arg, '.');

	/* Search for a suitable h */
	if (bnSetQ(&h, 2) < 0 ||
	    bnTwoExpMod(&sec->s.g, &e, &sec->s.p) < 0)
		goto nomem;
	while (bnBits(&sec->s.g) < 2) {
		if (progress)
			progress(arg, '.');
		if (bnAddQ(&h, 1) < 0 ||
		    bnExpMod(&sec->s.g, &h, &e, &sec->s.p) < 0)
			goto nomem;
	}
	if (progress)
		progress(arg, ' ');

	/* Choose a random 0 < x < q of reasonable size as secret key */
	if (pgpBnGenRand(&sec->s.x, rc, qbits + 8, 0, 0, qbits) < 0 ||
	    bnMod(&sec->s.x, &sec->s.x, &sec->s.q) < 0)
		goto nomem;
	/* prob. failure < 2^-140 is awful unlikely... */
	pgpAssert(bnBits(&sec->s.x) > 20);

	/* 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;
	dsaFillSecKey(seckey, sec);

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

	goto done;

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

	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 + =
减小字号Ctrl + -
显示快捷键?