# -*- coding: utf-8 -*-
#
# PublicKey/RSA.py : RSA public key primitive
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# 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.
#
# 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.
# ===================================================================
"""RSA public-key cryptography algorithm (signature and encryption).
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.
The cryptograhic strength is primarily linked to the length of the modulus *n*.
In 2012, a sufficient length is deemed to be 2048 bits. For more information,
see the most recent ECRYPT_ report.
Both RSA ciphertext and RSA signature are as big as the modulus *n* (256
bytes if *n* is 2048 bit long).
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')
>>> f.write(RSA.exportKey('PEM'))
>>> 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
to perform the primitive cryptographic operations (e.g. `_RSAobj.encrypt`),
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
:sort: generate,construct,importKey,error
"""
__revision__ = "$Id$"
__all__ = ['generate', 'construct', 'error', 'importKey', 'RSAImplementation', '_RSAobj']
import sys
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
from Crypto.Util.py21compat import *
from Crypto.Util.py3compat import *
#from Crypto.Util.python_compat import *
from Crypto.Util.number import getRandomRange, bytes_to_long, long_to_bytes
from Crypto.PublicKey import _RSA, _slowmath, pubkey
from Crypto import Random
from Crypto.Util.asn1 import DerObject, DerSequence, DerNull
import binascii
import struct
from Crypto.Util.number import inverse
from Crypto.Util.number import inverse
try:
from Crypto.PublicKey import _fastmath
except ImportError:
_fastmath = None
class _RSAobj(pubkey.pubkey):
"""Class defining an actual RSA key.
:undocumented: __getstate__, __setstate__, __repr__, __getattr__
"""
#: 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.
keydata = ['n', 'e', 'd', 'p', 'q', 'u']
def __init__(self, implementation, key, randfunc=None):
self.implementation = implementation
self.key = key
if randfunc is None:
randfunc = Random.new().read
self._randfunc = randfunc
def __getattr__(self, attrname):
if attrname in self.keydata:
# For backward compatibility, allow the user to get (not set) the
# RSA key parameters directly from this object.
return getattr(self.key, attrname)
else:
raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,))
def encrypt(self, plaintext, K):
"""Encrypt a piece of data with RSA.
:Parameter plaintext: The piece of data to encrypt with RSA. It may not
be numerically larger than the RSA module (**n**).
:Type plaintext: byte string or long
:Parameter K: A random parameter (*for compatibility only. This
value will be ignored*)
:Type K: byte string or long
:attention: this function performs the plain, primitive RSA encryption
(*textbook*). In real applications, you always need to use proper
cryptographic padding, and you should not directly encrypt data with
this method. Failure to do so may lead to security vulnerabilities.
It is recommended to use modules
`Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead.
:Return: A tuple with two items. The first item is the ciphertext
of the same type as the plaintext (string or long). The second item
is always None.
"""
return pubkey.pubkey.encrypt(self, plaintext, K)
def decrypt(self, ciphertext):
"""Decrypt a piece of data with RSA.
Decryption always takes place with blinding.
:attention: this function performs the plain, primitive RSA decryption
(*textbook*). In real applications, you always need to use proper
cryptographic padding, and you should not directly decrypt data with
this method. Failure to do so may lead to security vulnerabilities.
It is recommended to use modules
`Crypto.Cipher.PKCS1_OAEP` or `Crypto.Cipher.PKCS1_v1_5` instead.
:Parameter ciphertext: The piece of data to decrypt with RSA. It may
not be numerically larger than the RSA module (**n**). If a tuple,
the first item is the actual ciphertext; the second item is ignored.
:Type ciphertext: byte string, long or a 2-item tuple as returned by
`encrypt`
:Return: A byte string if ciphertext was a byte string or a tuple
of byte strings. A long otherwise.
"""
return pubkey.pubkey.decrypt(self, ciphertext)
def sign(self, M, K):
"""Sign a piece of data with RSA.
Signing always takes place with blinding.
:attention: this function performs the plain, primitive RSA decryption
(*textbook*). In real applications, you always need to use proper
cryptographic padding, and you should not directly sign data with
this method. Failure to do so may lead to security vulnerabilities.
It is recommended to use modules
`Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead.
:Parameter M: The piece of data to sign with RSA. It may
not be numerically larger than the RSA module (**n**).
:Type M: byte string or long
:Parameter K: A random parameter (*for compatibility only. This
value will be ignored*)
:Type K: byte string or long
:Return: A 2-item tuple. The first item is the actual signature (a
long). The second item is always None.
"""
return pubkey.pubkey.sign(self, M, K)
def verify(self, M, signature):
"""Verify the validity of an RSA signature.
:attention: this function performs the plain, primitive RSA encryption
(*textbook*). In real applications, you always need to use proper
cryptographic padding, and you should not directly verify data with
this method. Failure to do so may lead to security vulnerabilities.
It is recommended to use modules
`Crypto.Signature.PKCS1_PSS` or `Crypto.Signature.PKCS1_v1_5` instead.
:Parameter M: The expected message.
:Type M: byte string or long
:Parameter signature: The RSA signature to verify. The first item of
the tuple is the actual signature (a long not larger than the modulus
**n**), whereas the second item is always ignored.
:Type signature: A 2-item tuple as return by `sign`
:Return: True if the signature is correct, False otherwise.
"""
return pubkey.pubkey.verify(self, M, signature)
def _encrypt(self, c, K):
return (self.key._encrypt(c),)
def _decrypt(self, c):
#(ciphertext,) = c
(ciphertext,) = c[:1] # HACK - We should use the previous line
# instead, but this is more compatible and we're
# going to replace the Crypto.PublicKey API soon
# anyway.
# Blinded RSA decryption (to prevent timing attacks):
# Step 1: Generate random secret blinding factor r, such that 0 < r < n-1
r = getRandomRange(1, self.key.n-1, randfunc=self._randfunc)
# Step 2: Compute c' = c * r**e mod n
cp = self.key._blind(ciphertext, r)
# Step 3: Compute m' = c'**d mod n (ordinary RSA decryption)
mp = self.key._decrypt(cp)
# Step 4: Compute m = m**(r-1) mod n
return self.key._unblind(mp, r)
def _blind(self, m, r):
return self.key._blind(m, r)
def _unblind(self, m, r):
return self.key._unblind(m, r)
def _sign(self, m, K=None):
return (self.key._sign(m),)
def _verify(self, m, sig):
#(s,) = sig
(s,) = sig[:1] # HACK - We should use the previous line instead, but
# this is more compatible and we're going to replace
# the Crypto.PublicKey API soon anyway.
return self.key._verify(m, s)
def has_private(self):
return self.key.has_private()
def size(self):
return self.key.size()
def can_blind(self):
return True
def can_encrypt(self):
return True
def can_sign(self):
return True
def publickey(self):
return self.implementation.construct((self.key.n, self.key.e))
def __getstate__(self):
d = {}
for k in self.keydata:
try:
d[k] = getattr(self.key, k)
except AttributeError:
pass
return d
def __setstate__(self, d):
if not hasattr(self, 'implementation'):
self.implementation = RSAImplementation()
t = []
for k in self.keydata:
if k not in d:
break
t.append(d[k])
self.key = self.implementation._math.rsa_construct(*tuple(t))
def __repr__(self):
attrs = []
for k in self.keydata:
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")
# PY3K: This is meant to be text, do not change to bytes (data)
return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs))
def exportKey(self, format='PEM', passphrase=None, pkcs=1):
"""Export this RSA key.
:Parameter format: The format to use for wrapping the key.
- *'DER'*. Binary encoding, always unencrypted.
- *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_.
Unencrypted (default) or encrypted.