1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
6 * The library is free for all purposes without any express
12 @file dsa_encrypt_key.c
13 DSA Crypto, Tom St Denis
19 Encrypt a symmetric key with DSA
20 @param in The symmetric key you want to encrypt
21 @param inlen The length of the key to encrypt (octets)
22 @param out [out] The destination for the ciphertext
23 @param outlen [in/out] The max size and resulting size of the ciphertext
24 @param prng An active PRNG state
25 @param wprng The index of the PRNG you wish to use
26 @param hash The index of the hash you want to use
27 @param key The DSA key you want to encrypt to
28 @return CRYPT_OK if successful
30 int dsa_encrypt_key(const unsigned char *in, unsigned long inlen,
31 unsigned char *out, unsigned long *outlen,
32 prng_state *prng, int wprng, int hash,
35 unsigned char *expt, *skey;
40 LTC_ARGCHK(in != NULL);
41 LTC_ARGCHK(out != NULL);
42 LTC_ARGCHK(outlen != NULL);
43 LTC_ARGCHK(key != NULL);
45 /* check that wprng/cipher/hash are not invalid */
46 if ((err = prng_is_valid(wprng)) != CRYPT_OK) {
50 if ((err = hash_is_valid(hash)) != CRYPT_OK) {
54 if (inlen > hash_descriptor[hash].hashsize) {
55 return CRYPT_INVALID_HASH;
58 /* make a random key and export the public copy */
59 if ((err = mp_init_multi(&g_pub, &g_priv, NULL)) != CRYPT_OK) {
63 expt = XMALLOC(mp_unsigned_bin_size(key->p) + 1);
64 skey = XMALLOC(MAXBLOCKSIZE);
65 if (expt == NULL || skey == NULL) {
72 mp_clear_multi(g_pub, g_priv, NULL);
76 /* make a random g_priv, g_pub = g^x pair
77 private key x should be in range: 1 <= x <= q-1 (see FIPS 186-4 B.1.2)
79 if ((err = rand_bn_upto(g_priv, key->q, prng, wprng)) != CRYPT_OK) {
84 if ((err = mp_exptmod(key->g, g_priv, key->p, g_pub)) != CRYPT_OK) {
89 x = mp_unsigned_bin_size(key->p) + 1;
90 if ((err = dsa_shared_secret(g_priv, key->y, key, expt, &x)) != CRYPT_OK) {
95 if ((err = hash_memory(hash, expt, x, skey, &y)) != CRYPT_OK) {
100 for (x = 0; x < inlen; x++) {
104 err = der_encode_sequence_multi(out, outlen,
105 LTC_ASN1_OBJECT_IDENTIFIER, hash_descriptor[hash].OIDlen, hash_descriptor[hash].OID,
106 LTC_ASN1_INTEGER, 1UL, g_pub,
107 LTC_ASN1_OCTET_STRING, inlen, skey,
108 LTC_ASN1_EOL, 0UL, NULL);
111 #ifdef LTC_CLEAN_STACK
113 zeromem(expt, mp_unsigned_bin_size(key->p) + 1);
114 zeromem(skey, MAXBLOCKSIZE);
120 mp_clear_multi(g_pub, g_priv, NULL);
125 /* ref: $Format:%D$ */
126 /* git commit: $Format:%H$ */
127 /* commit time: $Format:%ai$ */