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

📄 dsa_subr.c

📁 包含标准证书编/解码、哈希、MD5、SHA1等算法的实现源码
💻 C
📖 第 1 页 / 共 2 页
字号:
/*------------------------------------------------------------------  Copyright  Sun Microsystems, Inc.  Copyright (C) 1994, 1995, 1996 Sun Microsystems, Inc.  All Rights  Reserved.  Permission is hereby granted, free of charge, to any person  obtaining a copy of this software and associated documentation  files (the "Software"), to deal in the Software without  restriction, including without limitation the rights to use,  copy, modify, merge, publish, distribute, sublicense, and/or sell  copies of the Software or derivatives of the Software, and to   permit persons to whom the Software or its derivatives is furnished   to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be  included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND  NONINFRINGEMENT.  IN NO EVENT SHALL SUN MICROSYSTEMS, INC., BE LIABLE  FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN  CONNECTION WITH THE SOFTWARE OR DERIVATES OF THIS SOFTWARE OR   THE USE OR OTHER DEALINGS IN THE SOFTWARE.  Except as contained in this notice, the name of Sun Microsystems, Inc.  shall not be used in advertising or otherwise to promote  the sale, use or other dealings in this Software or its derivatives   without prior written authorization from Sun Microsystems, Inc.*/#pragma ident "@(#)dsa_subr.C	1.8 96/01/30"/* * Copyright (c) 1995, 1996  Colin Plumb.  All rights reserved. * For licensing and other legal details, see the file legal.c. * * This generates DSA primes using a (hopefully) clearly * defined algorithm, based on David Kravitz's "kosherizer". * It is not, however, identical. */#include <stdio.h>#include <string.h>#include "Bstream.h"#include "Bigint.h"#include "Time.h"#include "asn1_der.h"#include "ObjId.h"#include "Name.h"#include "X509Cert.h"#include "Sig.h"#include "bn.h"#include "bn_glue.h"#include "prime.h"#include "sha.h"#include "dsa.h"#include "ca.h"#include "utils.h"/* * Generate a random bignum of a specified length. */intgenRandBn(struct BigNum *bn, unsigned bits){	unsigned char buf[64];	unsigned bytes = (bits+7)/8;	unsigned l = 0;	/* Current position */	unsigned i;	bnSetQ(bn, 0);	if (!bits)		return 0;	/* Do low-order portions */	while (bytes > sizeof(buf)) {		randpool_getbytes(buf, sizeof(buf));		if (bnInsertBigBytes(bn, buf, l, sizeof(buf)) < 0)			return -1;		l += sizeof(buf);	}	/* Do the most-significant chunk */	randpool_getbytes(buf, bytes);	/* Mask off excess high bits */	buf[0] &= 255 >> (-bits & 7);	return bnInsertBigBytes(bn, buf, l, bytes);}/* * DSA signature. * Inputs: * p - a large prime * q - a 160-bit prime factor of (p-1).  (Actually, any length will do.) * g - a generator of order q modulo p, i.e. g^q == 1 (mod p) * x - the secret key, 1 < x < q-1 * hash - the value to be signed * k - the per-signature random number, 1 < k < q-1 * Outputs: r, s * * returns 0 on success and -1 on failure (out of memory or bogus key) */static intdsaSign(struct BigNum const *p, struct BigNum const *q,	struct BigNum const *g, struct BigNum const *x,	struct BigNum const *hash, struct BigNum const *k,	struct BigNum *r, struct BigNum *s){	int retval = -1;	struct BigNum t;	/* Sanity check all the values */	if ((bnLSWord(p) & 1) == 0|| (bnLSWord(q) & 1) == 0 ||	    bnCmp(p, q) <= 0 || bnCmp(p, g) <= 0 ||	    bnCmp(q, x) <= 0 || bnCmp(q, k) <= 0 ||	    bnBits(x) <= 1 || bnBits(k) <= 1)		return -1;	bnBegin(&t);	printf("Error: Cannot Sign\n");	retval = -1;failed:	bnEnd(&t);	return retval;}BstreamDSA_sign(const Bigint& p, const Bigint& q, const Bigint& g,		const Bigint& x, const Bstream& data) {	struct BigNum prime, subprime, gen, secret, k, s_r, s_s, hash;	Bstream nullbstr, localhash;	int retval;	bnInit();	// just in case ...	// locally compute the hash	localhash = messageDigest(data, dsaWithSHA);	// initialize bignums and convert as neccessary	bnBegin(&prime);	bnBegin(&subprime);	bnBegin(&gen);	bnBegin(&secret);	bnBegin(&hash);	bnBegin(&k);	bnBegin(&s_r);	bnBegin(&s_s);	Bigint_to_BigNum(&p, &prime);	Bigint_to_BigNum(&q, &subprime);	Bigint_to_BigNum(&g, &gen);	Bigint_to_BigNum(&x, &secret);	Bstream_to_BigNum(&localhash, &hash);	// generate k uniformly between 0 and q-1	camode = TRUE;	if (genRandBn(&k, bnBits(&subprime)+8) < 0 ||	    bnMod(&k, &k, &subprime) <0) {		fprintf(stderr, "DSA_sign: failed to generate 'k'\n");		goto failed;	}	retval = dsaSign(&prime, &subprime, &gen, &secret, &hash, &k,			&s_r, &s_s);	if (retval == 0) {		Bigint r, s;		BigNum_to_Bigint(&s_r, &r);		BigNum_to_Bigint(&s_s, &s);		nullbstr = asn1_der_encode_dsa_signature(r, s);	} else		fprintf(stderr, "DSA_sign: failed to sign\n");failed:	bnEnd(&prime);	bnEnd(&subprime);	bnEnd(&gen);	bnEnd(&secret);	bnEnd(&k);	bnEnd(&hash);	bnEnd(&s_r);	bnEnd(&s_s);	return (nullbstr);}/* * DSA signature verification. * Inputs: * p - a large prime * q - a 160-bit prime factor of (p-1).  (Actually, any length will do.) * g - a generator of order q modulo p, i.e. g^q == 1 (mod p) * y - the public key, g^x mod p, 1 < y < p-1 * r = the signature (first part) * s = the signature (second part) * hash - the value to be signed * Outputs: * Returns 1 for a good signature, 0 for bad, and -1 on error. * */static intdsaVerify(struct BigNum const *p, struct BigNum const *q,          struct BigNum const *g, struct BigNum const *y,          struct BigNum const *r, struct BigNum const *s,          struct BigNum const *hash){	struct BigNum v, u1, u2;	int retval = -1;	int i;	/* Sanity check all the values */	if ((bnLSWord(p) & 1) == 0|| (bnLSWord(q) & 1) == 0 ||	    bnCmp(p, q) <= 0 || bnCmp(p, g) <= 0 ||	    bnCmp(q, r) <= 0 || bnCmp(q, s) <= 0)		return 0;	// Messed up -> all signatures are bad	bnBegin(&v);	bnBegin(&u1);	bnBegin(&u2);	printf("Error: Cannot Verify\n");	retval = -1;		// An Error since we can't verifyfailed:	bnEnd(&u2);	bnEnd(&u1);	bnEnd(&v);	return retval;}VerifyResultDSA_verify(const Bstream& data, const Bstream& sig, const PubKey& pubkey,		AlgId sigalg){	Bigint p, q, g, y, r, s;	Bstream localhash;	struct BigNum prime, subprime, gen, pub, s_r, s_s, hash;	int retval;	bnInit();	// just in case ....	// decode the DSA parameters, and public key	Bstream der_stream = pubkey.keytype.params;	retval = asn1_der_decode_dsa_params(der_stream, p, q, g);	if (retval < 0) {		fprintf(stderr, "DSA_verify: Bad key params encoding\n");		return (INVALID_SIG);	}	der_stream = pubkey.key;	y = Bigint(der_stream.getdatap(), der_stream.getlength());	if (y == Bigint((short)0)) {		fprintf(stderr, "DSA_verify: Bad publickey encoding\n");		return (INVALID_SIG);	}	// decode the signature into its components	retval = asn1_der_decode_dsa_signature(sig, r, s);	if (retval < 0) {		fprintf(stderr, "DSA_verify: Bad signature encoding\n");		return (INVALID_SIG);	}	// Locally compute message digest over the input portion	localhash = messageDigest(data, sigalg.algid);	// intialize bignums and convert as necessary	bnBegin(&prime);	bnBegin(&subprime);	bnBegin(&gen);	bnBegin(&pub);	bnBegin(&s_r);	bnBegin(&s_s);	bnBegin(&hash);	Bigint_to_BigNum(&p, &prime);	Bigint_to_BigNum(&q, &subprime);	Bigint_to_BigNum(&g, &gen);	Bigint_to_BigNum(&y, &pub);	Bigint_to_BigNum(&r, &s_r);	Bigint_to_BigNum(&s, &s_s);	Bstream_to_BigNum(&localhash, &hash);		retval = dsaVerify(&prime, &subprime, &gen, &pub, &s_r, &s_s, &hash);	bnEnd(&prime);	bnEnd(&subprime);	bnEnd(&gen);	bnEnd(&pub);	bnEnd(&s_r);	bnEnd(&s_s);	bnEnd(&hash);	if (retval <= 0) {		fprintf(stderr, "DSA_verify: Bad signature\n");		return (INVALID_SIG);	}	return (VALID);}// ASN.1 routines for DSA encoding/decodingintasn1_der_decode_dsa_privkey(Bstream der_stream, Bigint& p, Bigint& q,				Bigint& g, Bigint& x){        byte tmp = 0;        int seqlen, retval = 0;        ObjId oid;        Bigint version;	Bstream DSAprivkey;	SEQUENCE {		INTEGER(version);	// version of syntax		SEQUENCE {		// privkey alg id			OBJECT_IDENTIFIER(oid);                	SEQUENCE {                        	INTEGER(p);                        	INTEGER(q);                        	INTEGER(g);                	}        	}		OCTET_STRING(DSAprivkey);		// XXX -- leaving out the optional attributes stuff	}

⌨️ 快捷键说明

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