# -*- coding: utf-8 -*-
# ===================================================================
#
# Copyright (c) 2016, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# ===================================================================
__all__ = ['generate', 'construct', 'import_key',
'RsaKey', 'oid']
import binascii
import struct
from Cryptodome import Random
from Cryptodome.Util.py3compat import tobytes, bord, tostr
from Cryptodome.Util.asn1 import DerSequence
from Cryptodome.Math.Numbers import Integer
from Cryptodome.Math.Primality import (test_probable_prime,
generate_probable_prime, COMPOSITE)
from Cryptodome.PublicKey import (_expand_subject_public_key_info,
_create_subject_public_key_info,
_extract_subject_public_key_info)
class RsaKey(object):
r"""Class defining an actual RSA key.
Do not instantiate directly.
Use :func:`generate`, :func:`construct` or :func:`import_key` instead.
:ivar n: RSA modulus
:vartype n: integer
:ivar e: RSA public exponent
:vartype e: integer
:ivar d: RSA private exponent
:vartype d: integer
:ivar p: First factor of the RSA modulus
:vartype p: integer
:ivar q: Second factor of the RSA modulus
:vartype q: integer
:ivar u: Chinese remainder component (:math:`p^{-1} \text{mod } q`)
:vartype q: integer
"""
def __init__(self, **kwargs):
"""Build an RSA key.
:Keywords:
n : integer
The modulus.
e : integer
The public exponent.
d : integer
The private exponent. Only required for private keys.
p : integer
The first factor of the modulus. Only required for private keys.
q : integer
The second factor of the modulus. Only required for private keys.
u : integer
The CRT coefficient (inverse of p modulo q). Only required for
private keys.
"""
input_set = set(kwargs.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")
for component, value in kwargs.items():
setattr(self, "_" + component, value)
if input_set == private_set:
self._dp = self._d % (self._p - 1) # = (e⁻¹) mod (p-1)
self._dq = self._d % (self._q - 1) # = (e⁻¹) mod (q-1)
@property
def n(self):
return int(self._n)
@property
def e(self):
return int(self._e)
@property
def d(self):
if not self.has_private():
raise AttributeError("No private exponent available for public keys")
return int(self._d)
@property
def p(self):
if not self.has_private():
raise AttributeError("No CRT component 'p' available for public keys")
return int(self._p)
@property
def q(self):
if not self.has_private():
raise AttributeError("No CRT component 'q' available for public keys")
return int(self._q)
@property
def u(self):
if not self.has_private():
raise AttributeError("No CRT component 'u' available for public keys")
return int(self._u)
def size_in_bits(self):
"""Size of the RSA modulus in bits"""
return self._n.size_in_bits()
def size_in_bytes(self):
"""The minimal amount of bytes that can hold the RSA modulus"""
return (self._n.size_in_bits() - 1) // 8 + 1
def _encrypt(self, plaintext):
if not 0 <= plaintext < self._n:
raise ValueError("Plaintext too large")
return int(pow(Integer(plaintext), self._e, self._n))
def _decrypt(self, ciphertext):
if not 0 <= ciphertext < self._n:
raise ValueError("Ciphertext too large")
if not self.has_private():
raise TypeError("This is not a private key")
# Blinded RSA decryption (to prevent timing attacks):
# Step 1: Generate random secret blinding factor r,
# such that 0 < r < n-1
r = Integer.random_range(min_inclusive=1, max_exclusive=self._n)
# Step 2: Compute c' = c * r**e mod n
cp = Integer(ciphertext) * pow(r, self._e, self._n) % self._n
# Step 3: Compute m' = c'**d mod n (normal RSA decryption)
m1 = pow(cp, self._dp, self._p)
m2 = pow(cp, self._dq, self._q)
h = ((m2 - m1) * self._u) % self._q
mp = h * self._p + m1
# Step 4: Compute m = m**(r-1) mod n
result = (r.inverse(self._n) * mp) % self._n
# Verify no faults occurred
if ciphertext != pow(result, self._e, self._n):
raise ValueError("Fault detected in RSA decryption")
return result
def has_private(self):
"""Whether this is an RSA private key"""
return hasattr(self, "_d")
def can_encrypt(self): # legacy
return True
def can_sign(self): # legacy
return True
def publickey(self):
"""A matching RSA public key.
Returns:
a new :class:`RsaKey` object
"""
return RsaKey(n=self._n, e=self._e)
def __eq__(self, other):
if self.has_private() != other.has_private():
return False
if self.n != other.n or self.e != other.e:
return False
if not self.has_private():
return True
return (self.d == other.d)
def __ne__(self, other):
return not (self == other)
def __getstate__(self):
# RSA key is not pickable
from pickle import PicklingError
raise PicklingError
def __repr__(self):
if self.has_private():
extra = ", d=%d, p=%d, q=%d, u=%d" % (int(self._d), int(self._p),
int(self._q), int(self._u))
else:
extra = ""
return "RsaKey(n=%d, e=%d%s)" % (int(self._n), int(self._e), extra)
def __str__(self):
if self.has_private():
key_type = "Private"
else:
key_type = "Public"
return "%s RSA key at 0x%X" % (key_type, id(self))
def export_key(self, format='PEM', passphrase=None, pkcs=1,
protection=None, randfunc=None):
"""Export this RSA key.
Args:
format (string):
The format to use for wrapping the key:
- *'PEM'*. (*Default*) Text encoding, done according to `RFC1421`_/`RFC1423`_.
- *'DER'*. Binary encoding.
- *'OpenSSH'*. Textual encoding, done according to OpenSSH specification.
Only suitable for public keys (not private keys).
passphrase (string):
(*For private keys only*) The pass phrase used for protecting the output.
pkcs (integer):
(*For private keys only*) The ASN.1 structure to use for
serializing the key. Note that even in case of PEM
encoding, there is an inner ASN.1 DER structure.
With ``pkcs=1`` (*default*), the private key is encoded in a
simple `PKCS#1`_ structure (``RSAPrivateKey``).
With ``pkcs=8``, the private key is encoded in a `PKCS#8`_ structure
(``PrivateKeyInfo``).
.. note::
This parameter is ignored for a public key.
For DER and PEM, an ASN.1 DER ``SubjectPublicKeyInfo``
structure is always used.
protection (string):
(*For private keys only*)
The encryption scheme to use for protecting the private key.
If ``None`` (default), the behavior depends on :attr:`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 :func:`Cryptodome.Protocol.KDF.PBKDF2` with 8 bytes salt,
and 1 000 iterations of :mod:`Cryptodome.Hash.HMAC`.
2. The private key is encrypted using CBC.
3. The encrypted key is encoded according to PKCS#8.
- For *'PEM'*, the obsolete PEM encryption scheme is used.
It is based on MD5 for key derivation, and Triple DES for encryp