Debian Codegraph @

src/lib/crypto/OSSLDSA.cpp

raw
1 /*
2 * Copyright (c) 2010 SURFnet bv
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
20 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
21 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
22 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
23 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
24 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27 /*****************************************************************************
28 OSSLDSA.cpp
29
30 OpenSSL DSA asymmetric algorithm implementation
31 *****************************************************************************/
32
33 #include "config.h"
34 #include "log.h"
35 #include "OSSLDSA.h"
36 #include "CryptoFactory.h"
37 #include "DSAParameters.h"
38 #include "OSSLDSAKeyPair.h"
39 #include "OSSLComp.h"
40 #include "OSSLUtil.h"
41 #include <algorithm>
42 #include <openssl/dsa.h>
43 #include <openssl/pem.h>
44 #include <openssl/err.h>
45
46 // Constructor
47 OSSLDSA::OSSLDSA()
48 {
49 pCurrentHash = NULL;
50 }
51
52 // Destructor
53 OSSLDSA::~OSSLDSA()
54 {
55 if (pCurrentHash != NULL)
56 {
57 delete pCurrentHash;
58 }
59 }
60
61 // Signing functions
62 bool OSSLDSA::sign(PrivateKey* privateKey, const ByteString& dataToSign,
63 ByteString& signature, const AsymMech::Type mechanism,
64 const void* param /* = NULL */, const size_t paramLen /* = 0 */)
65 {
66 if (mechanism == AsymMech::DSA)
67 {
68 // Separate implementation for DSA signing without hash computation
69
70 // Check if the private key is the right type
71 if (!privateKey->isOfType(OSSLDSAPrivateKey::type))
72 {
73 ERROR_MSG("Invalid key type supplied");
74
75 return false;
76 }
77
78 OSSLDSAPrivateKey* pk = (OSSLDSAPrivateKey*) privateKey;
79 DSA* dsa = pk->getOSSLKey();
80
81 // Perform the signature operation
82 unsigned int sigLen = pk->getOutputLength();
83 signature.resize(sigLen);
84 memset(&signature[0], 0, sigLen);
85 int dLen = dataToSign.size();
86 DSA_SIG* sig = DSA_do_sign(dataToSign.const_byte_str(), dLen, dsa);
87 if (sig == NULL)
88 return false;
89 // Store the 2 values with padding
90 const BIGNUM* bn_r = NULL;
91 const BIGNUM* bn_s = NULL;
92 DSA_SIG_get0(sig, &bn_r, &bn_s);
93 BN_bn2bin(bn_r, &signature[sigLen / 2 - BN_num_bytes(bn_r)]);
94 BN_bn2bin(bn_s, &signature[sigLen - BN_num_bytes(bn_s)]);
95 DSA_SIG_free(sig);
96 return true;
97 }
98 else
99 {
100 // Call default implementation
101 return AsymmetricAlgorithm::sign(privateKey, dataToSign, signature, mechanism, param, paramLen);
102 }
103 }
104
105 bool OSSLDSA::signInit(PrivateKey* privateKey, const AsymMech::Type mechanism,
106 const void* param /* = NULL */, const size_t paramLen /* = 0 */)
107 {
108 if (!AsymmetricAlgorithm::signInit(privateKey, mechanism, param, paramLen))
109 {
110 return false;
111 }
112
113 // Check if the private key is the right type
114 if (!privateKey->isOfType(OSSLDSAPrivateKey::type))
115 {
116 ERROR_MSG("Invalid key type supplied");
117
118 ByteString dummy;
119 AsymmetricAlgorithm::signFinal(dummy);
120
121 return false;
122 }
123
124 HashAlgo::Type hash = HashAlgo::Unknown;
125
126 switch (mechanism)
127 {
128 case AsymMech::DSA_SHA1:
129 hash = HashAlgo::SHA1;
130 break;
131 case AsymMech::DSA_SHA224:
132 hash = HashAlgo::SHA224;
133 break;
134 case AsymMech::DSA_SHA256:
135 hash = HashAlgo::SHA256;
136 break;
137 case AsymMech::DSA_SHA384:
138 hash = HashAlgo::SHA384;
139 break;
140 case AsymMech::DSA_SHA512:
141 hash = HashAlgo::SHA512;
142 break;
143 default:
144 ERROR_MSG("Invalid mechanism supplied (%i)", mechanism);
145
146 ByteString dummy;
147 AsymmetricAlgorithm::signFinal(dummy);
148
149 return false;
150 }
151
152 pCurrentHash = CryptoFactory::i()->getHashAlgorithm(hash);
153
154 if (pCurrentHash == NULL)
155 {
156 ByteString dummy;
157 AsymmetricAlgorithm::signFinal(dummy);
158
159 return false;
160 }
161
162 if (!pCurrentHash->hashInit())
163 {
164 delete pCurrentHash;
165 pCurrentHash = NULL;
166
167 ByteString dummy;
168 AsymmetricAlgorithm::signFinal(dummy);
169
170 return false;
171 }
172
173 return true;
174 }
175
176 bool OSSLDSA::signUpdate(const ByteString& dataToSign)
177 {
178 if (!AsymmetricAlgorithm::signUpdate(dataToSign))
179 {
180 return false;
181 }
182
183 if (!pCurrentHash->hashUpdate(dataToSign))
184 {
185 delete pCurrentHash;
186 pCurrentHash = NULL;
187
188 ByteString dummy;
189 AsymmetricAlgorithm::signFinal(dummy);
190
191 return false;
192 }
193
194 return true;
195 }
196
197 bool OSSLDSA::signFinal(ByteString& signature)
198 {
199 // Save necessary state before calling super class signFinal
200 OSSLDSAPrivateKey* pk = (OSSLDSAPrivateKey*) currentPrivateKey;
201
202 if (!AsymmetricAlgorithm::signFinal(signature))
203 {
204 return false;
205 }
206
207 ByteString hash;
208
209 bool bFirstResult = pCurrentHash->hashFinal(hash);
210
211 delete pCurrentHash;
212 pCurrentHash = NULL;
213
214 if (!bFirstResult)
215 {
216 return false;
217 }
218
219 DSA* dsa = pk->getOSSLKey();
220
221 // Perform the signature operation
222 unsigned int sigLen = pk->getOutputLength();
223 signature.resize(sigLen);
224 memset(&signature[0], 0, sigLen);
225 DSA_SIG* sig = DSA_do_sign(&hash[0], hash.size(), dsa);
226 if (sig == NULL)
227 return false;
228 // Store the 2 values with padding
229 const BIGNUM* bn_r = NULL;
230 const BIGNUM* bn_s = NULL;
231 DSA_SIG_get0(sig, &bn_r, &bn_s);
232 BN_bn2bin(bn_r, &signature[sigLen / 2 - BN_num_bytes(bn_r)]);
233 BN_bn2bin(bn_s, &signature[sigLen - BN_num_bytes(bn_s)]);
234 DSA_SIG_free(sig);
235 return true;
236 }
237
238 // Verification functions
239 bool OSSLDSA::verify(PublicKey* publicKey, const ByteString& originalData,
240 const ByteString& signature, const AsymMech::Type mechanism,
241 const void* param /* = NULL */, const size_t paramLen /* = 0 */)
242 {
243 if (mechanism == AsymMech::DSA)
244 {
245 // Separate implementation for DSA verification without hash computation
246
247 // Check if the private key is the right type
248 if (!publicKey->isOfType(OSSLDSAPublicKey::type))
249 {
250 ERROR_MSG("Invalid key type supplied");
251
252 return false;
253 }
254
255 // Perform the verify operation
256 OSSLDSAPublicKey* pk = (OSSLDSAPublicKey*) publicKey;
257 unsigned int sigLen = pk->getOutputLength();
258 if (signature.size() != sigLen)
259 return false;
260 DSA_SIG* sig = DSA_SIG_new();
261 if (sig == NULL)
262 return false;
263 const unsigned char *s = signature.const_byte_str();
264 BIGNUM* bn_r = BN_bin2bn(s, sigLen / 2, NULL);
265 BIGNUM* bn_s = BN_bin2bn(s + sigLen / 2, sigLen / 2, NULL);
266 if (bn_r == NULL || bn_s == NULL ||
267 !DSA_SIG_set0(sig, bn_r, bn_s))
268 {
269 DSA_SIG_free(sig);
270 return false;
271 }
272 int dLen = originalData.size();
273 int ret = DSA_do_verify(originalData.const_byte_str(), dLen, sig, pk->getOSSLKey());
274 if (ret != 1)
275 {
276 if (ret < 0)
277 ERROR_MSG("DSA verify failed (0x%08X)", ERR_get_error());
278
279 DSA_SIG_free(sig);
280 return false;
281 }
282
283 DSA_SIG_free(sig);
284 return true;
285 }
286 else
287 {
288 // Call the generic function
289 return AsymmetricAlgorithm::verify(publicKey, originalData, signature, mechanism, param, paramLen);
290 }
291 }
292
293 bool OSSLDSA::verifyInit(PublicKey* publicKey, const AsymMech::Type mechanism,
294 const void* param /* = NULL */, const size_t paramLen /* = 0 */)
295 {
296 if (!AsymmetricAlgorithm::verifyInit(publicKey, mechanism, param, paramLen))
297 {
298 return false;
299 }
300
301 // Check if the private key is the right type
302 if (!publicKey->isOfType(OSSLDSAPublicKey::type))
303 {
304 ERROR_MSG("Invalid key type supplied");
305
306 ByteString dummy;
307 AsymmetricAlgorithm::verifyFinal(dummy);
308
309 return false;
310 }
311
312 HashAlgo::Type hash = HashAlgo::Unknown;
313
314 switch (mechanism)
315 {
316 case AsymMech::DSA_SHA1:
317 hash = HashAlgo::SHA1;
318 break;
319 case AsymMech::DSA_SHA224:
320 hash = HashAlgo::SHA224;
321 break;
322 case AsymMech::DSA_SHA256:
323 hash = HashAlgo::SHA256;
324 break;
325 case AsymMech::DSA_SHA384:
326 hash = HashAlgo::SHA384;
327 break;
328 case AsymMech::DSA_SHA512:
329 hash = HashAlgo::SHA512;
330 break;
331 default:
332 ERROR_MSG("Invalid mechanism supplied (%i)", mechanism);
333
334 ByteString dummy;
335 AsymmetricAlgorithm::verifyFinal(dummy);
336
337 return false;
338 }
339
340 pCurrentHash = CryptoFactory::i()->getHashAlgorithm(hash);
341
342
343 if (pCurrentHash == NULL)
344 {
345 ByteString dummy;
346 AsymmetricAlgorithm::verifyFinal(dummy);
347
348 return false;
349 }
350
351 if (!pCurrentHash->hashInit())
352 {
353 delete pCurrentHash;
354 pCurrentHash = NULL;
355
356 ByteString dummy;
357 AsymmetricAlgorithm::verifyFinal(dummy);
358
359 return false;
360 }
361
362 return true;
363 }
364
365 bool OSSLDSA::verifyUpdate(const ByteString& originalData)
366 {
367 if (!AsymmetricAlgorithm::verifyUpdate(originalData))
368 {
369 return false;
370 }
371
372 if (!pCurrentHash->hashUpdate(originalData))
373 {
374 delete pCurrentHash;
375 pCurrentHash = NULL;
376
377 ByteString dummy;
378 AsymmetricAlgorithm::verifyFinal(dummy);
379
380 return false;
381 }
382
383 return true;
384 }
385
386 bool OSSLDSA::verifyFinal(const ByteString& signature)
387 {
388 // Save necessary state before calling super class verifyFinal
389 OSSLDSAPublicKey* pk = (OSSLDSAPublicKey*) currentPublicKey;
390
391 if (!AsymmetricAlgorithm::verifyFinal(signature))
392 {
393 return false;
394 }
395
396 ByteString hash;
397
398 bool bFirstResult = pCurrentHash->hashFinal(hash);
399
400 delete pCurrentHash;
401 pCurrentHash = NULL;
402
403 if (!bFirstResult)
404 {
405 return false;
406 }
407
408 // Perform the verify operation
409 unsigned int sigLen = pk->getOutputLength();
410 if (signature.size() != sigLen)
411 return false;
412 DSA_SIG* sig = DSA_SIG_new();
413 if (sig == NULL)
414 return false;
415 const unsigned char *s = signature.const_byte_str();
416 BIGNUM* bn_r = BN_bin2bn(s, sigLen / 2, NULL);
417 BIGNUM* bn_s = BN_bin2bn(s + sigLen / 2, sigLen / 2, NULL);
418 if (bn_r == NULL || bn_s == NULL ||
419 !DSA_SIG_set0(sig, bn_r, bn_s))
420 {
421 DSA_SIG_free(sig);
422 return false;
423 }
424 int ret = DSA_do_verify(&hash[0], hash.size(), sig, pk->getOSSLKey());
425 if (ret != 1)
426 {
427 if (ret < 0)
428 ERROR_MSG("DSA verify failed (0x%08X)", ERR_get_error());
429
430 DSA_SIG_free(sig);
431 return false;
432 }
433
434 DSA_SIG_free(sig);
435 return true;
436 }
437
438 // Encryption functions
439 bool OSSLDSA::encrypt(PublicKey* /*publicKey*/, const ByteString& /*data*/,
440 ByteString& /*encryptedData*/, const AsymMech::Type /*padding*/)
441 {
442 ERROR_MSG("DSA does not support encryption");
443
444 return false;
445 }
446
447 // Decryption functions
448 bool OSSLDSA::decrypt(PrivateKey* /*privateKey*/, const ByteString& /*encryptedData*/,
449 ByteString& /*data*/, const AsymMech::Type /*padding*/)
450 {
451 ERROR_MSG("DSA does not support decryption");
452
453 return false;
454 }
455
456 // Key factory
457 bool OSSLDSA::generateKeyPair(AsymmetricKeyPair** ppKeyPair, AsymmetricParameters* parameters, RNG* /*rng = NULL */)
458 {
459 // Check parameters
460 if ((ppKeyPair == NULL) ||
461 (parameters == NULL))
462 {
463 return false;
464 }
465
466 if (!parameters->areOfType(DSAParameters::type))
467 {
468 ERROR_MSG("Invalid parameters supplied for DSA key generation");
469
470 return false;
471 }
472
473 DSAParameters* params = (DSAParameters*) parameters;
474
475 // Generate the key-pair
476 DSA* dsa = DSA_new();
477 if (dsa == NULL)
478 {
479 ERROR_MSG("Failed to instantiate OpenSSL DSA object");
480
481 return false;
482 }
483
484 // Use the OpenSSL implementation and not any engine
485 DSA_set_method(dsa, DSA_get_default_method());
486
487 BIGNUM* bn_p = OSSL::byteString2bn(params->getP());
488 BIGNUM* bn_q = OSSL::byteString2bn(params->getQ());
489 BIGNUM* bn_g = OSSL::byteString2bn(params->getG());
490 DSA_set0_pqg(dsa, bn_p, bn_q, bn_g);
491
492 if (DSA_generate_key(dsa) != 1)
493 {
494 ERROR_MSG("DSA key generation failed (0x%08X)", ERR_get_error());
495
496 DSA_free(dsa);
497
498 return false;
499 }
500
501 // Create an asymmetric key-pair object to return
502 OSSLDSAKeyPair* kp = new OSSLDSAKeyPair();
503
504 ((OSSLDSAPublicKey*) kp->getPublicKey())->setFromOSSL(dsa);
505 ((OSSLDSAPrivateKey*) kp->getPrivateKey())->setFromOSSL(dsa);
506
507 *ppKeyPair = kp;
508
509 // Release the key
510 DSA_free(dsa);
511
512 return true;
513 }
514
515 unsigned long OSSLDSA::getMinKeySize()
516 {
517 #ifdef WITH_FIPS
518 // OPENSSL_DSA_FIPS_MIN_MODULUS_BITS is 1024
519 return 1024;
520 #else
521 return 512;
522 #endif
523 }
524
525 unsigned long OSSLDSA::getMaxKeySize()
526 {
527 return OPENSSL_DSA_MAX_MODULUS_BITS;
528 }
529
530 bool OSSLDSA::generateParameters(AsymmetricParameters** ppParams, void* parameters /* = NULL */, RNG* /*rng = NULL*/)
531 {
532 if ((ppParams == NULL) || (parameters == NULL))
533 {
534 return false;
535 }
536
537 size_t bitLen = (size_t) parameters;
538
539 if (bitLen < getMinKeySize() || bitLen > getMaxKeySize())
540 {
541 ERROR_MSG("This DSA key size is not supported");
542
543 return false;
544 }
545
546 DSA* dsa = DSA_new();
547
548 if (dsa == NULL ||
549 !DSA_generate_parameters_ex(dsa, bitLen, NULL, 0, NULL, NULL, NULL))
550 {
551 ERROR_MSG("Failed to generate %d bit DSA parameters", bitLen);
552
553 return false;
554 }
555
556 // Store the DSA parameters
557 DSAParameters* params = new DSAParameters();
558
559 const BIGNUM* bn_p = NULL;
560 const BIGNUM* bn_q = NULL;
561 const BIGNUM* bn_g = NULL;
562 DSA_get0_pqg(dsa, &bn_p, &bn_q, &bn_g);
563
564 ByteString p = OSSL::bn2ByteString(bn_p); params->setP(p);
565 ByteString q = OSSL::bn2ByteString(bn_q); params->setQ(q);
566 ByteString g = OSSL::bn2ByteString(bn_g); params->setG(g);
567
568 *ppParams = params;
569
570 DSA_free(dsa);
571
572 return true;
573 }
574
575 bool OSSLDSA::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData)
576 {
577 // Check input
578 if ((ppKeyPair == NULL) ||
579 (serialisedData.size() == 0))
580 {
581 return false;
582 }
583
584 ByteString dPub = ByteString::chainDeserialise(serialisedData);
585 ByteString dPriv = ByteString::chainDeserialise(serialisedData);
586
587 OSSLDSAKeyPair* kp = new OSSLDSAKeyPair();
588
589 bool rv = true;
590
591 if (!((DSAPublicKey*) kp->getPublicKey())->deserialise(dPub))
592 {
593 rv = false;
594 }
595
596 if (!((DSAPrivateKey*) kp->getPrivateKey())->deserialise(dPriv))
597 {
598 rv = false;
599 }
600
601 if (!rv)
602 {
603 delete kp;
604
605 return false;
606 }
607
608 *ppKeyPair = kp;
609
610 return true;
611 }
612
613 bool OSSLDSA::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData)
614 {
615 // Check input
616 if ((ppPublicKey == NULL) ||
617 (serialisedData.size() == 0))
618 {
619 return false;
620 }
621
622 OSSLDSAPublicKey* pub = new OSSLDSAPublicKey();
623
624 if (!pub->deserialise(serialisedData))
625 {
626 delete pub;
627
628 return false;
629 }
630
631 *ppPublicKey = pub;
632
633 return true;
634 }
635
636 bool OSSLDSA::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData)
637 {
638 // Check input
639 if ((ppPrivateKey == NULL) ||
640 (serialisedData.size() == 0))
641 {
642 return false;
643 }
644
645 OSSLDSAPrivateKey* priv = new OSSLDSAPrivateKey();
646
647 if (!priv->deserialise(serialisedData))
648 {
649 delete priv;
650
651 return false;
652 }
653
654 *ppPrivateKey = priv;
655
656 return true;
657 }
658
659 PublicKey* OSSLDSA::newPublicKey()
660 {
661 return (PublicKey*) new OSSLDSAPublicKey();
662 }
663
664 PrivateKey* OSSLDSA::newPrivateKey()
665 {
666 return (PrivateKey*) new OSSLDSAPrivateKey();
667 }
668
669 AsymmetricParameters* OSSLDSA::newParameters()
670 {
671 return (AsymmetricParameters*) new DSAParameters();
672 }
673
674 bool OSSLDSA::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData)
675 {
676 // Check input parameters
677 if ((ppParams == NULL) || (serialisedData.size() == 0))
678 {
679 return false;
680 }
681
682 DSAParameters* params = new DSAParameters();
683
684 if (!params->deserialise(serialisedData))
685 {
686 delete params;
687
688 return false;
689 }
690
691 *ppParams = params;
692
693 return true;
694 }
695