2008-09-18 21:42:28 -04:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
# PublicKey/RSA.py : RSA public key primitive
|
|
|
|
#
|
2009-02-28 13:24:04 -05:00
|
|
|
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
|
2008-09-18 21:42:28 -04:00
|
|
|
#
|
2009-02-28 13:24:04 -05:00
|
|
|
# ===================================================================
|
|
|
|
# The contents of this file are dedicated to the public domain. To
|
|
|
|
# the extent that dedication to the public domain is not available,
|
|
|
|
# everyone is granted a worldwide, perpetual, royalty-free,
|
|
|
|
# non-exclusive license to exercise all rights associated with the
|
|
|
|
# contents of this file for any purpose whatsoever.
|
|
|
|
# No rights are reserved.
|
2008-09-18 21:42:28 -04:00
|
|
|
#
|
2009-02-28 13:24:04 -05:00
|
|
|
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
|
|
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
|
|
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
|
|
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
|
|
|
|
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
|
|
|
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
|
|
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
|
|
# SOFTWARE.
|
|
|
|
# ===================================================================
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2012-04-12 23:16:52 +02:00
|
|
|
"""RSA public-key cryptography algorithm (signature and encryption).
|
2011-01-21 18:54:53 +01:00
|
|
|
|
2012-04-10 21:26:33 +02:00
|
|
|
RSA_ is the most widespread and used public key algorithm. Its security is
|
|
|
|
based on the difficulty of factoring large integers. The algorithm has
|
|
|
|
withstood attacks for 30 years, and it is therefore considered reasonably
|
|
|
|
secure for new designs.
|
|
|
|
|
|
|
|
The algorithm can be used for both confidentiality (encryption) and
|
|
|
|
authentication (digital signature). It is worth noting that signing and
|
|
|
|
decryption are significantly slower than verification and encryption.
|
2012-04-18 20:45:38 +02:00
|
|
|
The cryptograhic strength is primarily linked to the length of the modulus *n*.
|
2012-04-10 21:26:33 +02:00
|
|
|
In 2012, a sufficient length is deemed to be 2048 bits. For more information,
|
|
|
|
see the most recent ECRYPT_ report.
|
|
|
|
|
2012-04-18 20:45:38 +02:00
|
|
|
Both RSA ciphertext and RSA signature are as big as the modulus *n* (256
|
|
|
|
bytes if *n* is 2048 bit long).
|
|
|
|
|
2012-04-10 21:26:33 +02:00
|
|
|
This module provides facilities for generating fresh, new RSA keys, constructing
|
|
|
|
them from known components, exporting them, and importing them.
|
|
|
|
|
|
|
|
>>> from Crypto.PublicKey import RSA
|
|
|
|
>>>
|
|
|
|
>>> key = RSA.generate(2048)
|
|
|
|
>>> f = open('mykey.pem','w')
|
2013-06-16 11:47:16 +02:00
|
|
|
>>> f.write(key.exportKey('PEM'))
|
2012-04-10 21:26:33 +02:00
|
|
|
>>> f.close()
|
|
|
|
...
|
|
|
|
>>> f = open('mykey.pem','r')
|
|
|
|
>>> key = RSA.importKey(f.read())
|
|
|
|
|
|
|
|
Even though you may choose to directly use the methods of an RSA key object
|
2015-03-11 21:09:36 +01:00
|
|
|
to perform the primitive cryptographic operations (e.g. `RsaKey._encrypt`),
|
2012-04-10 21:26:33 +02:00
|
|
|
it is recommended to use one of the standardized schemes instead (like
|
|
|
|
`Crypto.Cipher.PKCS1_v1_5` or `Crypto.Signature.PKCS1_v1_5`).
|
|
|
|
|
|
|
|
.. _RSA: http://en.wikipedia.org/wiki/RSA_%28algorithm%29
|
|
|
|
.. _ECRYPT: http://www.ecrypt.eu.org/documents/D.SPA.17.pdf
|
|
|
|
|
2014-06-16 21:42:39 +02:00
|
|
|
:sort: generate,construct,importKey
|
2011-01-21 18:54:53 +01:00
|
|
|
"""
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2014-06-16 21:42:39 +02:00
|
|
|
__all__ = ['generate', 'construct', 'importKey', 'RSAImplementation',
|
2015-03-11 21:09:36 +01:00
|
|
|
'RsaKey', 'oid' , 'algorithmIdentifier' ]
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2010-12-28 16:26:52 -05:00
|
|
|
from Crypto.Util.py3compat import *
|
2013-06-15 23:25:49 +02:00
|
|
|
|
2010-01-21 20:14:10 +01:00
|
|
|
import binascii
|
2011-09-21 00:01:36 +02:00
|
|
|
import struct
|
2009-12-27 17:26:59 +01:00
|
|
|
|
2014-06-11 15:46:22 +02:00
|
|
|
from Crypto import Random
|
|
|
|
from Crypto.IO import PKCS8, PEM
|
|
|
|
|
|
|
|
from Crypto.Util.asn1 import (
|
|
|
|
DerNull,
|
|
|
|
DerSequence,
|
|
|
|
DerBitString,
|
|
|
|
DerObjectId,
|
|
|
|
newDerSequence,
|
|
|
|
newDerBitString
|
|
|
|
)
|
2011-01-16 21:44:10 +01:00
|
|
|
|
2014-12-05 08:12:51 -05:00
|
|
|
from Crypto.Math.Numbers import Integer
|
|
|
|
from Crypto.Math.Primality import (test_probable_prime,
|
|
|
|
generate_probable_prime, COMPOSITE)
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2013-06-15 23:25:49 +02:00
|
|
|
|
2015-03-11 21:09:36 +01:00
|
|
|
class RsaKey(object):
|
2012-04-10 21:26:33 +02:00
|
|
|
"""Class defining an actual RSA key.
|
2011-01-21 18:54:53 +01:00
|
|
|
|
2012-04-10 21:26:33 +02:00
|
|
|
:undocumented: __getstate__, __setstate__, __repr__, __getattr__
|
|
|
|
"""
|
2011-01-21 18:54:53 +01:00
|
|
|
#: Dictionary of RSA parameters.
|
|
|
|
#:
|
|
|
|
#: A public key will only have the following entries:
|
|
|
|
#:
|
|
|
|
#: - **n**, the modulus.
|
|
|
|
#: - **e**, the public exponent.
|
|
|
|
#:
|
|
|
|
#: A private key will also have:
|
|
|
|
#:
|
|
|
|
#: - **d**, the private exponent.
|
|
|
|
#: - **p**, the first factor of n.
|
|
|
|
#: - **q**, the second factor of n.
|
|
|
|
#: - **u**, the CRT coefficient (1/p) mod q.
|
2014-06-16 21:42:39 +02:00
|
|
|
_keydata = ['n', 'e', 'd', 'p', 'q', 'u']
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
def __init__(self, key_dict):
|
2014-12-05 08:12:51 -05:00
|
|
|
input_set = set(key_dict.keys())
|
|
|
|
public_set = set(('n' , 'e'))
|
|
|
|
private_set = public_set | set(('p' , 'q', 'd', 'u'))
|
|
|
|
if input_set not in (private_set, public_set):
|
|
|
|
raise ValueError("Some RSA components are missing")
|
|
|
|
self._key = dict(key_dict)
|
2008-09-18 21:42:28 -04:00
|
|
|
|
|
|
|
def __getattr__(self, attrname):
|
2014-12-05 08:12:51 -05:00
|
|
|
try:
|
|
|
|
return int(self._key[attrname])
|
|
|
|
except KeyError:
|
|
|
|
raise AttributeError(attrname)
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2014-06-16 21:42:39 +02:00
|
|
|
def _encrypt(self, plaintext):
|
|
|
|
if not 0 < plaintext < self.n:
|
2014-05-07 12:20:46 +02:00
|
|
|
raise ValueError("Plaintext too large")
|
2014-12-05 08:12:51 -05:00
|
|
|
e, n = self._key['e'], self._key['n']
|
|
|
|
return int(pow(Integer(plaintext), e, n))
|
2011-02-21 21:11:21 -05:00
|
|
|
|
2014-06-16 21:42:39 +02:00
|
|
|
def _decrypt(self, ciphertext):
|
2014-05-07 12:20:46 +02:00
|
|
|
if not 0 < ciphertext < self.n:
|
|
|
|
raise ValueError("Ciphertext too large")
|
2014-12-05 08:12:51 -05:00
|
|
|
if not self.has_private():
|
|
|
|
raise TypeError("This is not a private key")
|
|
|
|
|
|
|
|
e, d, n, p, q, u = [self._key[comp] for comp in 'e', 'd', 'n', 'p', 'q', 'u']
|
2014-05-07 12:20:46 +02:00
|
|
|
|
2011-02-21 21:11:21 -05:00
|
|
|
# Blinded RSA decryption (to prevent timing attacks):
|
|
|
|
# Step 1: Generate random secret blinding factor r, such that 0 < r < n-1
|
2015-03-11 11:26:10 -04:00
|
|
|
r = Integer.random_range(min_inclusive=1, max_exclusive=n)
|
2011-02-21 21:11:21 -05:00
|
|
|
# Step 2: Compute c' = c * r**e mod n
|
2014-12-05 08:12:51 -05:00
|
|
|
cp = Integer(ciphertext) * pow(r, e, n) % n
|
2011-02-21 21:11:21 -05:00
|
|
|
# Step 3: Compute m' = c'**d mod n (ordinary RSA decryption)
|
2014-12-05 08:12:51 -05:00
|
|
|
m1 = pow(cp, d % (p - 1), p)
|
|
|
|
m2 = pow(cp, d % (q - 1), q)
|
|
|
|
h = m2 - m1
|
|
|
|
while h < 0:
|
|
|
|
h += q
|
|
|
|
h = (h * u) % q
|
|
|
|
mp = h * p + m1
|
2011-02-21 21:11:21 -05:00
|
|
|
# Step 4: Compute m = m**(r-1) mod n
|
2015-09-23 08:58:09 +02:00
|
|
|
result = (r.inverse(n) * mp) % n
|
|
|
|
# Verify no faults occured
|
|
|
|
if ciphertext != pow(result, e, n):
|
|
|
|
raise ValueError("Fault detected in RSA decryption")
|
|
|
|
return result
|
2008-09-18 21:42:28 -04:00
|
|
|
|
|
|
|
def has_private(self):
|
2014-12-05 08:12:51 -05:00
|
|
|
return 'd' in self._key
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2014-06-16 21:42:39 +02:00
|
|
|
def publickey(self):
|
2015-03-11 21:09:36 +01:00
|
|
|
return RsaKey(dict([(k, self._key[k]) for k in 'n', 'e']))
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2014-06-16 21:42:39 +02:00
|
|
|
def __eq__(self, other):
|
2014-12-05 08:12:51 -05:00
|
|
|
return self._key == other._key
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2014-06-16 21:42:39 +02:00
|
|
|
def __ne__(self, other):
|
2014-12-05 08:12:51 -05:00
|
|
|
return self._key != other._key
|
2008-09-18 21:42:28 -04:00
|
|
|
|
|
|
|
def __getstate__(self):
|
2014-06-16 21:42:39 +02:00
|
|
|
# RSA key is not pickable
|
|
|
|
from pickle import PicklingError
|
|
|
|
raise PicklingError
|
2008-09-18 21:42:28 -04:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
attrs = []
|
2014-06-16 21:42:39 +02:00
|
|
|
for k in self._keydata:
|
2008-09-18 21:42:28 -04:00
|
|
|
if k == 'n':
|
|
|
|
attrs.append("n(%d)" % (self.size()+1,))
|
|
|
|
elif hasattr(self.key, k):
|
|
|
|
attrs.append(k)
|
|
|
|
if self.has_private():
|
|
|
|
attrs.append("private")
|
2010-12-28 16:26:52 -05:00
|
|
|
# PY3K: This is meant to be text, do not change to bytes (data)
|
2008-09-18 21:42:28 -04:00
|
|
|
return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs))
|
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
def exportKey(self, format='PEM', passphrase=None, pkcs=1, protection=None, randfunc=None):
|
2011-01-21 18:54:53 +01:00
|
|
|
"""Export this RSA key.
|
|
|
|
|
2013-06-15 23:25:49 +02:00
|
|
|
:Parameters:
|
|
|
|
format : string
|
|
|
|
The format to use for wrapping the key:
|
2011-01-16 22:05:54 +01:00
|
|
|
|
2013-06-15 23:25:49 +02:00
|
|
|
- *'DER'*. Binary encoding.
|
2012-04-12 23:16:52 +02:00
|
|
|
- *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_.
|
2011-10-10 08:11:31 +02:00
|
|
|
- *'OpenSSH'*. Textual encoding, done according to OpenSSH specification.
|
|
|
|
Only suitable for public keys (not private keys).
|
2011-01-21 18:54:53 +01:00
|
|
|
|
2013-06-15 23:25:49 +02:00
|
|
|
passphrase : string
|
|
|
|
For private keys only. The pass phrase used for deriving the encryption
|
|
|
|
key.
|
|
|
|
|
|
|
|
pkcs : integer
|
|
|
|
For *DER* and *PEM* format only.
|
|
|
|
The PKCS standard to follow for assembling the components of the key.
|
|
|
|
You have two choices:
|
|
|
|
|
|
|
|
- **1** (default): the public key is embedded into
|
|
|
|
an X.509 ``SubjectPublicKeyInfo`` DER SEQUENCE.
|
|
|
|
The private key is embedded into a `PKCS#1`_
|
|
|
|
``RSAPrivateKey`` DER SEQUENCE.
|
|
|
|
- **8**: the private key is embedded into a `PKCS#8`_
|
|
|
|
``PrivateKeyInfo`` DER SEQUENCE. This value cannot be used
|
|
|
|
for public keys.
|
|
|
|
|
|
|
|
protection : string
|
|
|
|
The encryption scheme to use for protecting the private key.
|
|
|
|
|
|
|
|
If ``None`` (default), the behavior depends on ``format``:
|
|
|
|
|
|
|
|
- For *DER*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*
|
|
|
|
scheme is used. The following operations are performed:
|
|
|
|
|
|
|
|
1. A 16 byte Triple DES key is derived from the passphrase
|
|
|
|
using `Crypto.Protocol.KDF.PBKDF2` with 8 bytes salt,
|
|
|
|
and 1 000 iterations of `Crypto.Hash.HMAC`.
|
|
|
|
2. The private key is encrypted using CBC.
|
|
|
|
3. The encrypted key is encoded according to PKCS#8.
|
2011-10-03 23:33:11 +02:00
|
|
|
|
2013-06-15 23:25:49 +02:00
|
|
|
- For *PEM*, the obsolete PEM encryption scheme is used.
|
|
|
|
It is based on MD5 for key derivation, and Triple DES for encryption.
|
2012-05-18 15:26:58 +02:00
|
|
|
|
2013-06-15 23:25:49 +02:00
|
|
|
Specifying a value for ``protection`` is only meaningful for PKCS#8
|
|
|
|
(that is, ``pkcs=8``) and only if a pass phrase is present too.
|
2012-05-18 15:26:58 +02:00
|
|
|
|
2013-06-15 23:25:49 +02:00
|
|
|
The supported schemes for PKCS#8 are listed in the
|
|
|
|
`Crypto.IO.PKCS8` module (see ``wrap_algo`` parameter).
|
2011-10-10 08:11:31 +02:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
randfunc : callable
|
|
|
|
A function that provides random bytes. Only used for PEM encoding.
|
|
|
|
The default is `Crypto.Random.get_random_bytes`.
|
|
|
|
|
2013-06-15 23:25:49 +02:00
|
|
|
:Return: A byte string with the encoded public or private half
|
|
|
|
of the key.
|
2011-01-21 18:54:53 +01:00
|
|
|
:Raise ValueError:
|
2013-06-15 23:25:49 +02:00
|
|
|
When the format is unknown or when you try to encrypt a private
|
|
|
|
key with *DER* format and PKCS#1.
|
|
|
|
:attention:
|
|
|
|
If you don't provide a pass phrase, the private key will be
|
|
|
|
exported in the clear!
|
2012-04-12 23:16:52 +02:00
|
|
|
|
2012-05-18 15:26:58 +02:00
|
|
|
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
|
|
|
|
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
|
|
|
|
.. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
|
|
|
|
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
|
2011-01-16 22:05:54 +01:00
|
|
|
"""
|
2015-03-11 11:26:10 -04:00
|
|
|
|
2011-10-18 23:20:26 +02:00
|
|
|
if passphrase is not None:
|
|
|
|
passphrase = tobytes(passphrase)
|
2015-03-11 11:26:10 -04:00
|
|
|
|
|
|
|
if randfunc is None:
|
|
|
|
randfunc = Random.get_random_bytes
|
|
|
|
|
2011-09-21 20:54:17 +02:00
|
|
|
if format=='OpenSSH':
|
2014-12-05 08:12:51 -05:00
|
|
|
eb, nb = [self._key[comp].to_bytes() for comp in 'e', 'n']
|
2011-10-18 23:20:26 +02:00
|
|
|
if bord(eb[0]) & 0x80: eb=bchr(0x00)+eb
|
|
|
|
if bord(nb[0]) & 0x80: nb=bchr(0x00)+nb
|
2012-05-28 13:19:22 +02:00
|
|
|
keyparts = [ b('ssh-rsa'), eb, nb ]
|
|
|
|
keystring = b('').join([ struct.pack(">I",len(kp))+kp for kp in keyparts])
|
|
|
|
return b('ssh-rsa ')+binascii.b2a_base64(keystring)[:-1]
|
2011-09-21 20:54:17 +02:00
|
|
|
|
2011-10-10 08:11:31 +02:00
|
|
|
# DER format is always used, even in case of PEM, which simply
|
|
|
|
# encodes it into BASE64.
|
2011-01-16 22:05:54 +01:00
|
|
|
if self.has_private():
|
2013-06-15 23:25:49 +02:00
|
|
|
binary_key = newDerSequence(
|
|
|
|
0,
|
|
|
|
self.n,
|
|
|
|
self.e,
|
|
|
|
self.d,
|
|
|
|
self.p,
|
|
|
|
self.q,
|
|
|
|
self.d % (self.p-1),
|
|
|
|
self.d % (self.q-1),
|
2014-12-05 08:12:51 -05:00
|
|
|
Integer(self.q).inverse(self.p)
|
2013-06-15 23:25:49 +02:00
|
|
|
).encode()
|
|
|
|
if pkcs==1:
|
|
|
|
keyType = 'RSA PRIVATE'
|
|
|
|
if format=='DER' and passphrase:
|
|
|
|
raise ValueError("PKCS#1 private key cannot be encrypted")
|
|
|
|
else: # PKCS#8
|
|
|
|
if format=='PEM' and protection is None:
|
|
|
|
keyType = 'PRIVATE'
|
|
|
|
binary_key = PKCS8.wrap(binary_key, oid, None)
|
|
|
|
else:
|
|
|
|
keyType = 'ENCRYPTED PRIVATE'
|
|
|
|
if not protection:
|
|
|
|
protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
|
|
|
|
binary_key = PKCS8.wrap(binary_key, oid, passphrase, protection)
|
|
|
|
passphrase = None
|
2011-01-16 22:05:54 +01:00
|
|
|
else:
|
2013-06-15 23:25:49 +02:00
|
|
|
keyType = "RSA PUBLIC"
|
|
|
|
binary_key = newDerSequence(
|
|
|
|
algorithmIdentifier,
|
|
|
|
newDerBitString(
|
|
|
|
newDerSequence( self.n, self.e )
|
|
|
|
)
|
|
|
|
).encode()
|
2011-01-16 22:05:54 +01:00
|
|
|
if format=='DER':
|
2013-06-15 23:25:49 +02:00
|
|
|
return binary_key
|
2011-01-16 22:05:54 +01:00
|
|
|
if format=='PEM':
|
2015-03-11 11:26:10 -04:00
|
|
|
pem_str = PEM.encode(binary_key, keyType+" KEY", passphrase, randfunc)
|
2013-06-15 23:25:49 +02:00
|
|
|
return tobytes(pem_str)
|
2012-05-28 13:27:42 +02:00
|
|
|
raise ValueError("Unknown key format '%s'. Cannot export the RSA key." % format)
|
2009-12-27 17:26:59 +01:00
|
|
|
|
2011-01-21 18:54:53 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
def generate(bits, randfunc=None, e=65537):
|
|
|
|
"""Create a new RSA key.
|
|
|
|
|
|
|
|
The algorithm closely follows NIST `FIPS 186-4`_ in its
|
|
|
|
sections B.3.1 and B.3.3. The modulus is the product of
|
|
|
|
two non-strong probable primes.
|
|
|
|
Each prime passes a suitable number of Miller-Rabin tests
|
|
|
|
with random bases and a single Lucas test.
|
|
|
|
|
|
|
|
:Parameters:
|
|
|
|
bits : integer
|
|
|
|
Key length, or size (in bits) of the RSA modulus.
|
|
|
|
It must be at least 1024.
|
|
|
|
The FIPS standard only defines 1024, 2048 and 3072.
|
|
|
|
randfunc : callable
|
|
|
|
Function that returns random bytes.
|
|
|
|
The default is `Crypto.Random.get_random_bytes`.
|
|
|
|
e : integer
|
|
|
|
Public RSA exponent. It must be an odd positive integer.
|
|
|
|
It is typically a small number with very few ones in its
|
|
|
|
binary representation.
|
|
|
|
The FIPS standard requires the public exponent to be
|
|
|
|
at least 65537 (the default).
|
|
|
|
|
2015-03-11 21:09:36 +01:00
|
|
|
:Return: An RSA key object (`RsaKey`).
|
2015-03-11 11:26:10 -04:00
|
|
|
|
|
|
|
.. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf
|
2011-01-21 18:54:53 +01:00
|
|
|
"""
|
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
if bits < 1024:
|
|
|
|
raise ValueError("RSA modulus length must be >= 1024")
|
|
|
|
if e % 2 == 0 or e < 3:
|
|
|
|
raise ValueError("RSA public exponent must be a positive, odd integer larger than 2.")
|
2015-02-27 21:57:21 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
if randfunc is None:
|
|
|
|
randfunc = Random.get_random_bytes
|
2014-12-05 08:12:51 -05:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
d = n = Integer(1)
|
|
|
|
e = Integer(e)
|
2014-12-05 08:12:51 -05:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
while n.size_in_bits() != bits and d < (1 << (bits // 2)):
|
|
|
|
# Generate the prime factors of n: p and q.
|
|
|
|
# By construciton, their product is always
|
|
|
|
# 2^{bits-1} < p*q < 2^bits.
|
|
|
|
size_q = bits // 2
|
|
|
|
size_p = bits - size_q
|
2015-02-27 21:57:21 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
min_p = min_q = (Integer(1) << (2 * size_q - 1)).sqrt()
|
|
|
|
if size_q != size_p:
|
|
|
|
min_p = (Integer(1) << (2 * size_p - 1)).sqrt()
|
2015-02-25 07:35:45 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
def filter_p(candidate):
|
|
|
|
return candidate > min_p and (candidate - 1).gcd(e) == 1
|
2015-02-25 07:35:45 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
p = generate_probable_prime(exact_bits=size_p,
|
|
|
|
randfunc=randfunc,
|
|
|
|
prime_filter=filter_p)
|
2015-02-27 21:57:21 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
min_distance = Integer(1) << (bits // 2 - 100)
|
2015-02-27 21:57:21 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
def filter_q(candidate):
|
|
|
|
return candidate > min_q and (candidate - 1).gcd(e) == 1 \
|
|
|
|
and abs(candidate - p) > min_distance
|
2015-02-27 21:57:21 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
q = generate_probable_prime(exact_bits=size_q,
|
|
|
|
randfunc=randfunc,
|
|
|
|
prime_filter=filter_q)
|
2015-02-27 21:57:21 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
n = p * q
|
|
|
|
lcm = (p - 1).lcm(q - 1)
|
|
|
|
d = e.inverse(lcm)
|
2014-12-05 08:12:51 -05:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
if p > q:
|
|
|
|
p, q = q, p
|
2014-12-05 08:12:51 -05:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
u = p.inverse(q)
|
2014-12-05 08:12:51 -05:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
key_dict = dict(zip(('n', 'e', 'd', 'p', 'q', 'u'),
|
|
|
|
(n, e, d, p, q, u)))
|
2015-03-11 21:09:36 +01:00
|
|
|
return RsaKey(key_dict)
|
2008-09-18 21:42:28 -04:00
|
|
|
|
2011-01-21 18:54:53 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
def construct(tup, consistency_check=True):
|
|
|
|
"""Construct an RSA key from a tuple of valid RSA components.
|
2011-01-21 18:54:53 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
The modulus **n** must be the product of two primes.
|
|
|
|
The public exponent **e** must be odd and larger than 1.
|
2011-01-21 18:54:53 +01:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
In case of a private key, the following equations must apply:
|
2013-06-17 23:25:21 +02:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
- e != 1
|
|
|
|
- p*q = n
|
2015-03-11 21:09:36 +01:00
|
|
|
- e*d = 1 mod lcm[(p-1)(q-1)]
|
2015-03-11 11:26:10 -04:00
|
|
|
- p*u = 1 mod q
|
2013-06-17 23:25:21 +02:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
:Parameters:
|
|
|
|
tup : tuple
|
|
|
|
A tuple of long integers, with at least 2 and no
|
|
|
|
more than 6 items. The items come in the following order:
|
2011-10-10 08:11:31 +02:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
1. RSA modulus (*n*).
|
|
|
|
2. Public exponent (*e*).
|
|
|
|
3. Private exponent (*d*).
|
|
|
|
Only required if the key is private.
|
|
|
|
4. First factor of *n* (*p*).
|
|
|
|
Optional, but factor q must also be present.
|
|
|
|
5. Second factor of *n* (*q*). Optional.
|
|
|
|
6. CRT coefficient, *(1/p) mod q* (*u*). Optional.
|
|
|
|
consistency_check : boolean
|
|
|
|
If *True*, the library will verify that the provided components
|
|
|
|
fulfil the main RSA properties.
|
2011-10-10 08:11:31 +02:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
:Raise ValueError:
|
|
|
|
When the key being imported fails the most basic RSA validity checks.
|
2015-03-11 21:09:36 +01:00
|
|
|
:Return: An RSA key object (`RsaKey`).
|
2015-03-11 11:26:10 -04:00
|
|
|
"""
|
2011-10-18 23:20:26 +02:00
|
|
|
|
2015-03-11 11:26:10 -04:00
|
|
|
comp_names = 'n', 'e', 'd', 'p', 'q', 'u'
|
|
|
|
key_dict = dict(zip(comp_names, map(Integer, tup)))
|
|
|
|
n, e, d, p, q, u = [key_dict.get(comp) for comp in comp_names]
|
|
|
|
|
|
|
|
if d is not None:
|
|
|
|
|
|
|
|
if None in (p, q):
|
|
|
|
# Compute factors p and q from the private exponent d.
|
|
|
|
# We assume that n has no more than two factors.
|
|
|
|
# See 8.2.2(i) in Handbook of Applied Cryptography.
|
|
|
|
ktot = d * e - 1
|
|
|
|
# The quantity d*e-1 is a multiple of phi(n), even,
|
|
|
|
# and can be represented as t*2^s.
|
|
|
|
t = ktot
|
|
|
|
while t % 2 ==0:
|
|
|
|
t //= 2
|
|
|
|
# Cycle through all multiplicative inverses in Zn.
|
|
|
|
# The algorithm is non-deterministic, but there is a 50% chance
|
|
|
|
# any candidate a leads to successful factoring.
|
|
|
|
# See "Digitalized Signatures and Public Key Functions as Intractable
|
|
|
|
# as Factorization", M. Rabin, 1979
|
|
|
|
spotted = False
|
|
|
|
a = Integer(2)
|
|
|
|
while not spotted and a < 100:
|
|
|
|
k = Integer(t)
|
|
|
|
# Cycle through all values a^{t*2^i}=a^k
|
|
|
|
while k < ktot:
|
|
|
|
cand = pow(a, k, n)
|
|
|
|
# Check if a^k is a non-trivial root of unity (mod n)
|
|
|
|
if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1:
|
|
|
|
# We have found a number such that (cand-1)(cand+1)=0 (mod n).
|
|
|
|
# Either of the terms divides n.
|
|
|
|
p = Integer(n).gcd(cand + 1)
|
|
|
|
spotted = True
|
|
|
|
break
|
|
|
|
k *= 2
|
|
|
|
# This value was not any good... let's try another!
|
|
|
|
a += 2
|
|
|
|
if not spotted:
|
|
|
|
raise ValueError("Unable to compute factors p and q from exponent d.")
|
|
|
|
# Found !
|
|
|
|
assert ((n % p) == 0)
|
|
|
|
q = n // p
|
|
|
|
|
|
|
|
if u is None:
|
|
|
|
u = p.inverse(q)
|
|
|
|
|
|
|
|
key_dict['p'] = p
|
|
|
|
key_dict['q'] = q
|
|
|
|
key_dict['u'] = u
|
|
|
|
|
|
|
|
# Build key object
|
2015-03-11 21:09:36 +01:00
|
|
|
key = RsaKey(key_dict)
|
2015-03-11 11:26:10 -04:00
|
|
|
|
|
|
|
# Very consistency of the key
|
|
|
|
fmt_error = False
|
|
|
|
if consistency_check:
|
|
|
|
# Modulus and public exponent must be coprime
|
|
|
|
fmt_error = e <= 1 or e >= n
|
|
|
|
fmt_error |= Integer(n).gcd(e) != 1
|
|
|
|
|
|
|
|
# For RSA, modulus must be odd
|
|
|
|
fmt_error |= not n & 1
|
|
|
|
|
|
|
|
if not fmt_error and key.has_private():
|
|
|
|
# Modulus and private exponent must be coprime
|
|
|
|
fmt_error = d <= 1 or d >= n
|
|
|
|
fmt_error |= Integer(n).gcd(d) != 1
|
|
|
|
# Modulus must be product of 2 primes
|
|
|
|
fmt_error |= (p * q != n)
|
|
|
|
fmt_error |= test_probable_prime(p) == COMPOSITE
|
|
|
|
fmt_error |= test_probable_prime(q) == COMPOSITE
|
|
|
|
# See Carmichael theorem
|
|
|
|
phi = (p - 1) * (q - 1)
|
|
|
|
lcm = phi // (p - 1).gcd(q - 1)
|
|
|
|
fmt_error |= (e * d % int(lcm)) != 1
|
|
|
|
if hasattr(key, 'u'):
|
|
|
|
# CRT coefficient
|
|
|
|
fmt_error |= u <= 1 or u >= q
|
|
|
|
fmt_error |= (p * u % q) != 1
|
|
|
|
else:
|
|
|
|
fmt_error = True
|
|
|
|
|
|
|
|
if fmt_error:
|
|
|
|
raise ValueError("Invalid RSA key components")
|
|
|
|
|
|
|
|
return key
|
|
|
|
|
|
|
|
|
2015-06-30 20:52:22 +00:00
|
|
|
def _importKeyDER(extern_key, passphrase):
|
2015-03-11 11:26:10 -04:00
|
|
|
"""Import an RSA key (public or private half), encoded in DER form."""
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
2015-03-18 08:42:04 +01:00
|
|
|
der = DerSequence().decode(extern_key)
|
2015-03-11 11:26:10 -04:00
|
|
|
|
|
|
|
# Try PKCS#1 first, for a private key
|
|
|
|
if len(der) == 9 and der.hasOnlyInts() and der[0] == 0:
|
|
|
|
# ASN.1 RSAPrivateKey element
|
|
|
|
del der[6:] # Remove d mod (p-1),
|
|
|
|
# d mod (q-1), and
|
|
|
|
# q^{-1} mod p
|
|
|
|
der.append(Integer(der[4]).inverse(der[5])) # Add p^{-1} mod q
|
|
|
|
del der[0] # Remove version
|
|
|
|
return construct(der[:])
|
|
|
|
|
|
|
|
# Keep on trying PKCS#1, but now for a public key
|
|
|
|
if len(der) == 2:
|
|
|
|
try:
|
|
|
|
# The DER object is an RSAPublicKey SEQUENCE with
|
|
|
|
# two elements
|
|
|
|
if der.hasOnlyInts():
|
|
|
|
return construct(der[:])
|
|
|
|
# The DER object is a SubjectPublicKeyInfo SEQUENCE
|
|
|
|
# with two elements: an 'algorithmIdentifier' and a
|
|
|
|
# 'subjectPublicKey'BIT STRING.
|
|
|
|
# 'algorithmIdentifier' takes the value given at the
|
|
|
|
# module level.
|
|
|
|
# 'subjectPublicKey' encapsulates the actual ASN.1
|
|
|
|
# RSAPublicKey element.
|
|
|
|
if der[0] == algorithmIdentifier:
|
2015-03-18 08:42:04 +01:00
|
|
|
bitmap = DerBitString().decode(der[1])
|
|
|
|
rsaPub = DerSequence().decode(bitmap.value)
|
2015-03-11 11:26:10 -04:00
|
|
|
if len(rsaPub) == 2 and rsaPub.hasOnlyInts():
|
|
|
|
return construct(rsaPub[:])
|
|
|
|
except (ValueError, EOFError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
# Try to see if this is an X.509 DER certificate
|
|
|
|
# (Certificate ASN.1 type)
|
|
|
|
if len(der) == 3:
|
|
|
|
from Crypto.PublicKey import _extract_sp_info
|
|
|
|
try:
|
|
|
|
sp_info = _extract_sp_info(der)
|
2015-06-30 20:52:22 +00:00
|
|
|
return _importKeyDER(sp_info, passphrase)
|
2015-03-11 11:26:10 -04:00
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
# Try PKCS#8 (possibly encrypted)
|
|
|
|
k = PKCS8.unwrap(extern_key, passphrase)
|
|
|
|
if k[0] == oid:
|
2015-06-30 20:52:22 +00:00
|
|
|
return _importKeyDER(k[1], passphrase)
|
2015-03-11 11:26:10 -04:00
|
|
|
|
|
|
|
except (ValueError, EOFError):
|
|
|
|
pass
|
|
|
|
|
|
|
|
raise ValueError("RSA key format is not supported")
|
|
|
|
|
2015-06-30 20:52:22 +00:00
|
|
|
def importKey(extern_key, passphrase=None):
|
2015-03-11 11:26:10 -04:00
|
|
|
"""Import an RSA key (public or private half), encoded in standard
|
|
|
|
form.
|
|
|
|
|
|
|
|
:Parameter extern_key:
|
|
|
|
The RSA key to import, encoded as a byte string.
|
|
|
|
|
|
|
|
An RSA public key can be in any of the following formats:
|
|
|
|
|
|
|
|
- X.509 certificate (binary or PEM format)
|
|
|
|
- X.509 ``subjectPublicKeyInfo`` DER SEQUENCE (binary or PEM
|
|
|
|
encoding)
|
|
|
|
- `PKCS#1`_ ``RSAPublicKey`` DER SEQUENCE (binary or PEM encoding)
|
|
|
|
- OpenSSH (textual public key only)
|
|
|
|
|
|
|
|
An RSA private key can be in any of the following formats:
|
|
|
|
|
|
|
|
- PKCS#1 ``RSAPrivateKey`` DER SEQUENCE (binary or PEM encoding)
|
|
|
|
- `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo``
|
|
|
|
DER SEQUENCE (binary or PEM encoding)
|
|
|
|
- OpenSSH (textual public key only)
|
|
|
|
|
|
|
|
For details about the PEM encoding, see `RFC1421`_/`RFC1423`_.
|
|
|
|
|
|
|
|
The private key may be encrypted by means of a certain pass phrase
|
|
|
|
either at the PEM level or at the PKCS#8 level.
|
|
|
|
:Type extern_key: string
|
|
|
|
|
|
|
|
:Parameter passphrase:
|
|
|
|
In case of an encrypted private key, this is the pass phrase from
|
|
|
|
which the decryption key is derived.
|
|
|
|
:Type passphrase: string
|
|
|
|
|
2015-03-11 21:09:36 +01:00
|
|
|
:Return: An RSA key object (`RsaKey`).
|
2015-03-11 11:26:10 -04:00
|
|
|
|
|
|
|
:Raise ValueError/IndexError/TypeError:
|
|
|
|
When the given key cannot be parsed (possibly because the pass
|
|
|
|
phrase is wrong).
|
|
|
|
|
|
|
|
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
|
|
|
|
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
|
|
|
|
.. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt
|
|
|
|
.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
|
|
|
|
"""
|
|
|
|
extern_key = tobytes(extern_key)
|
|
|
|
if passphrase is not None:
|
|
|
|
passphrase = tobytes(passphrase)
|
|
|
|
|
|
|
|
if extern_key.startswith(b('-----')):
|
|
|
|
# This is probably a PEM encoded key.
|
|
|
|
(der, marker, enc_flag) = PEM.decode(tostr(extern_key), passphrase)
|
|
|
|
if enc_flag:
|
|
|
|
passphrase = None
|
2015-06-30 20:52:22 +00:00
|
|
|
return _importKeyDER(der, passphrase)
|
2015-03-11 11:26:10 -04:00
|
|
|
|
|
|
|
if extern_key.startswith(b('ssh-rsa ')):
|
|
|
|
# This is probably an OpenSSH key
|
|
|
|
keystring = binascii.a2b_base64(extern_key.split(b(' '))[1])
|
|
|
|
keyparts = []
|
|
|
|
while len(keystring) > 4:
|
|
|
|
l = struct.unpack(">I", keystring[:4])[0]
|
|
|
|
keyparts.append(keystring[4:4 + l])
|
|
|
|
keystring = keystring[4 + l:]
|
|
|
|
e = Integer.from_bytes(keyparts[1])
|
|
|
|
n = Integer.from_bytes(keyparts[2])
|
|
|
|
return construct([n, e])
|
|
|
|
|
|
|
|
if bord(extern_key[0]) == 0x30:
|
|
|
|
# This is probably a DER encoded key
|
2015-06-30 20:52:22 +00:00
|
|
|
return _importKeyDER(extern_key, passphrase)
|
2015-03-11 11:26:10 -04:00
|
|
|
|
|
|
|
raise ValueError("RSA key format is not supported")
|
2009-12-27 17:26:59 +01:00
|
|
|
|
2013-06-15 23:25:49 +02:00
|
|
|
#: `Object ID`_ for the RSA encryption algorithm. This OID often indicates
|
|
|
|
#: a generic RSA key, even when such key will be actually used for digital
|
|
|
|
#: signatures.
|
|
|
|
#:
|
|
|
|
#: .. _`Object ID`: http://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html
|
|
|
|
oid = "1.2.840.113549.1.1.1"
|
|
|
|
|
|
|
|
#: This is the standard DER object that qualifies a cryptographic algorithm
|
|
|
|
#: in ASN.1-based data structures (e.g. X.509 certificates).
|
2011-10-10 08:11:31 +02:00
|
|
|
algorithmIdentifier = DerSequence(
|
2013-06-15 23:25:49 +02:00
|
|
|
[DerObjectId(oid).encode(), # algorithm field
|
|
|
|
DerNull().encode()] # parameters field
|
2011-10-10 08:11:31 +02:00
|
|
|
).encode()
|