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_decrypt_key.c
13 DSA Crypto, Tom St Denis
19 Decrypt an DSA encrypted key
20 @param in The ciphertext
21 @param inlen The length of the ciphertext (octets)
22 @param out [out] The plaintext
23 @param outlen [in/out] The max size and resulting size of the plaintext
24 @param key The corresponding private DSA key
25 @return CRYPT_OK if successful
27 int dsa_decrypt_key(const unsigned char *in, unsigned long inlen,
28 unsigned char *out, unsigned long *outlen,
31 unsigned char *skey, *expt;
34 unsigned long hashOID[32] = { 0 };
36 ltc_asn1_list decode[3];
38 LTC_ARGCHK(in != NULL);
39 LTC_ARGCHK(out != NULL);
40 LTC_ARGCHK(outlen != NULL);
41 LTC_ARGCHK(key != NULL);
44 if (key->type != PK_PRIVATE) {
45 return CRYPT_PK_NOT_PRIVATE;
48 /* decode to find out hash */
49 LTC_SET_ASN1(decode, 0, LTC_ASN1_OBJECT_IDENTIFIER, hashOID, sizeof(hashOID)/sizeof(hashOID[0]));
50 err = der_decode_sequence(in, inlen, decode, 1);
51 if (err != CRYPT_OK && err != CRYPT_INPUT_TOO_LONG) {
55 hash = find_hash_oid(hashOID, decode[0].size);
56 if (hash_is_valid(hash) != CRYPT_OK) {
57 return CRYPT_INVALID_PACKET;
60 /* we now have the hash! */
62 if ((err = mp_init(&g_pub)) != CRYPT_OK) {
67 expt = XMALLOC(mp_unsigned_bin_size(key->p) + 1);
68 skey = XMALLOC(MAXBLOCKSIZE);
69 if (expt == NULL || skey == NULL) {
80 LTC_SET_ASN1(decode, 1, LTC_ASN1_INTEGER, g_pub, 1UL);
81 LTC_SET_ASN1(decode, 2, LTC_ASN1_OCTET_STRING, skey, MAXBLOCKSIZE);
83 /* read the structure in now */
84 if ((err = der_decode_sequence(in, inlen, decode, 3)) != CRYPT_OK) {
89 x = mp_unsigned_bin_size(key->p) + 1;
90 if ((err = dsa_shared_secret(key->x, g_pub, key, expt, &x)) != CRYPT_OK) {
94 y = mp_unsigned_bin_size(key->p) + 1;
95 y = MIN(y, MAXBLOCKSIZE);
96 if ((err = hash_memory(hash, expt, x, expt, &y)) != CRYPT_OK) {
100 /* ensure the hash of the shared secret is at least as big as the encrypt itself */
101 if (decode[2].size > y) {
102 err = CRYPT_INVALID_PACKET;
106 /* avoid buffer overflow */
107 if (*outlen < decode[2].size) {
108 *outlen = decode[2].size;
109 err = CRYPT_BUFFER_OVERFLOW;
113 /* Decrypt the key */
114 for (x = 0; x < decode[2].size; x++) {
115 out[x] = expt[x] ^ skey[x];
121 #ifdef LTC_CLEAN_STACK
122 zeromem(expt, mp_unsigned_bin_size(key->p) + 1);
123 zeromem(skey, MAXBLOCKSIZE);
136 /* ref: $Format:%D$ */
137 /* git commit: $Format:%H$ */
138 /* commit time: $Format:%ai$ */