1# coding: utf-8
2from __future__ import unicode_literals, division, absolute_import, print_function
3
4import hashlib
5
6from .._asn1 import (
7 Certificate as Asn1Certificate,
8 DHParameters,
9 ECDomainParameters,
10 PrivateKeyInfo,
11 PublicKeyAlgorithm,
12 PublicKeyInfo,
13)
14from .._asymmetric import (
15 _CertificateBase,
16 _fingerprint,
17 _parse_pkcs12,
18 _PrivateKeyBase,
19 _PublicKeyBase,
20 _unwrap_private_key_info,
21 parse_certificate,
22 parse_private,
23 parse_public,
24)
25from .._errors import pretty_message
26from .._ffi import (
27 buffer_from_bytes,
28 buffer_pointer,
29 bytes_from_buffer,
30 deref,
31 is_null,
32 new,
33 null,
34 unwrap,
35 write_to_buffer,
36)
37from ._libcrypto import (
38 get_first_openssl_error,
39 handle_openssl_error,
40 libcrypto,
41 LibcryptoConst,
42 libcrypto_version_info,
43 raise_openssl_error,
44)
45from ..errors import AsymmetricKeyError, IncompleteAsymmetricKeyError, SignatureError
46from .._types import type_name, str_cls, byte_cls, int_types
47from ..util import constant_compare
48
49
50__all__ = [
51 'Certificate',
52 'dsa_sign',
53 'dsa_verify',
54 'ecdsa_sign',
55 'ecdsa_verify',
56 'generate_pair',
57 'load_certificate',
58 'load_pkcs12',
59 'load_private_key',
60 'load_public_key',
61 'parse_pkcs12',
62 'PrivateKey',
63 'PublicKey',
64 'rsa_oaep_decrypt',
65 'rsa_oaep_encrypt',
66 'rsa_pkcs1v15_decrypt',
67 'rsa_pkcs1v15_encrypt',
68 'rsa_pkcs1v15_sign',
69 'rsa_pkcs1v15_verify',
70 'rsa_pss_sign',
71 'rsa_pss_verify',
72]
73
74
75class PrivateKey(_PrivateKeyBase):
76 """
77 Container for the OpenSSL representation of a private key
78 """
79
80 evp_pkey = None
81 _public_key = None
82
83 # A reference to the library used in the destructor to make sure it hasn't
84 # been garbage collected by the time this object is garbage collected
85 _lib = None
86
87 def __init__(self, evp_pkey, asn1):
88 """
89 :param evp_pkey:
90 An OpenSSL EVP_PKEY value from loading/importing the key
91
92 :param asn1:
93 An asn1crypto.keys.PrivateKeyInfo object
94 """
95
96 self.evp_pkey = evp_pkey
97 self.asn1 = asn1
98 self._lib = libcrypto
99
100 @property
101 def public_key(self):
102 """
103 :return:
104 A PublicKey object corresponding to this private key.
105 """
106
107 if self._public_key is None:
108 buffer_size = libcrypto.i2d_PUBKEY(self.evp_pkey, null())
109 pubkey_buffer = buffer_from_bytes(buffer_size)
110 pubkey_pointer = buffer_pointer(pubkey_buffer)
111 pubkey_length = libcrypto.i2d_PUBKEY(self.evp_pkey, pubkey_pointer)
112 handle_openssl_error(pubkey_length)
113 pubkey_data = bytes_from_buffer(pubkey_buffer, pubkey_length)
114
115 asn1 = PublicKeyInfo.load(pubkey_data)
116
117 # OpenSSL 1.x suffers from issues trying to use RSASSA-PSS keys, so we
118 # masquerade it as a normal RSA key so the OID checks work
119 if libcrypto_version_info < (3,) and asn1.algorithm == 'rsassa_pss':
120 temp_asn1 = asn1.copy()
121 temp_asn1['algorithm']['algorithm'] = 'rsa'
122 temp_data = temp_asn1.dump()
123 write_to_buffer(pubkey_buffer, temp_data)
124 pubkey_length = len(temp_data)
125
126 pub_evp_pkey = libcrypto.d2i_PUBKEY(null(), buffer_pointer(pubkey_buffer), pubkey_length)
127 if is_null(pub_evp_pkey):
128 handle_openssl_error(0)
129
130 self._public_key = PublicKey(pub_evp_pkey, asn1)
131
132 return self._public_key
133
134 @property
135 def fingerprint(self):
136 """
137 Creates a fingerprint that can be compared with a public key to see if
138 the two form a pair.
139
140 This fingerprint is not compatible with fingerprints generated by any
141 other software.
142
143 :return:
144 A byte string that is a sha256 hash of selected components (based
145 on the key type)
146 """
147
148 if self._fingerprint is None:
149 self._fingerprint = _fingerprint(self.asn1, load_private_key)
150 return self._fingerprint
151
152 def __del__(self):
153 if self.evp_pkey:
154 self._lib.EVP_PKEY_free(self.evp_pkey)
155 self._lib = None
156 self.evp_pkey = None
157
158
159class PublicKey(_PublicKeyBase):
160 """
161 Container for the OpenSSL representation of a public key
162 """
163
164 evp_pkey = None
165
166 # A reference to the library used in the destructor to make sure it hasn't
167 # been garbage collected by the time this object is garbage collected
168 _lib = None
169
170 def __init__(self, evp_pkey, asn1):
171 """
172 :param evp_pkey:
173 An OpenSSL EVP_PKEY value from loading/importing the key
174
175 :param asn1:
176 An asn1crypto.keys.PublicKeyInfo object
177 """
178
179 self.evp_pkey = evp_pkey
180 self.asn1 = asn1
181 self._lib = libcrypto
182
183 def __del__(self):
184 if self.evp_pkey:
185 self._lib.EVP_PKEY_free(self.evp_pkey)
186 self._lib = None
187 self.evp_pkey = None
188
189
190class Certificate(_CertificateBase):
191 """
192 Container for the OpenSSL representation of a certificate
193 """
194
195 x509 = None
196 _public_key = None
197 _self_signed = None
198
199 # A reference to the library used in the destructor to make sure it hasn't
200 # been garbage collected by the time this object is garbage collected
201 _lib = None
202
203 def __init__(self, x509, asn1):
204 """
205 :param x509:
206 An OpenSSL X509 value from loading/importing the certificate
207
208 :param asn1:
209 An asn1crypto.x509.Certificate object
210 """
211
212 self.x509 = x509
213 self.asn1 = asn1
214 self._lib = libcrypto
215
216 @property
217 def evp_pkey(self):
218 """
219 :return:
220 The EVP_PKEY of the public key this certificate contains
221 """
222
223 return self.public_key.evp_pkey
224
225 @property
226 def public_key(self):
227 """
228 :return:
229 The PublicKey object for the public key this certificate contains
230 """
231
232 if not self._public_key and self.x509:
233 # OpenSSL 1.x suffers from issues trying to use RSASSA-PSS keys, so we
234 # masquerade it as a normal RSA key so the OID checks work
235 if libcrypto_version_info < (3,) and self.asn1.public_key.algorithm == 'rsassa_pss':
236 self._public_key = load_public_key(self.asn1.public_key)
237 else:
238 evp_pkey = libcrypto.X509_get_pubkey(self.x509)
239 self._public_key = PublicKey(evp_pkey, self.asn1.public_key)
240
241 return self._public_key
242
243 @property
244 def self_signed(self):
245 """
246 :return:
247 A boolean - if the certificate is self-signed
248 """
249
250 if self._self_signed is None:
251 self._self_signed = False
252 if self.asn1.self_signed in set(['yes', 'maybe']):
253
254 signature_algo = self.asn1['signature_algorithm'].signature_algo
255 hash_algo = self.asn1['signature_algorithm'].hash_algo
256
257 if signature_algo == 'rsassa_pkcs1v15':
258 verify_func = rsa_pkcs1v15_verify
259 elif signature_algo == 'rsassa_pss':
260 verify_func = rsa_pss_verify
261 elif signature_algo == 'dsa':
262 verify_func = dsa_verify
263 elif signature_algo == 'ecdsa':
264 verify_func = ecdsa_verify
265 else:
266 raise OSError(pretty_message(
267 '''
268 Unable to verify the signature of the certificate since
269 it uses the unsupported algorithm %s
270 ''',
271 signature_algo
272 ))
273
274 try:
275 verify_func(
276 self.public_key,
277 self.asn1['signature_value'].native,
278 self.asn1['tbs_certificate'].dump(),
279 hash_algo
280 )
281 self._self_signed = True
282 except (SignatureError):
283 pass
284
285 return self._self_signed
286
287 def __del__(self):
288 if self._public_key:
289 self._public_key.__del__()
290 self._public_key = None
291
292 if self.x509:
293 self._lib.X509_free(self.x509)
294 self._lib = None
295 self.x509 = None
296
297
298def generate_pair(algorithm, bit_size=None, curve=None):
299 """
300 Generates a public/private key pair
301
302 :param algorithm:
303 The key algorithm - "rsa", "dsa" or "ec"
304
305 :param bit_size:
306 An integer - used for "rsa" and "dsa". For "rsa" the value maye be 1024,
307 2048, 3072 or 4096. For "dsa" the value may be 1024, plus 2048 or 3072
308 if OpenSSL 1.0.0 or newer is available.
309
310 :param curve:
311 A unicode string - used for "ec" keys. Valid values include "secp256r1",
312 "secp384r1" and "secp521r1".
313
314 :raises:
315 ValueError - when any of the parameters contain an invalid value
316 TypeError - when any of the parameters are of the wrong type
317 OSError - when an error is returned by the OS crypto library
318
319 :return:
320 A 2-element tuple of (PublicKey, PrivateKey). The contents of each key
321 may be saved by calling .asn1.dump().
322 """
323
324 if algorithm not in set(['rsa', 'dsa', 'ec']):
325 raise ValueError(pretty_message(
326 '''
327 algorithm must be one of "rsa", "dsa", "ec", not %s
328 ''',
329 repr(algorithm)
330 ))
331
332 if algorithm == 'rsa':
333 if bit_size not in set([1024, 2048, 3072, 4096]):
334 raise ValueError(pretty_message(
335 '''
336 bit_size must be one of 1024, 2048, 3072, 4096, not %s
337 ''',
338 repr(bit_size)
339 ))
340
341 elif algorithm == 'dsa':
342 if libcrypto_version_info < (1,):
343 if bit_size != 1024:
344 raise ValueError(pretty_message(
345 '''
346 bit_size must be 1024, not %s
347 ''',
348 repr(bit_size)
349 ))
350 else:
351 if bit_size not in set([1024, 2048, 3072]):
352 raise ValueError(pretty_message(
353 '''
354 bit_size must be one of 1024, 2048, 3072, not %s
355 ''',
356 repr(bit_size)
357 ))
358
359 elif algorithm == 'ec':
360 if curve not in set(['secp256r1', 'secp384r1', 'secp521r1']):
361 raise ValueError(pretty_message(
362 '''
363 curve must be one of "secp256r1", "secp384r1", "secp521r1",
364 not %s
365 ''',
366 repr(curve)
367 ))
368
369 if algorithm == 'rsa':
370 rsa = None
371 exponent = None
372
373 try:
374 rsa = libcrypto.RSA_new()
375 if is_null(rsa):
376 handle_openssl_error(0)
377
378 exponent_pointer = new(libcrypto, 'BIGNUM **')
379 result = libcrypto.BN_dec2bn(exponent_pointer, b'65537')
380 handle_openssl_error(result)
381 exponent = unwrap(exponent_pointer)
382
383 result = libcrypto.RSA_generate_key_ex(rsa, bit_size, exponent, null())
384 handle_openssl_error(result)
385
386 buffer_length = libcrypto.i2d_RSAPublicKey(rsa, null())
387 if buffer_length < 0:
388 handle_openssl_error(buffer_length)
389 buffer = buffer_from_bytes(buffer_length)
390 result = libcrypto.i2d_RSAPublicKey(rsa, buffer_pointer(buffer))
391 if result < 0:
392 handle_openssl_error(result)
393 public_key_bytes = bytes_from_buffer(buffer, buffer_length)
394
395 buffer_length = libcrypto.i2d_RSAPrivateKey(rsa, null())
396 if buffer_length < 0:
397 handle_openssl_error(buffer_length)
398 buffer = buffer_from_bytes(buffer_length)
399 result = libcrypto.i2d_RSAPrivateKey(rsa, buffer_pointer(buffer))
400 if result < 0:
401 handle_openssl_error(result)
402 private_key_bytes = bytes_from_buffer(buffer, buffer_length)
403
404 finally:
405 if rsa:
406 libcrypto.RSA_free(rsa)
407 if exponent:
408 libcrypto.BN_free(exponent)
409
410 elif algorithm == 'dsa':
411 dsa = None
412
413 try:
414 dsa = libcrypto.DSA_new()
415 if is_null(dsa):
416 handle_openssl_error(0)
417
418 result = libcrypto.DSA_generate_parameters_ex(dsa, bit_size, null(), 0, null(), null(), null())
419 handle_openssl_error(result)
420
421 result = libcrypto.DSA_generate_key(dsa)
422 handle_openssl_error(result)
423
424 buffer_length = libcrypto.i2d_DSA_PUBKEY(dsa, null())
425 if buffer_length < 0:
426 handle_openssl_error(buffer_length)
427 buffer = buffer_from_bytes(buffer_length)
428 result = libcrypto.i2d_DSA_PUBKEY(dsa, buffer_pointer(buffer))
429 if result < 0:
430 handle_openssl_error(result)
431 public_key_bytes = bytes_from_buffer(buffer, buffer_length)
432
433 buffer_length = libcrypto.i2d_DSAPrivateKey(dsa, null())
434 if buffer_length < 0:
435 handle_openssl_error(buffer_length)
436 buffer = buffer_from_bytes(buffer_length)
437 result = libcrypto.i2d_DSAPrivateKey(dsa, buffer_pointer(buffer))
438 if result < 0:
439 handle_openssl_error(result)
440 private_key_bytes = bytes_from_buffer(buffer, buffer_length)
441
442 finally:
443 if dsa:
444 libcrypto.DSA_free(dsa)
445
446 elif algorithm == 'ec':
447 ec_key = None
448
449 try:
450 curve_id = {
451 'secp256r1': LibcryptoConst.NID_X9_62_prime256v1,
452 'secp384r1': LibcryptoConst.NID_secp384r1,
453 'secp521r1': LibcryptoConst.NID_secp521r1,
454 }[curve]
455
456 ec_key = libcrypto.EC_KEY_new_by_curve_name(curve_id)
457 if is_null(ec_key):
458 handle_openssl_error(0)
459
460 result = libcrypto.EC_KEY_generate_key(ec_key)
461 handle_openssl_error(result)
462
463 libcrypto.EC_KEY_set_asn1_flag(ec_key, LibcryptoConst.OPENSSL_EC_NAMED_CURVE)
464
465 buffer_length = libcrypto.i2o_ECPublicKey(ec_key, null())
466 if buffer_length < 0:
467 handle_openssl_error(buffer_length)
468 buffer = buffer_from_bytes(buffer_length)
469 result = libcrypto.i2o_ECPublicKey(ec_key, buffer_pointer(buffer))
470 if result < 0:
471 handle_openssl_error(result)
472 public_key_point_bytes = bytes_from_buffer(buffer, buffer_length)
473
474 # i2o_ECPublicKey only returns the ECPoint bytes, so we have to
475 # manually wrap it in a PublicKeyInfo structure to get it to parse
476 public_key = PublicKeyInfo({
477 'algorithm': PublicKeyAlgorithm({
478 'algorithm': 'ec',
479 'parameters': ECDomainParameters(
480 name='named',
481 value=curve
482 )
483 }),
484 'public_key': public_key_point_bytes
485 })
486 public_key_bytes = public_key.dump()
487
488 buffer_length = libcrypto.i2d_ECPrivateKey(ec_key, null())
489 if buffer_length < 0:
490 handle_openssl_error(buffer_length)
491 buffer = buffer_from_bytes(buffer_length)
492 result = libcrypto.i2d_ECPrivateKey(ec_key, buffer_pointer(buffer))
493 if result < 0:
494 handle_openssl_error(result)
495 private_key_bytes = bytes_from_buffer(buffer, buffer_length)
496
497 finally:
498 if ec_key:
499 libcrypto.EC_KEY_free(ec_key)
500
501 return (load_public_key(public_key_bytes), load_private_key(private_key_bytes))
502
503
504def generate_dh_parameters(bit_size):
505 """
506 Generates DH parameters for use with Diffie-Hellman key exchange. Returns
507 a structure in the format of DHParameter defined in PKCS#3, which is also
508 used by the OpenSSL dhparam tool.
509
510 THIS CAN BE VERY TIME CONSUMING!
511
512 :param bit_size:
513 The integer bit size of the parameters to generate. Must be between 512
514 and 4096, and divisible by 64. Recommended secure value as of early 2016
515 is 2048, with an absolute minimum of 1024.
516
517 :raises:
518 ValueError - when any of the parameters contain an invalid value
519 TypeError - when any of the parameters are of the wrong type
520 OSError - when an error is returned by the OS crypto library
521
522 :return:
523 An asn1crypto.algos.DHParameters object. Use
524 oscrypto.asymmetric.dump_dh_parameters() to save to disk for usage with
525 web servers.
526 """
527
528 if not isinstance(bit_size, int_types):
529 raise TypeError(pretty_message(
530 '''
531 bit_size must be an integer, not %s
532 ''',
533 type_name(bit_size)
534 ))
535
536 if bit_size < 512:
537 raise ValueError('bit_size must be greater than or equal to 512')
538
539 if bit_size > 4096:
540 raise ValueError('bit_size must be less than or equal to 4096')
541
542 if bit_size % 64 != 0:
543 raise ValueError('bit_size must be a multiple of 64')
544
545 dh = None
546
547 try:
548 dh = libcrypto.DH_new()
549 if is_null(dh):
550 handle_openssl_error(0)
551
552 result = libcrypto.DH_generate_parameters_ex(dh, bit_size, LibcryptoConst.DH_GENERATOR_2, null())
553 handle_openssl_error(result)
554
555 buffer_length = libcrypto.i2d_DHparams(dh, null())
556 if buffer_length < 0:
557 handle_openssl_error(buffer_length)
558 buffer = buffer_from_bytes(buffer_length)
559 result = libcrypto.i2d_DHparams(dh, buffer_pointer(buffer))
560 if result < 0:
561 handle_openssl_error(result)
562 dh_params_bytes = bytes_from_buffer(buffer, buffer_length)
563
564 return DHParameters.load(dh_params_bytes)
565
566 finally:
567 if dh:
568 libcrypto.DH_free(dh)
569
570
571def load_certificate(source):
572 """
573 Loads an x509 certificate into a Certificate object
574
575 :param source:
576 A byte string of file contents, a unicode string filename or an
577 asn1crypto.x509.Certificate object
578
579 :raises:
580 ValueError - when any of the parameters contain an invalid value
581 TypeError - when any of the parameters are of the wrong type
582 OSError - when an error is returned by the OS crypto library
583
584 :return:
585 A Certificate object
586 """
587
588 if isinstance(source, Asn1Certificate):
589 certificate = source
590
591 elif isinstance(source, byte_cls):
592 certificate = parse_certificate(source)
593
594 elif isinstance(source, str_cls):
595 with open(source, 'rb') as f:
596 certificate = parse_certificate(f.read())
597
598 else:
599 raise TypeError(pretty_message(
600 '''
601 source must be a byte string, unicode string or
602 asn1crypto.x509.Certificate object, not %s
603 ''',
604 type_name(source)
605 ))
606
607 return _load_x509(certificate)
608
609
610def _load_x509(certificate):
611 """
612 Loads an ASN.1 object of an x509 certificate into a Certificate object
613
614 :param certificate:
615 An asn1crypto.x509.Certificate object
616
617 :return:
618 A Certificate object
619 """
620
621 source = certificate.dump()
622
623 buffer = buffer_from_bytes(source)
624 evp_pkey = libcrypto.d2i_X509(null(), buffer_pointer(buffer), len(source))
625 if is_null(evp_pkey):
626 handle_openssl_error(0)
627 return Certificate(evp_pkey, certificate)
628
629
630def load_private_key(source, password=None):
631 """
632 Loads a private key into a PrivateKey object
633
634 :param source:
635 A byte string of file contents, a unicode string filename or an
636 asn1crypto.keys.PrivateKeyInfo object
637
638 :param password:
639 A byte or unicode string to decrypt the private key file. Unicode
640 strings will be encoded using UTF-8. Not used is the source is a
641 PrivateKeyInfo object.
642
643 :raises:
644 ValueError - when any of the parameters contain an invalid value
645 TypeError - when any of the parameters are of the wrong type
646 oscrypto.errors.AsymmetricKeyError - when the private key is incompatible with the OS crypto library
647 OSError - when an error is returned by the OS crypto library
648
649 :return:
650 A PrivateKey object
651 """
652
653 if isinstance(source, PrivateKeyInfo):
654 private_object = source
655
656 else:
657 if password is not None:
658 if isinstance(password, str_cls):
659 password = password.encode('utf-8')
660 if not isinstance(password, byte_cls):
661 raise TypeError(pretty_message(
662 '''
663 password must be a byte string, not %s
664 ''',
665 type_name(password)
666 ))
667
668 if isinstance(source, str_cls):
669 with open(source, 'rb') as f:
670 source = f.read()
671
672 elif not isinstance(source, byte_cls):
673 raise TypeError(pretty_message(
674 '''
675 source must be a byte string, unicode string or
676 asn1crypto.keys.PrivateKeyInfo object, not %s
677 ''',
678 type_name(source)
679 ))
680
681 private_object = parse_private(source, password)
682
683 return _load_key(private_object)
684
685
686def load_public_key(source):
687 """
688 Loads a public key into a PublicKey object
689
690 :param source:
691 A byte string of file contents, a unicode string filename or an
692 asn1crypto.keys.PublicKeyInfo object
693
694 :raises:
695 ValueError - when any of the parameters contain an invalid value
696 TypeError - when any of the parameters are of the wrong type
697 oscrypto.errors.AsymmetricKeyError - when the public key is incompatible with the OS crypto library
698 OSError - when an error is returned by the OS crypto library
699
700 :return:
701 A PublicKey object
702 """
703
704 if isinstance(source, PublicKeyInfo):
705 public_key = source
706
707 elif isinstance(source, byte_cls):
708 public_key = parse_public(source)
709
710 elif isinstance(source, str_cls):
711 with open(source, 'rb') as f:
712 public_key = parse_public(f.read())
713
714 else:
715 raise TypeError(pretty_message(
716 '''
717 source must be a byte string, unicode string or
718 asn1crypto.keys.PublicKeyInfo object, not %s
719 ''',
720 type_name(source)
721 ))
722
723 if public_key.algorithm == 'dsa':
724 if libcrypto_version_info < (1,) and public_key.hash_algo == 'sha2':
725 raise AsymmetricKeyError(pretty_message(
726 '''
727 OpenSSL 0.9.8 only supports DSA keys based on SHA1 (2048 bits or
728 less) - this key is based on SHA2 and is %s bits
729 ''',
730 public_key.bit_size
731 ))
732 elif public_key.hash_algo is None:
733 raise IncompleteAsymmetricKeyError(pretty_message(
734 '''
735 The DSA key does not contain the necessary p, q and g
736 parameters and can not be used
737 '''
738 ))
739
740 # OpenSSL 1.x suffers from issues trying to use RSASSA-PSS keys, so we
741 # masquerade it as a normal RSA key so the OID checks work
742 if libcrypto_version_info < (3,) and public_key.algorithm == 'rsassa_pss':
743 temp_key = public_key.copy()
744 temp_key['algorithm']['algorithm'] = 'rsa'
745 data = temp_key.dump()
746 else:
747 data = public_key.dump()
748
749 buffer = buffer_from_bytes(data)
750 evp_pkey = libcrypto.d2i_PUBKEY(null(), buffer_pointer(buffer), len(data))
751 if is_null(evp_pkey):
752 handle_openssl_error(0)
753 return PublicKey(evp_pkey, public_key)
754
755
756def _load_key(private_object):
757 """
758 Loads a private key into a PrivateKey object
759
760 :param private_object:
761 An asn1crypto.keys.PrivateKeyInfo object
762
763 :return:
764 A PrivateKey object
765 """
766
767 if libcrypto_version_info < (1,) and private_object.algorithm == 'dsa' and private_object.hash_algo == 'sha2':
768 raise AsymmetricKeyError(pretty_message(
769 '''
770 OpenSSL 0.9.8 only supports DSA keys based on SHA1 (2048 bits or
771 less) - this key is based on SHA2 and is %s bits
772 ''',
773 private_object.bit_size
774 ))
775
776 source = _unwrap_private_key_info(private_object).dump()
777
778 buffer = buffer_from_bytes(source)
779 evp_pkey = libcrypto.d2i_AutoPrivateKey(null(), buffer_pointer(buffer), len(source))
780 if is_null(evp_pkey):
781 handle_openssl_error(0)
782 return PrivateKey(evp_pkey, private_object)
783
784
785def parse_pkcs12(data, password=None):
786 """
787 Parses a PKCS#12 ANS.1 DER-encoded structure and extracts certs and keys
788
789 :param data:
790 A byte string of a DER-encoded PKCS#12 file
791
792 :param password:
793 A byte string of the password to any encrypted data
794
795 :raises:
796 ValueError - when any of the parameters are of the wrong type or value
797 OSError - when an error is returned by one of the OS decryption functions
798
799 :return:
800 A three-element tuple of:
801 1. An asn1crypto.keys.PrivateKeyInfo object
802 2. An asn1crypto.x509.Certificate object
803 3. A list of zero or more asn1crypto.x509.Certificate objects that are
804 "extra" certificates, possibly intermediates from the cert chain
805 """
806
807 return _parse_pkcs12(data, password, load_private_key)
808
809
810def load_pkcs12(source, password=None):
811 """
812 Loads a .p12 or .pfx file into a PrivateKey object and one or more
813 Certificates objects
814
815 :param source:
816 A byte string of file contents or a unicode string filename
817
818 :param password:
819 A byte or unicode string to decrypt the PKCS12 file. Unicode strings
820 will be encoded using UTF-8.
821
822 :raises:
823 ValueError - when any of the parameters contain an invalid value
824 TypeError - when any of the parameters are of the wrong type
825 oscrypto.errors.AsymmetricKeyError - when a contained key is incompatible with the OS crypto library
826 OSError - when an error is returned by the OS crypto library
827
828 :return:
829 A three-element tuple containing (PrivateKey, Certificate, [Certificate, ...])
830 """
831
832 if password is not None:
833 if isinstance(password, str_cls):
834 password = password.encode('utf-8')
835 if not isinstance(password, byte_cls):
836 raise TypeError(pretty_message(
837 '''
838 password must be a byte string, not %s
839 ''',
840 type_name(password)
841 ))
842
843 if isinstance(source, str_cls):
844 with open(source, 'rb') as f:
845 source = f.read()
846
847 elif not isinstance(source, byte_cls):
848 raise TypeError(pretty_message(
849 '''
850 source must be a byte string or a unicode string, not %s
851 ''',
852 type_name(source)
853 ))
854
855 key_info, cert_info, extra_certs_info = parse_pkcs12(source, password)
856
857 key = None
858 cert = None
859
860 if key_info:
861 key = _load_key(key_info)
862
863 if cert_info:
864 cert = _load_x509(cert_info)
865
866 extra_certs = [_load_x509(info) for info in extra_certs_info]
867
868 return (key, cert, extra_certs)
869
870
871def rsa_pkcs1v15_encrypt(certificate_or_public_key, data):
872 """
873 Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1
874 v1.5 padding.
875
876 :param certificate_or_public_key:
877 A PublicKey or Certificate object
878
879 :param data:
880 A byte string, with a maximum length 11 bytes less than the key length
881 (in bytes)
882
883 :raises:
884 ValueError - when any of the parameters contain an invalid value
885 TypeError - when any of the parameters are of the wrong type
886 OSError - when an error is returned by the OS crypto library
887
888 :return:
889 A byte string of the encrypted data
890 """
891
892 return _encrypt(certificate_or_public_key, data, LibcryptoConst.RSA_PKCS1_PADDING)
893
894
895def rsa_pkcs1v15_decrypt(private_key, ciphertext):
896 """
897 Decrypts a byte string using an RSA private key. Uses PKCS#1 v1.5 padding.
898
899 :param private_key:
900 A PrivateKey object
901
902 :param ciphertext:
903 A byte string of the encrypted data
904
905 :raises:
906 ValueError - when any of the parameters contain an invalid value
907 TypeError - when any of the parameters are of the wrong type
908 OSError - when an error is returned by the OS crypto library
909
910 :return:
911 A byte string of the original plaintext
912 """
913
914 return _decrypt(private_key, ciphertext, LibcryptoConst.RSA_PKCS1_PADDING)
915
916
917def rsa_oaep_encrypt(certificate_or_public_key, data):
918 """
919 Encrypts a byte string using an RSA public key or certificate. Uses PKCS#1
920 OAEP padding with SHA1.
921
922 :param certificate_or_public_key:
923 A PublicKey or Certificate object
924
925 :param data:
926 A byte string, with a maximum length 41 bytes (or more) less than the
927 key length (in bytes)
928
929 :raises:
930 ValueError - when any of the parameters contain an invalid value
931 TypeError - when any of the parameters are of the wrong type
932 OSError - when an error is returned by the OS crypto library
933
934 :return:
935 A byte string of the encrypted data
936 """
937
938 return _encrypt(certificate_or_public_key, data, LibcryptoConst.RSA_PKCS1_OAEP_PADDING)
939
940
941def rsa_oaep_decrypt(private_key, ciphertext):
942 """
943 Decrypts a byte string using an RSA private key. Uses PKCS#1 OAEP padding
944 with SHA1.
945
946 :param private_key:
947 A PrivateKey object
948
949 :param ciphertext:
950 A byte string of the encrypted data
951
952 :raises:
953 ValueError - when any of the parameters contain an invalid value
954 TypeError - when any of the parameters are of the wrong type
955 OSError - when an error is returned by the OS crypto library
956
957 :return:
958 A byte string of the original plaintext
959 """
960
961 return _decrypt(private_key, ciphertext, LibcryptoConst.RSA_PKCS1_OAEP_PADDING)
962
963
964def _evp_pkey_get_size(evp_pkey):
965 """
966 Handles the function name change from OpenSSL 1.1 -> 3.0
967
968 :param evp_pkey:
969 The EVP_PKEY of the Certificte or PublicKey to get the size of
970
971 :return:
972 An int of the number of bytes necessary for the key
973 """
974
975 if libcrypto_version_info < (3, ):
976 return libcrypto.EVP_PKEY_size(evp_pkey)
977 return libcrypto.EVP_PKEY_get_size(evp_pkey)
978
979
980def _encrypt(certificate_or_public_key, data, padding):
981 """
982 Encrypts plaintext using an RSA public key or certificate
983
984 :param certificate_or_public_key:
985 A PublicKey, Certificate or PrivateKey object
986
987 :param data:
988 The byte string to encrypt
989
990 :param padding:
991 The padding mode to use
992
993 :raises:
994 ValueError - when any of the parameters contain an invalid value
995 TypeError - when any of the parameters are of the wrong type
996 OSError - when an error is returned by the OS crypto library
997
998 :return:
999 A byte string of the encrypted data
1000 """
1001
1002 if not isinstance(certificate_or_public_key, (Certificate, PublicKey)):
1003 raise TypeError(pretty_message(
1004 '''
1005 certificate_or_public_key must be an instance of the Certificate or
1006 PublicKey class, not %s
1007 ''',
1008 type_name(certificate_or_public_key)
1009 ))
1010
1011 if not isinstance(data, byte_cls):
1012 raise TypeError(pretty_message(
1013 '''
1014 data must be a byte string, not %s
1015 ''',
1016 type_name(data)
1017 ))
1018
1019 rsa = None
1020
1021 try:
1022 buffer_size = _evp_pkey_get_size(certificate_or_public_key.evp_pkey)
1023 buffer = buffer_from_bytes(buffer_size)
1024
1025 rsa = libcrypto.EVP_PKEY_get1_RSA(certificate_or_public_key.evp_pkey)
1026 res = libcrypto.RSA_public_encrypt(len(data), data, buffer, rsa, padding)
1027 handle_openssl_error(res)
1028
1029 return bytes_from_buffer(buffer, res)
1030
1031 finally:
1032 if rsa:
1033 libcrypto.RSA_free(rsa)
1034
1035
1036def _decrypt(private_key, ciphertext, padding):
1037 """
1038 Decrypts RSA ciphertext using a private key
1039
1040 :param private_key:
1041 A PrivateKey object
1042
1043 :param ciphertext:
1044 The ciphertext - a byte string
1045
1046 :param padding:
1047 The padding mode to use
1048
1049 :raises:
1050 ValueError - when any of the parameters contain an invalid value
1051 TypeError - when any of the parameters are of the wrong type
1052 OSError - when an error is returned by the OS crypto library
1053
1054 :return:
1055 A byte string of the plaintext
1056 """
1057
1058 if not isinstance(private_key, PrivateKey):
1059 raise TypeError(pretty_message(
1060 '''
1061 private_key must be an instance of the PrivateKey class, not %s
1062 ''',
1063 type_name(private_key)
1064 ))
1065
1066 if not isinstance(ciphertext, byte_cls):
1067 raise TypeError(pretty_message(
1068 '''
1069 ciphertext must be a byte string, not %s
1070 ''',
1071 type_name(ciphertext)
1072 ))
1073
1074 rsa = None
1075
1076 try:
1077 buffer_size = _evp_pkey_get_size(private_key.evp_pkey)
1078 buffer = buffer_from_bytes(buffer_size)
1079
1080 rsa = libcrypto.EVP_PKEY_get1_RSA(private_key.evp_pkey)
1081 res = libcrypto.RSA_private_decrypt(len(ciphertext), ciphertext, buffer, rsa, padding)
1082 handle_openssl_error(res)
1083
1084 return bytes_from_buffer(buffer, res)
1085
1086 finally:
1087 if rsa:
1088 libcrypto.RSA_free(rsa)
1089
1090
1091def rsa_pkcs1v15_verify(certificate_or_public_key, signature, data, hash_algorithm):
1092 """
1093 Verifies an RSASSA-PKCS-v1.5 signature.
1094
1095 When the hash_algorithm is "raw", the operation is identical to RSA
1096 public key decryption. That is: the data is not hashed and no ASN.1
1097 structure with an algorithm identifier of the hash algorithm is placed in
1098 the encrypted byte string.
1099
1100 :param certificate_or_public_key:
1101 A Certificate or PublicKey instance to verify the signature with
1102
1103 :param signature:
1104 A byte string of the signature to verify
1105
1106 :param data:
1107 A byte string of the data the signature is for
1108
1109 :param hash_algorithm:
1110 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384",
1111 "sha512" or "raw"
1112
1113 :raises:
1114 oscrypto.errors.SignatureError - when the signature is determined to be invalid
1115 ValueError - when any of the parameters contain an invalid value
1116 TypeError - when any of the parameters are of the wrong type
1117 OSError - when an error is returned by the OS crypto library
1118 """
1119
1120 if certificate_or_public_key.algorithm != 'rsa':
1121 raise ValueError(pretty_message(
1122 '''
1123 The key specified is not an RSA public key, but %s
1124 ''',
1125 certificate_or_public_key.algorithm.upper()
1126 ))
1127
1128 return _verify(certificate_or_public_key, signature, data, hash_algorithm)
1129
1130
1131def rsa_pss_verify(certificate_or_public_key, signature, data, hash_algorithm):
1132 """
1133 Verifies an RSASSA-PSS signature. For the PSS padding the mask gen algorithm
1134 will be mgf1 using the same hash algorithm as the signature, and the trailer
1135 field will be the standard 0xBC byte.
1136
1137 :param certificate_or_public_key:
1138 A Certificate or PublicKey instance to verify the signature with
1139
1140 :param signature:
1141 A byte string of the signature to verify
1142
1143 :param data:
1144 A byte string of the data the signature is for
1145
1146 :param hash_algorithm:
1147 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"
1148
1149 :raises:
1150 oscrypto.errors.SignatureError - when the signature is determined to be invalid
1151 ValueError - when any of the parameters contain an invalid value
1152 TypeError - when any of the parameters are of the wrong type
1153 OSError - when an error is returned by the OS crypto library
1154 """
1155
1156 cp_alg = certificate_or_public_key.algorithm
1157
1158 if cp_alg != 'rsa' and cp_alg != 'rsassa_pss':
1159 raise ValueError(pretty_message(
1160 '''
1161 The key specified is not an RSA public key, but %s
1162 ''',
1163 certificate_or_public_key.algorithm.upper()
1164 ))
1165
1166 return _verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=True)
1167
1168
1169def dsa_verify(certificate_or_public_key, signature, data, hash_algorithm):
1170 """
1171 Verifies a DSA signature
1172
1173 :param certificate_or_public_key:
1174 A Certificate or PublicKey instance to verify the signature with
1175
1176 :param signature:
1177 A byte string of the signature to verify
1178
1179 :param data:
1180 A byte string of the data the signature is for
1181
1182 :param hash_algorithm:
1183 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"
1184
1185 :raises:
1186 oscrypto.errors.SignatureError - when the signature is determined to be invalid
1187 ValueError - when any of the parameters contain an invalid value
1188 TypeError - when any of the parameters are of the wrong type
1189 OSError - when an error is returned by the OS crypto library
1190 """
1191
1192 if certificate_or_public_key.algorithm != 'dsa':
1193 raise ValueError(pretty_message(
1194 '''
1195 The key specified is not a DSA public key, but %s
1196 ''',
1197 certificate_or_public_key.algorithm.upper()
1198 ))
1199
1200 return _verify(certificate_or_public_key, signature, data, hash_algorithm)
1201
1202
1203def ecdsa_verify(certificate_or_public_key, signature, data, hash_algorithm):
1204 """
1205 Verifies an ECDSA signature
1206
1207 :param certificate_or_public_key:
1208 A Certificate or PublicKey instance to verify the signature with
1209
1210 :param signature:
1211 A byte string of the signature to verify
1212
1213 :param data:
1214 A byte string of the data the signature is for
1215
1216 :param hash_algorithm:
1217 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"
1218
1219 :raises:
1220 oscrypto.errors.SignatureError - when the signature is determined to be invalid
1221 ValueError - when any of the parameters contain an invalid value
1222 TypeError - when any of the parameters are of the wrong type
1223 OSError - when an error is returned by the OS crypto library
1224 """
1225
1226 if certificate_or_public_key.algorithm != 'ec':
1227 raise ValueError(pretty_message(
1228 '''
1229 The key specified is not an EC public key, but %s
1230 ''',
1231 certificate_or_public_key.algorithm.upper()
1232 ))
1233
1234 return _verify(certificate_or_public_key, signature, data, hash_algorithm)
1235
1236
1237def _verify(certificate_or_public_key, signature, data, hash_algorithm, rsa_pss_padding=False):
1238 """
1239 Verifies an RSA, DSA or ECDSA signature
1240
1241 :param certificate_or_public_key:
1242 A Certificate or PublicKey instance to verify the signature with
1243
1244 :param signature:
1245 A byte string of the signature to verify
1246
1247 :param data:
1248 A byte string of the data the signature is for
1249
1250 :param hash_algorithm:
1251 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"
1252
1253 :param rsa_pss_padding:
1254 If the certificate_or_public_key is an RSA key, this enables PSS padding
1255
1256 :raises:
1257 oscrypto.errors.SignatureError - when the signature is determined to be invalid
1258 ValueError - when any of the parameters contain an invalid value
1259 TypeError - when any of the parameters are of the wrong type
1260 OSError - when an error is returned by the OS crypto library
1261 """
1262
1263 if not isinstance(certificate_or_public_key, (Certificate, PublicKey)):
1264 raise TypeError(pretty_message(
1265 '''
1266 certificate_or_public_key must be an instance of the Certificate or
1267 PublicKey class, not %s
1268 ''',
1269 type_name(certificate_or_public_key)
1270 ))
1271
1272 if not isinstance(signature, byte_cls):
1273 raise TypeError(pretty_message(
1274 '''
1275 signature must be a byte string, not %s
1276 ''',
1277 type_name(signature)
1278 ))
1279
1280 if not isinstance(data, byte_cls):
1281 raise TypeError(pretty_message(
1282 '''
1283 data must be a byte string, not %s
1284 ''',
1285 type_name(data)
1286 ))
1287
1288 cp_alg = certificate_or_public_key.algorithm
1289 cp_is_rsa = cp_alg == 'rsa' or cp_alg == 'rsassa_pss'
1290
1291 valid_hash_algorithms = set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'])
1292 if cp_is_rsa and not rsa_pss_padding:
1293 valid_hash_algorithms |= set(['raw'])
1294
1295 if hash_algorithm not in valid_hash_algorithms:
1296 valid_hash_algorithms_error = '"md5", "sha1", "sha224", "sha256", "sha384", "sha512"'
1297 if cp_is_rsa and not rsa_pss_padding:
1298 valid_hash_algorithms_error += ', "raw"'
1299 raise ValueError(pretty_message(
1300 '''
1301 hash_algorithm must be one of %s, not %s
1302 ''',
1303 valid_hash_algorithms_error,
1304 repr(hash_algorithm)
1305 ))
1306
1307 if not cp_is_rsa and rsa_pss_padding:
1308 raise ValueError(pretty_message(
1309 '''
1310 PSS padding can only be used with RSA keys - the key provided is a
1311 %s key
1312 ''',
1313 cp_alg.upper()
1314 ))
1315
1316 if cp_is_rsa and hash_algorithm == 'raw':
1317 if len(data) > certificate_or_public_key.byte_size - 11:
1318 raise ValueError(pretty_message(
1319 '''
1320 data must be 11 bytes shorter than the key size when
1321 hash_algorithm is "raw" - key size is %s bytes, but data is
1322 %s bytes long
1323 ''',
1324 certificate_or_public_key.byte_size,
1325 len(data)
1326 ))
1327
1328 rsa = None
1329
1330 try:
1331 rsa = libcrypto.EVP_PKEY_get1_RSA(certificate_or_public_key.evp_pkey)
1332 if is_null(rsa):
1333 handle_openssl_error(0)
1334
1335 buffer_size = _evp_pkey_get_size(certificate_or_public_key.evp_pkey)
1336 decrypted_buffer = buffer_from_bytes(buffer_size)
1337 decrypted_length = libcrypto.RSA_public_decrypt(
1338 len(signature),
1339 signature,
1340 decrypted_buffer,
1341 rsa,
1342 LibcryptoConst.RSA_PKCS1_PADDING
1343 )
1344 handle_openssl_error(decrypted_length)
1345
1346 decrypted_bytes = bytes_from_buffer(decrypted_buffer, decrypted_length)
1347
1348 if not constant_compare(data, decrypted_bytes):
1349 raise SignatureError('Signature is invalid')
1350 return
1351
1352 finally:
1353 if rsa:
1354 libcrypto.RSA_free(rsa)
1355
1356 evp_md_ctx = None
1357 rsa = None
1358 dsa = None
1359 dsa_sig = None
1360 ec_key = None
1361 ecdsa_sig = None
1362
1363 try:
1364 if libcrypto_version_info < (1, 1):
1365 evp_md_ctx = libcrypto.EVP_MD_CTX_create()
1366 else:
1367 evp_md_ctx = libcrypto.EVP_MD_CTX_new()
1368
1369 evp_md = {
1370 'md5': libcrypto.EVP_md5,
1371 'sha1': libcrypto.EVP_sha1,
1372 'sha224': libcrypto.EVP_sha224,
1373 'sha256': libcrypto.EVP_sha256,
1374 'sha384': libcrypto.EVP_sha384,
1375 'sha512': libcrypto.EVP_sha512
1376 }[hash_algorithm]()
1377
1378 if libcrypto_version_info < (1,):
1379 if cp_is_rsa and rsa_pss_padding:
1380 digest = getattr(hashlib, hash_algorithm)(data).digest()
1381
1382 rsa = libcrypto.EVP_PKEY_get1_RSA(certificate_or_public_key.evp_pkey)
1383 if is_null(rsa):
1384 handle_openssl_error(0)
1385
1386 buffer_size = _evp_pkey_get_size(certificate_or_public_key.evp_pkey)
1387 decoded_buffer = buffer_from_bytes(buffer_size)
1388 decoded_length = libcrypto.RSA_public_decrypt(
1389 len(signature),
1390 signature,
1391 decoded_buffer,
1392 rsa,
1393 LibcryptoConst.RSA_NO_PADDING
1394 )
1395 handle_openssl_error(decoded_length)
1396
1397 res = libcrypto.RSA_verify_PKCS1_PSS(
1398 rsa,
1399 digest,
1400 evp_md,
1401 decoded_buffer,
1402 LibcryptoConst.EVP_MD_CTX_FLAG_PSS_MDLEN
1403 )
1404
1405 elif cp_is_rsa:
1406 res = libcrypto.EVP_DigestInit_ex(evp_md_ctx, evp_md, null())
1407 handle_openssl_error(res)
1408
1409 res = libcrypto.EVP_DigestUpdate(evp_md_ctx, data, len(data))
1410 handle_openssl_error(res)
1411
1412 res = libcrypto.EVP_VerifyFinal(
1413 evp_md_ctx,
1414 signature,
1415 len(signature),
1416 certificate_or_public_key.evp_pkey
1417 )
1418
1419 elif cp_alg == 'dsa':
1420 digest = getattr(hashlib, hash_algorithm)(data).digest()
1421
1422 signature_buffer = buffer_from_bytes(signature)
1423 signature_pointer = buffer_pointer(signature_buffer)
1424 dsa_sig = libcrypto.d2i_DSA_SIG(null(), signature_pointer, len(signature))
1425 if is_null(dsa_sig):
1426 raise SignatureError('Signature is invalid')
1427
1428 dsa = libcrypto.EVP_PKEY_get1_DSA(certificate_or_public_key.evp_pkey)
1429 if is_null(dsa):
1430 handle_openssl_error(0)
1431
1432 res = libcrypto.DSA_do_verify(digest, len(digest), dsa_sig, dsa)
1433
1434 elif cp_alg == 'ec':
1435 digest = getattr(hashlib, hash_algorithm)(data).digest()
1436
1437 signature_buffer = buffer_from_bytes(signature)
1438 signature_pointer = buffer_pointer(signature_buffer)
1439 ecdsa_sig = libcrypto.d2i_ECDSA_SIG(null(), signature_pointer, len(signature))
1440 if is_null(ecdsa_sig):
1441 raise SignatureError('Signature is invalid')
1442
1443 ec_key = libcrypto.EVP_PKEY_get1_EC_KEY(certificate_or_public_key.evp_pkey)
1444 if is_null(ec_key):
1445 handle_openssl_error(0)
1446
1447 res = libcrypto.ECDSA_do_verify(digest, len(digest), ecdsa_sig, ec_key)
1448
1449 else:
1450 evp_pkey_ctx_pointer_pointer = new(libcrypto, 'EVP_PKEY_CTX **')
1451 res = libcrypto.EVP_DigestVerifyInit(
1452 evp_md_ctx,
1453 evp_pkey_ctx_pointer_pointer,
1454 evp_md,
1455 null(),
1456 certificate_or_public_key.evp_pkey
1457 )
1458 if hash_algorithm == "sha1":
1459 _handle_sha1_disabled(res)
1460 else:
1461 handle_openssl_error(res)
1462 evp_pkey_ctx_pointer = unwrap(evp_pkey_ctx_pointer_pointer)
1463
1464 if rsa_pss_padding:
1465 # Enable PSS padding
1466 res = libcrypto.EVP_PKEY_CTX_ctrl(
1467 evp_pkey_ctx_pointer,
1468 LibcryptoConst.EVP_PKEY_RSA,
1469 -1, # All operations
1470 LibcryptoConst.EVP_PKEY_CTRL_RSA_PADDING,
1471 LibcryptoConst.RSA_PKCS1_PSS_PADDING,
1472 null()
1473 )
1474 handle_openssl_error(res)
1475
1476 # Use the hash algorithm output length as the salt length
1477 if libcrypto_version_info < (3, 0):
1478 res = libcrypto.EVP_PKEY_CTX_ctrl(
1479 evp_pkey_ctx_pointer,
1480 LibcryptoConst.EVP_PKEY_RSA,
1481 LibcryptoConst.EVP_PKEY_OP_SIGN | LibcryptoConst.EVP_PKEY_OP_VERIFY,
1482 LibcryptoConst.EVP_PKEY_CTRL_RSA_PSS_SALTLEN,
1483 -1,
1484 null()
1485 )
1486 handle_openssl_error(res)
1487
1488 res = libcrypto.EVP_DigestUpdate(evp_md_ctx, data, len(data))
1489 handle_openssl_error(res)
1490
1491 res = libcrypto.EVP_DigestVerifyFinal(evp_md_ctx, signature, len(signature))
1492
1493 if res < 1:
1494 raise SignatureError('Signature is invalid')
1495 handle_openssl_error(res)
1496
1497 finally:
1498 if evp_md_ctx:
1499 if libcrypto_version_info < (1, 1):
1500 libcrypto.EVP_MD_CTX_destroy(evp_md_ctx)
1501 else:
1502 libcrypto.EVP_MD_CTX_free(evp_md_ctx)
1503 if rsa:
1504 libcrypto.RSA_free(rsa)
1505 if dsa:
1506 libcrypto.DSA_free(dsa)
1507 if dsa_sig:
1508 libcrypto.DSA_SIG_free(dsa_sig)
1509 if ec_key:
1510 libcrypto.EC_KEY_free(ec_key)
1511 if ecdsa_sig:
1512 libcrypto.ECDSA_SIG_free(ecdsa_sig)
1513
1514
1515def rsa_pkcs1v15_sign(private_key, data, hash_algorithm):
1516 """
1517 Generates an RSASSA-PKCS-v1.5 signature.
1518
1519 When the hash_algorithm is "raw", the operation is identical to RSA
1520 private key encryption. That is: the data is not hashed and no ASN.1
1521 structure with an algorithm identifier of the hash algorithm is placed in
1522 the encrypted byte string.
1523
1524 :param private_key:
1525 The PrivateKey to generate the signature with
1526
1527 :param data:
1528 A byte string of the data the signature is for
1529
1530 :param hash_algorithm:
1531 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384",
1532 "sha512" or "raw"
1533
1534 :raises:
1535 ValueError - when any of the parameters contain an invalid value
1536 TypeError - when any of the parameters are of the wrong type
1537 OSError - when an error is returned by the OS crypto library
1538
1539 :return:
1540 A byte string of the signature
1541 """
1542
1543 if private_key.algorithm != 'rsa':
1544 raise ValueError(pretty_message(
1545 '''
1546 The key specified is not an RSA private key, but %s
1547 ''',
1548 private_key.algorithm.upper()
1549 ))
1550
1551 return _sign(private_key, data, hash_algorithm)
1552
1553
1554def rsa_pss_sign(private_key, data, hash_algorithm):
1555 """
1556 Generates an RSASSA-PSS signature. For the PSS padding the mask gen
1557 algorithm will be mgf1 using the same hash algorithm as the signature. The
1558 salt length with be the length of the hash algorithm, and the trailer field
1559 with be the standard 0xBC byte.
1560
1561 :param private_key:
1562 The PrivateKey to generate the signature with
1563
1564 :param data:
1565 A byte string of the data the signature is for
1566
1567 :param hash_algorithm:
1568 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"
1569
1570 :raises:
1571 ValueError - when any of the parameters contain an invalid value
1572 TypeError - when any of the parameters are of the wrong type
1573 OSError - when an error is returned by the OS crypto library
1574
1575 :return:
1576 A byte string of the signature
1577 """
1578
1579 pkey_alg = private_key.algorithm
1580
1581 if pkey_alg != 'rsa' and pkey_alg != 'rsassa_pss':
1582 raise ValueError(pretty_message(
1583 '''
1584 The key specified is not an RSA private key, but %s
1585 ''',
1586 pkey_alg.upper()
1587 ))
1588
1589 return _sign(private_key, data, hash_algorithm, rsa_pss_padding=True)
1590
1591
1592def dsa_sign(private_key, data, hash_algorithm):
1593 """
1594 Generates a DSA signature
1595
1596 :param private_key:
1597 The PrivateKey to generate the signature with
1598
1599 :param data:
1600 A byte string of the data the signature is for
1601
1602 :param hash_algorithm:
1603 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"
1604
1605 :raises:
1606 ValueError - when any of the parameters contain an invalid value
1607 TypeError - when any of the parameters are of the wrong type
1608 OSError - when an error is returned by the OS crypto library
1609
1610 :return:
1611 A byte string of the signature
1612 """
1613
1614 if private_key.algorithm != 'dsa':
1615 raise ValueError(pretty_message(
1616 '''
1617 The key specified is not a DSA private key, but %s
1618 ''',
1619 private_key.algorithm.upper()
1620 ))
1621
1622 return _sign(private_key, data, hash_algorithm)
1623
1624
1625def ecdsa_sign(private_key, data, hash_algorithm):
1626 """
1627 Generates an ECDSA signature
1628
1629 :param private_key:
1630 The PrivateKey to generate the signature with
1631
1632 :param data:
1633 A byte string of the data the signature is for
1634
1635 :param hash_algorithm:
1636 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"
1637
1638 :raises:
1639 ValueError - when any of the parameters contain an invalid value
1640 TypeError - when any of the parameters are of the wrong type
1641 OSError - when an error is returned by the OS crypto library
1642
1643 :return:
1644 A byte string of the signature
1645 """
1646
1647 if private_key.algorithm != 'ec':
1648 raise ValueError(pretty_message(
1649 '''
1650 The key specified is not an EC private key, but %s
1651 ''',
1652 private_key.algorithm.upper()
1653 ))
1654
1655 return _sign(private_key, data, hash_algorithm)
1656
1657
1658def _sign(private_key, data, hash_algorithm, rsa_pss_padding=False):
1659 """
1660 Generates an RSA, DSA or ECDSA signature
1661
1662 :param private_key:
1663 The PrivateKey to generate the signature with
1664
1665 :param data:
1666 A byte string of the data the signature is for
1667
1668 :param hash_algorithm:
1669 A unicode string of "md5", "sha1", "sha224", "sha256", "sha384" or "sha512"
1670
1671 :param rsa_pss_padding:
1672 If the private_key is an RSA key, this enables PSS padding
1673
1674 :raises:
1675 ValueError - when any of the parameters contain an invalid value
1676 TypeError - when any of the parameters are of the wrong type
1677 OSError - when an error is returned by the OS crypto library
1678
1679 :return:
1680 A byte string of the signature
1681 """
1682
1683 if not isinstance(private_key, PrivateKey):
1684 raise TypeError(pretty_message(
1685 '''
1686 private_key must be an instance of PrivateKey, not %s
1687 ''',
1688 type_name(private_key)
1689 ))
1690
1691 if not isinstance(data, byte_cls):
1692 raise TypeError(pretty_message(
1693 '''
1694 data must be a byte string, not %s
1695 ''',
1696 type_name(data)
1697 ))
1698
1699 pkey_alg = private_key.algorithm
1700 pkey_is_rsa = pkey_alg == 'rsa' or pkey_alg == 'rsassa_pss'
1701
1702 valid_hash_algorithms = set(['md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512'])
1703 if pkey_alg == 'rsa' and not rsa_pss_padding:
1704 valid_hash_algorithms |= set(['raw'])
1705
1706 if hash_algorithm not in valid_hash_algorithms:
1707 valid_hash_algorithms_error = '"md5", "sha1", "sha224", "sha256", "sha384", "sha512"'
1708 if pkey_is_rsa and not rsa_pss_padding:
1709 valid_hash_algorithms_error += ', "raw"'
1710 raise ValueError(pretty_message(
1711 '''
1712 hash_algorithm must be one of %s, not %s
1713 ''',
1714 valid_hash_algorithms_error,
1715 repr(hash_algorithm)
1716 ))
1717
1718 if not pkey_is_rsa and rsa_pss_padding:
1719 raise ValueError(pretty_message(
1720 '''
1721 PSS padding can only be used with RSA keys - the key provided is a
1722 %s key
1723 ''',
1724 pkey_alg.upper()
1725 ))
1726
1727 if pkey_is_rsa and hash_algorithm == 'raw':
1728 if len(data) > private_key.byte_size - 11:
1729 raise ValueError(pretty_message(
1730 '''
1731 data must be 11 bytes shorter than the key size when
1732 hash_algorithm is "raw" - key size is %s bytes, but data is
1733 %s bytes long
1734 ''',
1735 private_key.byte_size,
1736 len(data)
1737 ))
1738
1739 rsa = None
1740
1741 try:
1742 rsa = libcrypto.EVP_PKEY_get1_RSA(private_key.evp_pkey)
1743 if is_null(rsa):
1744 handle_openssl_error(0)
1745
1746 buffer_size = _evp_pkey_get_size(private_key.evp_pkey)
1747
1748 signature_buffer = buffer_from_bytes(buffer_size)
1749 signature_length = libcrypto.RSA_private_encrypt(
1750 len(data),
1751 data,
1752 signature_buffer,
1753 rsa,
1754 LibcryptoConst.RSA_PKCS1_PADDING
1755 )
1756 handle_openssl_error(signature_length)
1757
1758 return bytes_from_buffer(signature_buffer, signature_length)
1759
1760 finally:
1761 if rsa:
1762 libcrypto.RSA_free(rsa)
1763
1764 evp_md_ctx = None
1765 rsa = None
1766 dsa = None
1767 dsa_sig = None
1768 ec_key = None
1769 ecdsa_sig = None
1770
1771 try:
1772 if libcrypto_version_info < (1, 1):
1773 evp_md_ctx = libcrypto.EVP_MD_CTX_create()
1774 else:
1775 evp_md_ctx = libcrypto.EVP_MD_CTX_new()
1776
1777 evp_md = {
1778 'md5': libcrypto.EVP_md5,
1779 'sha1': libcrypto.EVP_sha1,
1780 'sha224': libcrypto.EVP_sha224,
1781 'sha256': libcrypto.EVP_sha256,
1782 'sha384': libcrypto.EVP_sha384,
1783 'sha512': libcrypto.EVP_sha512
1784 }[hash_algorithm]()
1785
1786 if libcrypto_version_info < (1,):
1787 if pkey_is_rsa and rsa_pss_padding:
1788 digest = getattr(hashlib, hash_algorithm)(data).digest()
1789
1790 rsa = libcrypto.EVP_PKEY_get1_RSA(private_key.evp_pkey)
1791 if is_null(rsa):
1792 handle_openssl_error(0)
1793
1794 buffer_size = _evp_pkey_get_size(private_key.evp_pkey)
1795 em_buffer = buffer_from_bytes(buffer_size)
1796 res = libcrypto.RSA_padding_add_PKCS1_PSS(
1797 rsa,
1798 em_buffer,
1799 digest,
1800 evp_md,
1801 LibcryptoConst.EVP_MD_CTX_FLAG_PSS_MDLEN
1802 )
1803 handle_openssl_error(res)
1804
1805 signature_buffer = buffer_from_bytes(buffer_size)
1806 signature_length = libcrypto.RSA_private_encrypt(
1807 buffer_size,
1808 em_buffer,
1809 signature_buffer,
1810 rsa,
1811 LibcryptoConst.RSA_NO_PADDING
1812 )
1813 handle_openssl_error(signature_length)
1814
1815 elif pkey_is_rsa:
1816 buffer_size = _evp_pkey_get_size(private_key.evp_pkey)
1817 signature_buffer = buffer_from_bytes(buffer_size)
1818 signature_length = new(libcrypto, 'unsigned int *')
1819
1820 res = libcrypto.EVP_DigestInit_ex(evp_md_ctx, evp_md, null())
1821 handle_openssl_error(res)
1822
1823 res = libcrypto.EVP_DigestUpdate(evp_md_ctx, data, len(data))
1824 handle_openssl_error(res)
1825
1826 res = libcrypto.EVP_SignFinal(
1827 evp_md_ctx,
1828 signature_buffer,
1829 signature_length,
1830 private_key.evp_pkey
1831 )
1832 handle_openssl_error(res)
1833
1834 signature_length = deref(signature_length)
1835
1836 elif pkey_alg == 'dsa':
1837 digest = getattr(hashlib, hash_algorithm)(data).digest()
1838
1839 dsa = libcrypto.EVP_PKEY_get1_DSA(private_key.evp_pkey)
1840 if is_null(dsa):
1841 handle_openssl_error(0)
1842
1843 dsa_sig = libcrypto.DSA_do_sign(digest, len(digest), dsa)
1844 if is_null(dsa_sig):
1845 handle_openssl_error(0)
1846
1847 buffer_size = libcrypto.i2d_DSA_SIG(dsa_sig, null())
1848 signature_buffer = buffer_from_bytes(buffer_size)
1849 signature_pointer = buffer_pointer(signature_buffer)
1850 signature_length = libcrypto.i2d_DSA_SIG(dsa_sig, signature_pointer)
1851 handle_openssl_error(signature_length)
1852
1853 elif pkey_alg == 'ec':
1854 digest = getattr(hashlib, hash_algorithm)(data).digest()
1855
1856 ec_key = libcrypto.EVP_PKEY_get1_EC_KEY(private_key.evp_pkey)
1857 if is_null(ec_key):
1858 handle_openssl_error(0)
1859
1860 ecdsa_sig = libcrypto.ECDSA_do_sign(digest, len(digest), ec_key)
1861 if is_null(ecdsa_sig):
1862 handle_openssl_error(0)
1863
1864 buffer_size = libcrypto.i2d_ECDSA_SIG(ecdsa_sig, null())
1865 signature_buffer = buffer_from_bytes(buffer_size)
1866 signature_pointer = buffer_pointer(signature_buffer)
1867 signature_length = libcrypto.i2d_ECDSA_SIG(ecdsa_sig, signature_pointer)
1868 handle_openssl_error(signature_length)
1869
1870 else:
1871 buffer_size = _evp_pkey_get_size(private_key.evp_pkey)
1872 signature_buffer = buffer_from_bytes(buffer_size)
1873 signature_length = new(libcrypto, 'size_t *', buffer_size)
1874
1875 evp_pkey_ctx_pointer_pointer = new(libcrypto, 'EVP_PKEY_CTX **')
1876 res = libcrypto.EVP_DigestSignInit(
1877 evp_md_ctx,
1878 evp_pkey_ctx_pointer_pointer,
1879 evp_md,
1880 null(),
1881 private_key.evp_pkey
1882 )
1883 if hash_algorithm == "sha1":
1884 _handle_sha1_disabled(res)
1885 else:
1886 handle_openssl_error(res)
1887 evp_pkey_ctx_pointer = unwrap(evp_pkey_ctx_pointer_pointer)
1888
1889 if rsa_pss_padding:
1890 # Enable PSS padding
1891 res = libcrypto.EVP_PKEY_CTX_ctrl(
1892 evp_pkey_ctx_pointer,
1893 LibcryptoConst.EVP_PKEY_RSA,
1894 -1, # All operations
1895 LibcryptoConst.EVP_PKEY_CTRL_RSA_PADDING,
1896 LibcryptoConst.RSA_PKCS1_PSS_PADDING,
1897 null()
1898 )
1899 handle_openssl_error(res)
1900
1901 # Use the hash algorithm output length as the salt length
1902 if libcrypto_version_info < (3, 0):
1903 res = libcrypto.EVP_PKEY_CTX_ctrl(
1904 evp_pkey_ctx_pointer,
1905 LibcryptoConst.EVP_PKEY_RSA,
1906 LibcryptoConst.EVP_PKEY_OP_SIGN | LibcryptoConst.EVP_PKEY_OP_VERIFY,
1907 LibcryptoConst.EVP_PKEY_CTRL_RSA_PSS_SALTLEN,
1908 -1,
1909 null()
1910 )
1911 handle_openssl_error(res)
1912
1913 res = libcrypto.EVP_DigestUpdate(evp_md_ctx, data, len(data))
1914 handle_openssl_error(res)
1915
1916 res = libcrypto.EVP_DigestSignFinal(evp_md_ctx, signature_buffer, signature_length)
1917 handle_openssl_error(res)
1918
1919 signature_length = deref(signature_length)
1920
1921 return bytes_from_buffer(signature_buffer, signature_length)
1922
1923 finally:
1924 if evp_md_ctx:
1925 if libcrypto_version_info < (1, 1):
1926 libcrypto.EVP_MD_CTX_destroy(evp_md_ctx)
1927 else:
1928 libcrypto.EVP_MD_CTX_free(evp_md_ctx)
1929 if rsa:
1930 libcrypto.RSA_free(rsa)
1931 if dsa:
1932 libcrypto.DSA_free(dsa)
1933 if dsa_sig:
1934 libcrypto.DSA_SIG_free(dsa_sig)
1935 if ec_key:
1936 libcrypto.EC_KEY_free(ec_key)
1937 if ecdsa_sig:
1938 libcrypto.ECDSA_SIG_free(ecdsa_sig)
1939
1940
1941def _handle_sha1_disabled(result):
1942 if result <= 0:
1943 error_num = get_first_openssl_error()
1944 # The following errors can occur when SHA1 is disabled:
1945 # error:02000068:rsa routines::bad signature
1946 # error:02000072:rsa routines::padding check failed
1947 # error:0200008A:rsa routines::invalid padding
1948 # error:03000098:digital envelope routines::invalid digest
1949 if error_num in set([0x02000068, 0x02000072, 0x0200008A, 0x03000098]):
1950 raise SignatureError(
1951 'SHA1 signatures are disabled by the OpenSSL configuration. '
1952 'Try "export OPENSSL_ENABLE_SHA1_SIGNATURES=1" before starting the application.'
1953 )
1954 raise_openssl_error(error_num, SignatureError)