RSA.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. # -*- coding: utf-8 -*-
  2. #
  3. # PublicKey/RSA.py : RSA public key primitive
  4. #
  5. # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
  6. #
  7. # ===================================================================
  8. # The contents of this file are dedicated to the public domain. To
  9. # the extent that dedication to the public domain is not available,
  10. # everyone is granted a worldwide, perpetual, royalty-free,
  11. # non-exclusive license to exercise all rights associated with the
  12. # contents of this file for any purpose whatsoever.
  13. # No rights are reserved.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  19. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  20. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. # SOFTWARE.
  23. # ===================================================================
  24. """RSA public-key cryptography algorithm (signature and encryption).
  25. RSA_ is the most widespread and used public key algorithm. Its security is
  26. based on the difficulty of factoring large integers. The algorithm has
  27. withstood attacks for 30 years, and it is therefore considered reasonably
  28. secure for new designs.
  29. The algorithm can be used for both confidentiality (encryption) and
  30. authentication (digital signature). It is worth noting that signing and
  31. decryption are significantly slower than verification and encryption.
  32. The cryptograhic strength is primarily linked to the length of the modulus *n*.
  33. In 2012, a sufficient length is deemed to be 2048 bits. For more information,
  34. see the most recent ECRYPT_ report.
  35. Both RSA ciphertext and RSA signature are as big as the modulus *n* (256
  36. bytes if *n* is 2048 bit long).
  37. This module provides facilities for generating fresh, new RSA keys, constructing
  38. them from known components, exporting them, and importing them.
  39. >>> from Crypto.PublicKey import RSA
  40. >>>
  41. >>> key = RSA.generate(2048)
  42. >>> f = open('mykey.pem','w')
  43. >>> f.write(RSA.exportKey('PEM'))
  44. >>> f.close()
  45. ...
  46. >>> f = open('mykey.pem','r')
  47. >>> key = RSA.importKey(f.read())
  48. Even though you may choose to directly use the methods of an RSA key object
  49. to perform the primitive cryptographic operations (e.g. `_RSAobj.encrypt`),
  50. it is recommended to use one of the standardized schemes instead (like
  51. `Crypto.Cipher.PKCS1_v1_5` or `Crypto.Signature.PKCS1_v1_5`).
  52. .. _RSA: http://en.wikipedia.org/wiki/RSA_%28algorithm%29
  53. .. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf
  54. :sort: generate,construct,importKey,error
  55. """
  56. __revision__ = "$Id$"
  57. __all__ = ['generate', 'construct', 'error', 'importKey', 'RSAImplementation', '_RSAobj']
  58. import sys
  59. if sys.version_info[0] == 2 and sys.version_info[1] == 1:
  60. from Crypto.Util.py21compat import *
  61. from Crypto.Util.py3compat import *
  62. #from Crypto.Util.python_compat import *
  63. from Crypto.Util.number import getRandomRange, bytes_to_long, long_to_bytes
  64. from Crypto.PublicKey import _RSA, _slowmath, pubkey
  65. from Crypto import Random
  66. from Crypto.Util.asn1 import DerObject, DerSequence, DerNull
  67. import binascii
  68. import struct
  69. from Crypto.Util.number import inverse
  70. from Crypto.Util.number import inverse
  71. try:
  72. from Crypto.PublicKey import _fastmath
  73. except ImportError:
  74. _fastmath = None
  75. class _RSAobj(pubkey.pubkey):
  76. """Class defining an actual RSA key.
  77. :undocumented: __getstate__, __setstate__, __repr__, __getattr__
  78. """
  79. #: Dictionary of RSA parameters.
  80. #:
  81. #: A public key will only have the following entries:
  82. #:
  83. #: - **n**, the modulus.
  84. #: - **e**, the public exponent.
  85. #:
  86. #: A private key will also have:
  87. #:
  88. #: - **d**, the private exponent.
  89. #: - **p**, the first factor of n.
  90. #: - **q**, the second factor of n.
  91. #: - **u**, the CRT coefficient (1/p) mod q.
  92. keydata = ['n', 'e', 'd', 'p', 'q', 'u']
  93. def __init__(self, implementation, key, randfunc=None):
  94. self.implementation = implementation
  95. self.key = key
  96. if randfunc is None:
  97. randfunc = Random.new().read
  98. self._randfunc = randfunc
  99. def __getattr__(self, attrname):
  100. if attrname in self.keydata:
  101. # For backward compatibility, allow the user to get (not set) the
  102. # RSA key parameters directly from this object.
  103. return getattr(self.key, attrname)
  104. else:
  105. raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,))
  106. def encrypt(self, plaintext, K):
  107. """Encrypt a piece of data with RSA.
  108. :Parameter plaintext: The piece of data to encrypt with RSA. It may not
  109. be numerically larger than the RSA module (**n**).
  110. :Type plaintext: byte string or long
  111. :Parameter K: A random parameter (*for compatibility only. This
  112. value will be ignored*)
  113. :Type K: byte string or long
  114. :attention: this function performs the plain, primitive RSA encryption
  115. (*textbook*). In real applications, you always need to use proper
  116. cryptographic padding, and you should not directly encrypt data with
  117. this method. Failure to do so may lead to security vulnerabilities.
  118. It is recommended to use modules
  119. `Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead.
  120. :Return: A tuple with two items. The first item is the ciphertext
  121. of the same type as the plaintext (string or long). The second item
  122. is always None.
  123. """
  124. return pubkey.pubkey.encrypt(self, plaintext, K)
  125. def decrypt(self, ciphertext):
  126. """Decrypt a piece of data with RSA.
  127. Decryption always takes place with blinding.
  128. :attention: this function performs the plain, primitive RSA decryption
  129. (*textbook*). In real applications, you always need to use proper
  130. cryptographic padding, and you should not directly decrypt data with
  131. this method. Failure to do so may lead to security vulnerabilities.
  132. It is recommended to use modules
  133. `Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead.
  134. :Parameter ciphertext: The piece of data to decrypt with RSA. It may
  135. not be numerically larger than the RSA module (**n**). If a tuple,
  136. the first item is the actual ciphertext; the second item is ignored.
  137. :Type ciphertext: byte string, long or a 2-item tuple as returned by
  138. `encrypt`
  139. :Return: A byte string if ciphertext was a byte string or a tuple
  140. of byte strings. A long otherwise.
  141. """
  142. return pubkey.pubkey.decrypt(self, ciphertext)
  143. def sign(self, M, K):
  144. """Sign a piece of data with RSA.
  145. Signing always takes place with blinding.
  146. :attention: this function performs the plain, primitive RSA decryption
  147. (*textbook*). In real applications, you always need to use proper
  148. cryptographic padding, and you should not directly sign data with
  149. this method. Failure to do so may lead to security vulnerabilities.
  150. It is recommended to use modules
  151. `Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead.
  152. :Parameter M: The piece of data to sign with RSA. It may
  153. not be numerically larger than the RSA module (**n**).
  154. :Type M: byte string or long
  155. :Parameter K: A random parameter (*for compatibility only. This
  156. value will be ignored*)
  157. :Type K: byte string or long
  158. :Return: A 2-item tuple. The first item is the actual signature (a
  159. long). The second item is always None.
  160. """
  161. return pubkey.pubkey.sign(self, M, K)
  162. def verify(self, M, signature):
  163. """Verify the validity of an RSA signature.
  164. :attention: this function performs the plain, primitive RSA encryption
  165. (*textbook*). In real applications, you always need to use proper
  166. cryptographic padding, and you should not directly verify data with
  167. this method. Failure to do so may lead to security vulnerabilities.
  168. It is recommended to use modules
  169. `Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead.
  170. :Parameter M: The expected message.
  171. :Type M: byte string or long
  172. :Parameter signature: The RSA signature to verify. The first item of
  173. the tuple is the actual signature (a long not larger than the modulus
  174. **n**), whereas the second item is always ignored.
  175. :Type signature: A 2-item tuple as return by `sign`
  176. :Return: True if the signature is correct, False otherwise.
  177. """
  178. return pubkey.pubkey.verify(self, M, signature)
  179. def _encrypt(self, c, K):
  180. return (self.key._encrypt(c),)
  181. def _decrypt(self, c):
  182. #(ciphertext,) = c
  183. (ciphertext,) = c[:1] # HACK - We should use the previous line
  184. # instead, but this is more compatible and we're
  185. # going to replace the Crypto.PublicKey API soon
  186. # anyway.
  187. # Blinded RSA decryption (to prevent timing attacks):
  188. # Step 1: Generate random secret blinding factor r, such that 0 < r < n-1
  189. r = getRandomRange(1, self.key.n-1, randfunc=self._randfunc)
  190. # Step 2: Compute c' = c * r**e mod n
  191. cp = self.key._blind(ciphertext, r)
  192. # Step 3: Compute m' = c'**d mod n (ordinary RSA decryption)
  193. mp = self.key._decrypt(cp)
  194. # Step 4: Compute m = m**(r-1) mod n
  195. return self.key._unblind(mp, r)
  196. def _blind(self, m, r):
  197. return self.key._blind(m, r)
  198. def _unblind(self, m, r):
  199. return self.key._unblind(m, r)
  200. def _sign(self, m, K=None):
  201. return (self.key._sign(m),)
  202. def _verify(self, m, sig):
  203. #(s,) = sig
  204. (s,) = sig[:1] # HACK - We should use the previous line instead, but
  205. # this is more compatible and we're going to replace
  206. # the Crypto.PublicKey API soon anyway.
  207. return self.key._verify(m, s)
  208. def has_private(self):
  209. return self.key.has_private()
  210. def size(self):
  211. return self.key.size()
  212. def can_blind(self):
  213. return True
  214. def can_encrypt(self):
  215. return True
  216. def can_sign(self):
  217. return True
  218. def publickey(self):
  219. return self.implementation.construct((self.key.n, self.key.e))
  220. def __getstate__(self):
  221. d = {}
  222. for k in self.keydata:
  223. try:
  224. d[k] = getattr(self.key, k)
  225. except AttributeError:
  226. pass
  227. return d
  228. def __setstate__(self, d):
  229. if not hasattr(self, 'implementation'):
  230. self.implementation = RSAImplementation()
  231. t = []
  232. for k in self.keydata:
  233. if not d.has_key(k):
  234. break
  235. t.append(d[k])
  236. self.key = self.implementation._math.rsa_construct(*tuple(t))
  237. def __repr__(self):
  238. attrs = []
  239. for k in self.keydata:
  240. if k == 'n':
  241. attrs.append("n(%d)" % (self.size()+1,))
  242. elif hasattr(self.key, k):
  243. attrs.append(k)
  244. if self.has_private():
  245. attrs.append("private")
  246. # PY3K: This is meant to be text, do not change to bytes (data)
  247. return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs))
  248. def exportKey(self, format='PEM', passphrase=None, pkcs=1):
  249. """Export this RSA key.
  250. :Parameter format: The format to use for wrapping the key.
  251. - *'DER'*. Binary encoding, always unencrypted.
  252. - *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_.
  253. Unencrypted (default) or encrypted.
  254. - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification.
  255. Only suitable for public keys (not private keys).
  256. :Type format: string
  257. :Parameter passphrase: In case of PEM, the pass phrase to derive the encryption key from.
  258. :Type passphrase: string
  259. :Parameter pkcs: The PKCS standard to follow for assembling the key.
  260. You have two choices:
  261. - with **1**, the public key is embedded into an X.509 `SubjectPublicKeyInfo` DER SEQUENCE.
  262. The private key is embedded into a `PKCS#1`_ `RSAPrivateKey` DER SEQUENCE.
  263. This mode is the default.
  264. - with **8**, the private key is embedded into a `PKCS#8`_ `PrivateKeyInfo` DER SEQUENCE.
  265. This mode is not available for public keys.
  266. PKCS standards are not relevant for the *OpenSSH* format.
  267. :Type pkcs: integer
  268. :Return: A byte string with the encoded public or private half.
  269. :Raise ValueError:
  270. When the format is unknown.
  271. .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
  272. .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
  273. .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
  274. .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
  275. """
  276. if passphrase is not None:
  277. passphrase = tobytes(passphrase)
  278. if format=='OpenSSH':
  279. eb = long_to_bytes(self.e)
  280. nb = long_to_bytes(self.n)
  281. if bord(eb[0]) & 0x80: eb=bchr(0x00)+eb
  282. if bord(nb[0]) & 0x80: nb=bchr(0x00)+nb
  283. keyparts = [ 'ssh-rsa', eb, nb ]
  284. keystring = ''.join([ struct.pack(">I",len(kp))+kp for kp in keyparts])
  285. return 'ssh-rsa '+binascii.b2a_base64(keystring)[:-1]
  286. # DER format is always used, even in case of PEM, which simply
  287. # encodes it into BASE64.
  288. der = DerSequence()
  289. if self.has_private():
  290. keyType= { 1: 'RSA PRIVATE', 8: 'PRIVATE' }[pkcs]
  291. der[:] = [ 0, self.n, self.e, self.d, self.p, self.q,
  292. self.d % (self.p-1), self.d % (self.q-1),
  293. inverse(self.q, self.p) ]
  294. if pkcs==8:
  295. derkey = der.encode()
  296. der = DerSequence([0])
  297. der.append(algorithmIdentifier)
  298. der.append(DerObject('OCTET STRING', derkey).encode())
  299. else:
  300. keyType = "PUBLIC"
  301. der.append(algorithmIdentifier)
  302. bitmap = DerObject('BIT STRING')
  303. derPK = DerSequence( [ self.n, self.e ] )
  304. bitmap.payload = bchr(0x00) + derPK.encode()
  305. der.append(bitmap.encode())
  306. if format=='DER':
  307. return der.encode()
  308. if format=='PEM':
  309. pem = b("-----BEGIN " + keyType + " KEY-----\n")
  310. objenc = None
  311. if passphrase and keyType.endswith('PRIVATE'):
  312. # We only support 3DES for encryption
  313. import Crypto.Hash.MD5
  314. from Crypto.Cipher import DES3
  315. from Crypto.Protocol.KDF import PBKDF1
  316. salt = self._randfunc(8)
  317. key = PBKDF1(passphrase, salt, 16, 1, Crypto.Hash.MD5)
  318. key += PBKDF1(key+passphrase, salt, 8, 1, Crypto.Hash.MD5)
  319. objenc = DES3.new(key, Crypto.Cipher.DES3.MODE_CBC, salt)
  320. pem += b('Proc-Type: 4,ENCRYPTED\n')
  321. pem += b('DEK-Info: DES-EDE3-CBC,') + binascii.b2a_hex(salt).upper() + b('\n\n')
  322. binaryKey = der.encode()
  323. if objenc:
  324. # Add PKCS#7-like padding
  325. padding = objenc.block_size-len(binaryKey)%objenc.block_size
  326. binaryKey = objenc.encrypt(binaryKey+bchr(padding)*padding)
  327. # Each BASE64 line can take up to 64 characters (=48 bytes of data)
  328. chunks = [ binascii.b2a_base64(binaryKey[i:i+48]) for i in range(0, len(binaryKey), 48) ]
  329. pem += b('').join(chunks)
  330. pem += b("-----END " + keyType + " KEY-----")
  331. return pem
  332. return ValueError("Unknown key format '%s'. Cannot export the RSA key." % format)
  333. class RSAImplementation(object):
  334. """
  335. An RSA key factory.
  336. This class is only internally used to implement the methods of the `Crypto.PublicKey.RSA` module.
  337. :sort: __init__,generate,construct,importKey
  338. :undocumented: _g*, _i*
  339. """
  340. def __init__(self, **kwargs):
  341. """Create a new RSA key factory.
  342. :Keywords:
  343. use_fast_math : bool
  344. Specify which mathematic library to use:
  345. - *None* (default). Use fastest math available.
  346. - *True* . Use fast math.
  347. - *False* . Use slow math.
  348. default_randfunc : callable
  349. Specify how to collect random data:
  350. - *None* (default). Use Random.new().read().
  351. - not *None* . Use the specified function directly.
  352. :Raise RuntimeError:
  353. When **use_fast_math** =True but fast math is not available.
  354. """
  355. use_fast_math = kwargs.get('use_fast_math', None)
  356. if use_fast_math is None: # Automatic
  357. if _fastmath is not None:
  358. self._math = _fastmath
  359. else:
  360. self._math = _slowmath
  361. elif use_fast_math: # Explicitly select fast math
  362. if _fastmath is not None:
  363. self._math = _fastmath
  364. else:
  365. raise RuntimeError("fast math module not available")
  366. else: # Explicitly select slow math
  367. self._math = _slowmath
  368. self.error = self._math.error
  369. self._default_randfunc = kwargs.get('default_randfunc', None)
  370. self._current_randfunc = None
  371. def _get_randfunc(self, randfunc):
  372. if randfunc is not None:
  373. return randfunc
  374. elif self._current_randfunc is None:
  375. self._current_randfunc = Random.new().read
  376. return self._current_randfunc
  377. def generate(self, bits, randfunc=None, progress_func=None, e=65537):
  378. """Randomly generate a fresh, new RSA key.
  379. :Parameters:
  380. bits : int
  381. Key length, or size (in bits) of the RSA modulus.
  382. It must be a multiple of 256, and no smaller than 1024.
  383. randfunc : callable
  384. Random number generation function; it should accept
  385. a single integer N and return a string of random data
  386. N bytes long.
  387. If not specified, a new one will be instantiated
  388. from ``Crypto.Random``.
  389. progress_func : callable
  390. Optional function that will be called with a short string
  391. containing the key parameter currently being generated;
  392. it's useful for interactive applications where a user is
  393. waiting for a key to be generated.
  394. e : int
  395. Public RSA exponent. It must be an odd positive integer.
  396. It is typically a small number with very few ones in its
  397. binary representation.
  398. The default value 65537 (= ``0b10000000000000001`` ) is a safe
  399. choice: other common values are 5, 7, 17, and 257.
  400. :attention: You should always use a cryptographically secure random number generator,
  401. such as the one defined in the ``Crypto.Random`` module; **don't** just use the
  402. current time and the ``random`` module.
  403. :attention: Exponent 3 is also widely used, but it requires very special care when padding
  404. the message.
  405. :Return: An RSA key object (`_RSAobj`).
  406. :Raise ValueError:
  407. When **bits** is too little or not a multiple of 256, or when
  408. **e** is not odd or smaller than 2.
  409. """
  410. if bits < 1024 or (bits & 0xff) != 0:
  411. # pubkey.getStrongPrime doesn't like anything that's not a multiple of 256 and >= 1024
  412. raise ValueError("RSA modulus length must be a multiple of 256 and >= 1024")
  413. if e%2==0 or e<3:
  414. raise ValueError("RSA public exponent must be a positive, odd integer larger than 2.")
  415. rf = self._get_randfunc(randfunc)
  416. obj = _RSA.generate_py(bits, rf, progress_func, e) # TODO: Don't use legacy _RSA module
  417. key = self._math.rsa_construct(obj.n, obj.e, obj.d, obj.p, obj.q, obj.u)
  418. return _RSAobj(self, key)
  419. def construct(self, tup):
  420. """Construct an RSA key from a tuple of valid RSA components.
  421. The modulus **n** must be the product of two primes.
  422. The public exponent **e** must be odd and larger than 1.
  423. In case of a private key, the following equations must apply:
  424. - e != 1
  425. - p*q = n
  426. - e*d = 1 mod (p-1)(q-1)
  427. - p*u = 1 mod q
  428. :Parameters:
  429. tup : tuple
  430. A tuple of long integers, with at least 2 and no
  431. more than 6 items. The items come in the following order:
  432. 1. RSA modulus (n).
  433. 2. Public exponent (e).
  434. 3. Private exponent (d). Only required if the key is private.
  435. 4. First factor of n (p). Optional.
  436. 5. Second factor of n (q). Optional.
  437. 6. CRT coefficient, (1/p) mod q (u). Optional.
  438. :Return: An RSA key object (`_RSAobj`).
  439. """
  440. key = self._math.rsa_construct(*tup)
  441. return _RSAobj(self, key)
  442. def _importKeyDER(self, externKey):
  443. """Import an RSA key (public or private half), encoded in DER form."""
  444. try:
  445. der = DerSequence()
  446. der.decode(externKey, True)
  447. # Try PKCS#1 first, for a private key
  448. if len(der)==9 and der.hasOnlyInts() and der[0]==0:
  449. # ASN.1 RSAPrivateKey element
  450. del der[6:] # Remove d mod (p-1), d mod (q-1), and q^{-1} mod p
  451. der.append(inverse(der[4],der[5])) # Add p^{-1} mod q
  452. del der[0] # Remove version
  453. return self.construct(der[:])
  454. # Keep on trying PKCS#1, but now for a public key
  455. if len(der)==2:
  456. # The DER object is an RSAPublicKey SEQUENCE with two elements
  457. if der.hasOnlyInts():
  458. return self.construct(der[:])
  459. # The DER object is a SubjectPublicKeyInfo SEQUENCE with two elements:
  460. # an 'algorithm' (or 'algorithmIdentifier') SEQUENCE and a 'subjectPublicKey' BIT STRING.
  461. # 'algorithm' takes the value given a few lines above.
  462. # 'subjectPublicKey' encapsulates the actual ASN.1 RSAPublicKey element.
  463. if der[0]==algorithmIdentifier:
  464. bitmap = DerObject()
  465. bitmap.decode(der[1], True)
  466. if bitmap.isType('BIT STRING') and bord(bitmap.payload[0])==0x00:
  467. der.decode(bitmap.payload[1:], True)
  468. if len(der)==2 and der.hasOnlyInts():
  469. return self.construct(der[:])
  470. # Try unencrypted PKCS#8
  471. if der[0]==0:
  472. # The second element in the SEQUENCE is algorithmIdentifier.
  473. # It must say RSA (see above for description).
  474. if der[1]==algorithmIdentifier:
  475. privateKey = DerObject()
  476. privateKey.decode(der[2], True)
  477. if privateKey.isType('OCTET STRING'):
  478. return self._importKeyDER(privateKey.payload)
  479. except ValueError, IndexError:
  480. pass
  481. raise ValueError("RSA key format is not supported")
  482. def importKey(self, externKey, passphrase=None):
  483. """Import an RSA key (public or private half), encoded in standard form.
  484. :Parameter externKey:
  485. The RSA key to import, encoded as a string.
  486. An RSA public key can be in any of the following formats:
  487. - X.509 `subjectPublicKeyInfo` DER SEQUENCE (binary or PEM encoding)
  488. - `PKCS#1`_ `RSAPublicKey` DER SEQUENCE (binary or PEM encoding)
  489. - OpenSSH (textual public key only)
  490. An RSA private key can be in any of the following formats:
  491. - PKCS#1 `RSAPrivateKey` DER SEQUENCE (binary or PEM encoding)
  492. - `PKCS#8`_ `PrivateKeyInfo` DER SEQUENCE (binary or PEM encoding)
  493. - OpenSSH (textual public key only)
  494. For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
  495. In case of PEM encoding, the private key can be encrypted with DES or 3TDES according to a certain ``pass phrase``.
  496. Only OpenSSL-compatible pass phrases are supported.
  497. :Type externKey: string
  498. :Parameter passphrase:
  499. In case of an encrypted PEM key, this is the pass phrase from which the encryption key is derived.
  500. :Type passphrase: string
  501. :Return: An RSA key object (`_RSAobj`).
  502. :Raise ValueError/IndexError/TypeError:
  503. When the given key cannot be parsed (possibly because the pass phrase is wrong).
  504. .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
  505. .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
  506. .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
  507. .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
  508. """
  509. externKey = tobytes(externKey)
  510. if passphrase is not None:
  511. passphrase = tobytes(passphrase)
  512. if externKey.startswith(b('-----')):
  513. # This is probably a PEM encoded key
  514. lines = externKey.replace(b(" "),b('')).split()
  515. keyobj = None
  516. # The encrypted PEM format
  517. if lines[1].startswith(b('Proc-Type:4,ENCRYPTED')):
  518. DEK = lines[2].split(b(':'))
  519. if len(DEK)!=2 or DEK[0]!=b('DEK-Info') or not passphrase:
  520. raise ValueError("PEM encryption format not supported.")
  521. algo, salt = DEK[1].split(b(','))
  522. salt = binascii.a2b_hex(salt)
  523. import Crypto.Hash.MD5
  524. from Crypto.Cipher import DES, DES3
  525. from Crypto.Protocol.KDF import PBKDF1
  526. if algo==b("DES-CBC"):
  527. # This is EVP_BytesToKey in OpenSSL
  528. key = PBKDF1(passphrase, salt, 8, 1, Crypto.Hash.MD5)
  529. keyobj = DES.new(key, Crypto.Cipher.DES.MODE_CBC, salt)
  530. elif algo==b("DES-EDE3-CBC"):
  531. # Note that EVP_BytesToKey is note exactly the same as PBKDF1
  532. key = PBKDF1(passphrase, salt, 16, 1, Crypto.Hash.MD5)
  533. key += PBKDF1(key+passphrase, salt, 8, 1, Crypto.Hash.MD5)
  534. keyobj = DES3.new(key, Crypto.Cipher.DES3.MODE_CBC, salt)
  535. else:
  536. raise ValueError("Unsupport PEM encryption algorithm.")
  537. lines = lines[2:]
  538. der = binascii.a2b_base64(b('').join(lines[1:-1]))
  539. if keyobj:
  540. der = keyobj.decrypt(der)
  541. padding = bord(der[-1])
  542. der = der[:-padding]
  543. return self._importKeyDER(der)
  544. if externKey.startswith(b('ssh-rsa ')):
  545. # This is probably an OpenSSH key
  546. keystring = binascii.a2b_base64(externKey.split(b(' '))[1])
  547. keyparts = []
  548. while len(keystring)>4:
  549. l = struct.unpack(">I",keystring[:4])[0]
  550. keyparts.append(keystring[4:4+l])
  551. keystring = keystring[4+l:]
  552. e = bytes_to_long(keyparts[1])
  553. n = bytes_to_long(keyparts[2])
  554. return self.construct([n, e])
  555. if bord(externKey[0])==0x30:
  556. # This is probably a DER encoded key
  557. return self._importKeyDER(externKey)
  558. raise ValueError("RSA key format is not supported")
  559. #: This is the ASN.1 DER object that qualifies an algorithm as
  560. #: compliant to PKCS#1 (that is, the standard RSA).
  561. # It is found in all 'algorithm' fields (also called 'algorithmIdentifier').
  562. # It is a SEQUENCE with the oid assigned to RSA and with its parameters (none).
  563. # 0x06 0x09 OBJECT IDENTIFIER, 9 bytes of payload
  564. # 0x2A 0x86 0x48 0x86 0xF7 0x0D 0x01 0x01 0x01
  565. # rsaEncryption (1 2 840 113549 1 1 1) (PKCS #1)
  566. # 0x05 0x00 NULL
  567. algorithmIdentifier = DerSequence(
  568. [ b('\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01'),
  569. DerNull().encode() ]
  570. ).encode()
  571. _impl = RSAImplementation()
  572. #:
  573. #: Randomly generate a fresh, new RSA key object.
  574. #:
  575. #: See `RSAImplementation.generate`.
  576. #:
  577. generate = _impl.generate
  578. #:
  579. #: Construct an RSA key object from a tuple of valid RSA components.
  580. #:
  581. #: See `RSAImplementation.construct`.
  582. #:
  583. construct = _impl.construct
  584. #:
  585. #: Import an RSA key (public or private half), encoded in standard form.
  586. #:
  587. #: See `RSAImplementation.importKey`.
  588. #:
  589. importKey = _impl.importKey
  590. error = _impl.error
  591. # vim:set ts=4 sw=4 sts=4 expandtab: