summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLegrandin <helderijs@gmail.com>2013-06-15 23:25:49 +0200
committerDwayne Litzenberger <dlitz@dlitz.net>2013-07-14 21:16:46 -0700
commit90d6d3dbcfb02fc441edafe6fafe6e6800009e35 (patch)
treea47b22eea2560392a673d8cba675579459452482
parent5a0ee14e9904335cb90c0dd7a4e10f1523435c52 (diff)
downloadpycrypto-90d6d3dbcfb02fc441edafe6fafe6e6800009e35.tar.gz
Added support for PKCS#8-encrypted private keys.
The patch contains the following changes: - Private RSA keys can be imported/exported in encrypted form, protected according to PKCS#8 and: * PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC. * PBKDF2WithHMAC-SHA1AndAES128-CBC * PBKDF2WithHMAC-SHA1AndAES192-CBC * PBKDF2WithHMAC-SHA1AndAES256-CBC In addition to that, it is possible to import keys i the following weak formats: * pbeWithMD5AndDES-CBC * pbeWithSHA1AndRC2-CBC * pbeWithMD5AndRC2-CBC * pbeWithSHA1AndDES-CBC - The following new module (and 1 new package) are added: * Crypto.Util.Padding for simple padding/unpadding logic * Crypto.IO._PBES for PBE-related PKCS#5 logic * Crypto.IO.PEM for PEM wrapping/unwrapping * Crypto.IO.PKCS8 for PKCS#8 wrapping/unwrapping - All Object ID (OIDs) are now in dotted form to increase readability. - Add AES support to PEM format (decode only). The PEM module can decrypt messages protected with AES-CBC. - Update RSA import test cases. - Updated to PKCS8 test cases
-rw-r--r--lib/Crypto/IO/PEM.py163
-rw-r--r--lib/Crypto/IO/PKCS8.py209
-rw-r--r--lib/Crypto/IO/_PBES.py348
-rw-r--r--lib/Crypto/IO/__init__.py32
-rw-r--r--lib/Crypto/PublicKey/RSA.py345
-rw-r--r--lib/Crypto/SelfTest/Hash/common.py2
-rw-r--r--lib/Crypto/SelfTest/Hash/test_MD2.py2
-rw-r--r--lib/Crypto/SelfTest/Hash/test_MD4.py2
-rw-r--r--lib/Crypto/SelfTest/Hash/test_MD5.py2
-rw-r--r--lib/Crypto/SelfTest/Hash/test_RIPEMD160.py2
-rw-r--r--lib/Crypto/SelfTest/Hash/test_SHA1.py2
-rw-r--r--lib/Crypto/SelfTest/Hash/test_SHA224.py2
-rw-r--r--lib/Crypto/SelfTest/Hash/test_SHA256.py2
-rw-r--r--lib/Crypto/SelfTest/Hash/test_SHA384.py2
-rw-r--r--lib/Crypto/SelfTest/Hash/test_SHA512.py2
-rw-r--r--lib/Crypto/SelfTest/IO/__init__.py34
-rw-r--r--lib/Crypto/SelfTest/IO/test_PKCS8.py419
-rw-r--r--lib/Crypto/SelfTest/PublicKey/test_importKey.py113
-rw-r--r--lib/Crypto/SelfTest/Util/__init__.py1
-rw-r--r--lib/Crypto/SelfTest/Util/test_Padding.py140
-rw-r--r--lib/Crypto/SelfTest/__init__.py1
-rw-r--r--lib/Crypto/Signature/PKCS1_v1_5.py45
-rw-r--r--lib/Crypto/Util/Padding.py103
-rw-r--r--lib/Crypto/Util/__init__.py11
-rw-r--r--lib/Crypto/Util/py21compat.py17
-rw-r--r--lib/Crypto/Util/py3compat.py6
-rw-r--r--lib/Crypto/__init__.py2
-rw-r--r--setup.py4
28 files changed, 1782 insertions, 231 deletions
diff --git a/lib/Crypto/IO/PEM.py b/lib/Crypto/IO/PEM.py
new file mode 100644
index 0000000..89a5689
--- /dev/null
+++ b/lib/Crypto/IO/PEM.py
@@ -0,0 +1,163 @@
+# -*- coding: ascii -*-
+#
+# Util/PEM.py : Privacy Enhanced Mail utilities
+#
+# ===================================================================
+# 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.
+# ===================================================================
+"""Set of functions for encapsulating data according to the PEM format.
+
+PEM (Privacy Enhanced Mail) was an IETF standard for securing emails via a
+Public Key Infrastructure. It is specified in RFC 1421-1424.
+
+Even though it has been abandoned, the simple message encapsulation it defined
+is still widely used today for encoding *binary* cryptographic objects like
+keys and certificates into text.
+"""
+
+__all__ = ['encode', 'decode']
+
+import sys
+if sys.version_info[0] == 2 and sys.version_info[1] == 1:
+ from Crypto.Util.py21compat import *
+from Crypto.Util.py3compat import *
+
+import re
+from binascii import hexlify, unhexlify, a2b_base64, b2a_base64
+
+from Crypto.Hash import MD5
+from Crypto.Util.Padding import pad, unpad
+from Crypto.Cipher import DES, DES3, AES
+from Crypto.Protocol.KDF import PBKDF1
+from Crypto.Random import get_random_bytes
+
+
+def encode(data, marker, passphrase=None, randfunc=None):
+ """Encode a piece of binary data into PEM format.
+
+ :Parameters:
+ data : byte string
+ The piece of binary data to encode.
+ marker : string
+ The marker for the PEM block (e.g. "PUBLIC KEY").
+ Note that there is no official master list for all allowed markers.
+ Still, you can refer to the OpenSSL_ source code.
+ passphrase : byte string
+ If given, the PEM block will be encrypted. The key is derived from
+ the passphrase.
+ randfunc : callable
+ Random number generation function; it accepts an integer N and returns
+ a byte string of random data, N bytes long. If not given, a new one is
+ instantiated.
+ :Returns:
+ The PEM block, as a string.
+
+ .. _OpenSSL: http://cvs.openssl.org/fileview?f=openssl/crypto/pem/pem.h&v=1.66.2.1.4.2
+ """
+
+ if randfunc is None:
+ randfunc = get_random_bytes
+
+ out = "-----BEGIN %s-----\n" % marker
+ if passphrase:
+ # We only support 3DES for encryption
+ salt = randfunc(8)
+ key = PBKDF1(passphrase, salt, 16, 1, MD5)
+ key += PBKDF1(key + passphrase, salt, 8, 1, MD5)
+ objenc = DES3.new(key, DES3.MODE_CBC, salt)
+ out += "Proc-Type: 4,ENCRYPTED\nDEK-Info: DES-EDE3-CBC,%s\n\n" %\
+ tostr(hexlify(salt).upper())
+ # Encrypt with PKCS#7 padding
+ data = objenc.encrypt(pad(data, objenc.block_size))
+
+ # Each BASE64 line can take up to 64 characters (=48 bytes of data)
+ # b2a_base64 adds a new line character!
+ chunks = [tostr(b2a_base64(data[i:i + 48]))
+ for i in range(0, len(data), 48)]
+ out += "".join(chunks)
+ out += "-----END %s-----" % marker
+ return out
+
+
+def decode(pem_data, passphrase=None):
+ """Decode a PEM block into binary.
+
+ :Parameters:
+ pem_data : string
+ The PEM block.
+ passphrase : byte string
+ If given and the PEM block is encrypted,
+ the key will be derived from the passphrase.
+ :Returns:
+ A tuple with the binary data, the marker string, and a boolean to
+ indicate if decryption was performed.
+ :Raises ValueError:
+ If decoding fails, if the PEM file is encrypted and no passphrase has
+ been provided or if the passphrase is incorrect.
+ """
+
+ # Verify Pre-Encapsulation Boundary
+ r = re.compile("\s*-----BEGIN (.*)-----\n")
+ m = r.match(pem_data)
+ if not m:
+ raise ValueError("Not a valid PEM pre boundary")
+ marker = m.group(1)
+
+ # Verify Post-Encapsulation Boundary
+ r = re.compile("-----END (.*)-----\s*$")
+ m = r.search(pem_data)
+ if not m or m.group(1) != marker:
+ raise ValueError("Not a valid PEM post boundary")
+
+ # Removes spaces and slit on lines
+ lines = pem_data.replace(" ", '').split()
+
+ # Decrypts, if necessary
+ if lines[1].startswith('Proc-Type:4,ENCRYPTED'):
+ if not passphrase:
+ raise ValueError("PEM is encrypted, but no passphrase available")
+ DEK = lines[2].split(':')
+ if len(DEK) != 2 or DEK[0] != 'DEK-Info':
+ raise ValueError("PEM encryption format not supported.")
+ algo, salt = DEK[1].split(',')
+ salt = unhexlify(tobytes(salt))
+ if algo == "DES-CBC":
+ # This is EVP_BytesToKey in OpenSSL
+ key = PBKDF1(passphrase, salt, 8, 1, MD5)
+ objdec = DES.new(key, DES.MODE_CBC, salt)
+ elif algo == "DES-EDE3-CBC":
+ # Note that EVP_BytesToKey is note exactly the same as PBKDF1
+ key = PBKDF1(passphrase, salt, 16, 1, MD5)
+ key += PBKDF1(key + passphrase, salt, 8, 1, MD5)
+ objdec = DES3.new(key, DES3.MODE_CBC, salt)
+ elif algo == "AES-128-CBC":
+ key = PBKDF1(passphrase, salt[:8], 16, 1, MD5)
+ objdec = AES.new(key, AES.MODE_CBC, salt)
+ else:
+ raise ValueError("Unsupport PEM encryption algorithm.")
+ lines = lines[2:]
+ else:
+ objdec = None
+
+ # Decode body
+ data = a2b_base64(b(''.join(lines[1:-1])))
+ enc_flag = False
+ if objdec:
+ data = unpad(objdec.decrypt(data), objdec.block_size)
+ enc_flag = True
+
+ return (data, marker, enc_flag)
diff --git a/lib/Crypto/IO/PKCS8.py b/lib/Crypto/IO/PKCS8.py
new file mode 100644
index 0000000..ceb0f5a
--- /dev/null
+++ b/lib/Crypto/IO/PKCS8.py
@@ -0,0 +1,209 @@
+# -*- coding: utf-8 -*-
+#
+# PublicKey/PKCS8.py : PKCS#8 functions
+#
+# ===================================================================
+# 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.
+# ===================================================================
+"""
+Module for handling private keys wrapped according to `PKCS#8`_.
+
+PKCS8 is a standard for storing and transferring private key information.
+The wrapped key can either be clear or encrypted.
+
+All encryption algorithms are based on passphrase-based key derivation.
+The following mechanisms are fully supported:
+
+* *PBKDF2WithHMAC-SHA1AndAES128-CBC*
+* *PBKDF2WithHMAC-SHA1AndAES192-CBC*
+* *PBKDF2WithHMAC-SHA1AndAES256-CBC*
+* *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*
+
+The following mechanisms are only supported for importing keys.
+They are much weaker than the ones listed above, and they are provided
+for backward compatibility only:
+
+* *pbeWithMD5AndRC2-CBC*
+* *pbeWithMD5AndDES-CBC*
+* *pbeWithSHA1AndRC2-CBC*
+* *pbeWithSHA1AndDES-CBC*
+
+.. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
+
+"""
+
+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.asn1 import *
+
+from Crypto.IO._PBES import PBES1, PBES2
+
+__all__ = ['wrap', 'unwrap']
+
+
+def decode_der(obj_class, binstr):
+ """Instantiate a DER object class, decode a DER binary string in it, and
+ return the object."""
+ der = obj_class()
+ der.decode(binstr)
+ return der
+
+
+def wrap(private_key, key_oid, passphrase=None, protection=None,
+ prot_params=None, key_params=None, randfunc=None):
+ """Wrap a private key into a PKCS#8 blob (clear or encrypted).
+
+ :Parameters:
+
+ private_key : byte string
+ The private key encoded in binary form. The actual encoding is
+ algorithm specific. In most cases, it is DER.
+
+ key_oid : string
+ The object identifier (OID) of the private key to wrap.
+ It is a dotted string, like "``1.2.840.113549.1.1.1``" (for RSA keys).
+
+ passphrase : (binary) string
+ The secret passphrase from which the wrapping key is derived.
+ Set it only if encryption is required.
+
+ protection : string
+ The identifier of the algorithm to use for securely wrapping the key.
+ The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'.
+
+ prot_params : dictionary
+ Parameters for the protection algorithm.
+
+ +------------------+-----------------------------------------------+
+ | Key | Description |
+ +==================+===============================================+
+ | iteration_count | The KDF algorithm is repeated several times to|
+ | | slow down brute force attacks on passwords. |
+ | | The default value is 1 000. |
+ +------------------+-----------------------------------------------+
+ | salt_size | Salt is used to thwart dictionary and rainbow |
+ | | attacks on passwords. The default value is 8 |
+ | | bytes. |
+ +------------------+-----------------------------------------------+
+
+ key_params : DER object
+ The algorithm parameters associated to the private key.
+ It is required for algorithms like DSA, but not for others like RSA.
+
+ randfunc : callable
+ Random number generation function; it should accept a single integer
+ N and return a string of random data, N bytes long.
+ If not specified, a new RNG will be instantiated
+ from ``Crypto.Random``.
+
+ :Return:
+ The PKCS#8-wrapped private key (possibly encrypted),
+ as a binary string.
+ """
+
+ if key_params is None:
+ key_params = DerNull()
+
+ #
+ # PrivateKeyInfo ::= SEQUENCE {
+ # version Version,
+ # privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
+ # privateKey PrivateKey,
+ # attributes [0] IMPLICIT Attributes OPTIONAL
+ # }
+ #
+ pk_info = newDerSequence(
+ 0,
+ newDerSequence(
+ DerObjectId(key_oid),
+ key_params
+ ),
+ newDerOctetString(private_key)
+ )
+ pk_info_der = pk_info.encode()
+
+ if not passphrase:
+ return pk_info_der
+
+ # Encryption with PBES2
+ passphrase = tobytes(passphrase)
+ if protection is None:
+ protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'
+ return PBES2.encrypt(pk_info_der, passphrase,
+ protection, prot_params, randfunc)
+
+
+def unwrap(p8_private_key, passphrase=None):
+ """Unwrap a private key from a PKCS#8 blob (clear or encrypted).
+
+ :Parameters:
+ p8_private_key : byte string
+ The private key wrapped into a PKCS#8 blob
+ passphrase : (byte) string
+ The passphrase to use to decrypt the blob (if it is encrypted).
+ :Return:
+ A tuple containing:
+
+ #. the algorithm identifier of the wrapped key (OID, dotted string)
+ #. the private key (byte string, DER encoded)
+ #. the associated parameters (byte string, DER encoded) or ``None``
+
+ :Raises ValueError:
+ If decoding fails
+ """
+
+ if passphrase:
+ passphrase = tobytes(passphrase)
+ found = False
+ for pbes in PBES1, PBES2:
+ try:
+ p8_private_key = pbes.decrypt(p8_private_key, passphrase)
+ except ValueError:
+ pass
+ else:
+ found = True
+ break
+ if not found:
+ raise ValueError("Unsupported PKCS#5 Object ID ")
+
+ pk_info = decode_der(DerSequence, p8_private_key)
+ if len(pk_info) == 2 and not passphrase:
+ raise ValueError("Not a valid clear PKCS#8 structure "
+ "(maybe it is encrypted?)")
+ if not 3 <= len(pk_info) <= 4 or pk_info[0] != 0:
+ raise ValueError("Not a valid PrivateKeyInfo SEQUENCE")
+
+ #
+ # AlgorithmIdentifier ::= SEQUENCE {
+ # algorithm OBJECT IDENTIFIER,
+ # parameters ANY DEFINED BY algorithm OPTIONAL
+ # }
+ #
+ algo_id = decode_der(DerSequence, pk_info[1])
+ if not 1 <= len(algo_id) <= 2:
+ raise ValueError("Not a valid AlgorithmIdentifier SEQUENCE")
+ algo = decode_der(DerObjectId, algo_id[0]).value
+ private_key = decode_der(DerOctetString, pk_info[2]).payload
+ if len(algo_id) == 2 and algo_id[1] != b('\x05\x00'):
+ params = algo_id[1]
+ else:
+ params = None
+ return (algo, private_key, params)
diff --git a/lib/Crypto/IO/_PBES.py b/lib/Crypto/IO/_PBES.py
new file mode 100644
index 0000000..42d5dbc
--- /dev/null
+++ b/lib/Crypto/IO/_PBES.py
@@ -0,0 +1,348 @@
+#
+# PublicKey/_PBES.py : Password-Based Encryption functions
+#
+# ===================================================================
+# 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.
+# ===================================================================
+
+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 import Random
+from Crypto.Util.asn1 import *
+
+from Crypto.Util.Padding import pad, unpad
+from Crypto.Hash import MD5, SHA1
+from Crypto.Cipher import DES, ARC2, DES3, AES
+from Crypto.Protocol.KDF import PBKDF1, PBKDF2
+
+
+# These are the ASN.1 definitions used by the PBES1/2 logic:
+#
+# EncryptedPrivateKeyInfo ::= SEQUENCE {
+# encryptionAlgorithm EncryptionAlgorithmIdentifier,
+# encryptedData EncryptedData
+# }
+#
+# EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
+#
+# EncryptedData ::= OCTET STRING
+#
+# AlgorithmIdentifier ::= SEQUENCE {
+# algorithm OBJECT IDENTIFIER,
+# parameters ANY DEFINED BY algorithm OPTIONAL
+# }
+#
+# PBEParameter ::= SEQUENCE {
+# salt OCTET STRING (SIZE(8)),
+# iterationCount INTEGER
+# }
+#
+# PBES2-params ::= SEQUENCE {
+# keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
+# encryptionScheme AlgorithmIdentifier {{PBES2-Encs}}
+# }
+#
+# PBKDF2-params ::= SEQUENCE {
+# salt CHOICE {
+# specified OCTET STRING,
+# otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}}
+# },
+# iterationCount INTEGER (1..MAX),
+# keyLength INTEGER (1..MAX) OPTIONAL,
+# prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1
+# }
+#
+
+
+def decode_der(obj_class, binstr):
+ """Instantiate a DER object class, decode a DER binary string in it, and
+ return the object."""
+ der = obj_class()
+ der.decode(binstr)
+ return der
+
+
+class PBES1(object):
+ """Deprecated encryption scheme with password-based key derivation
+ (originally defined in PKCS#5 v1.5, but still present in `v2.0`__).
+
+ .. __: http://www.ietf.org/rfc/rfc2898.txt
+ """
+
+ def decrypt(data, passphrase):
+ """Decrypt a piece of data using a passphrase and *PBES1*.
+
+ The algorithm to use is automatically detected.
+
+ :Parameters:
+ data : byte string
+ The piece of data to decrypt.
+ passphrase : byte string
+ The passphrase to use for decrypting the data.
+ :Returns:
+ The decrypted data, as a binary string.
+ """
+
+ encrypted_private_key_info = decode_der(DerSequence, data)
+ encrypted_algorithm = decode_der(
+ DerSequence,
+ encrypted_private_key_info[0]
+ )
+ encrypted_data = decode_der(
+ DerOctetString,
+ encrypted_private_key_info[1]
+ ).payload
+
+ pbe_oid = decode_der(DerObjectId, encrypted_algorithm[0]).value
+ cipher_params = {}
+ if pbe_oid == "1.2.840.113549.1.5.3":
+ # PBE_MD5_DES_CBC
+ hashmod = MD5
+ ciphermod = DES
+ elif pbe_oid == "1.2.840.113549.1.5.6":
+ # PBE_MD5_RC2_CBC
+ hashmod = MD5
+ ciphermod = ARC2
+ cipher_params['effective_keylen'] = 64
+ elif pbe_oid == "1.2.840.113549.1.5.10":
+ # PBE_SHA1_DES_CBC
+ hashmod = SHA1
+ ciphermod = DES
+ elif pbe_oid == "1.2.840.113549.1.5.11":
+ # PBE_SHA1_RC2_CBC
+ hashmod = SHA1
+ ciphermod = ARC2
+ cipher_params['effective_keylen'] = 64
+ else:
+ raise ValueError("Unknown OID")
+
+ pbe_params = decode_der(DerSequence, encrypted_algorithm[1])
+ salt = decode_der(DerOctetString, pbe_params[0]).payload
+ iterations = pbe_params[1]
+
+ key_iv = PBKDF1(passphrase, salt, 16, iterations, hashmod)
+ key, iv = key_iv[:8], key_iv[8:]
+
+ cipher = ciphermod.new(key, ciphermod.MODE_CBC, iv, **cipher_params)
+ pt = cipher.decrypt(encrypted_data)
+ return unpad(pt, cipher.block_size)
+ decrypt = staticmethod(decrypt)
+
+
+class PBES2(object):
+ """Encryption scheme with password-based key derivation
+ (defined in `PKCS#5 v2.0`__).
+
+ .. __: http://www.ietf.org/rfc/rfc2898.txt."""
+
+ def encrypt(data, passphrase, protection, prot_params=None, randfunc=None):
+ """Encrypt a piece of data using a passphrase and *PBES2*.
+
+ :Parameters:
+ data : byte string
+ The piece of data to encrypt.
+ passphrase : byte string
+ The passphrase to use for encrypting the data.
+ protection : string
+ The identifier of the encryption algorithm to use.
+ The default value is '``PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC``'.
+ prot_params : dictionary
+ Parameters of the protection algorithm.
+
+ +------------------+-----------------------------------------------+
+ | Key | Description |
+ +==================+===============================================+
+ | iteration_count | The KDF algorithm is repeated several times to|
+ | | slow down brute force attacks on passwords. |
+ | | The default value is 1 000. |
+ +------------------+-----------------------------------------------+
+ | salt_size | Salt is used to thwart dictionary and rainbow |
+ | | attacks on passwords. The default value is 8 |
+ | | bytes. |
+ +------------------+-----------------------------------------------+
+
+ randfunc : callable
+ Random number generation function; it should accept
+ a single integer N and return a string of random data,
+ N bytes long. If not specified, a new RNG will be
+ instantiated from ``Crypto.Random``.
+
+ :Returns:
+ The encrypted data, as a binary string.
+ """
+
+ if prot_params is None:
+ prot_params = {}
+
+ if randfunc is None:
+ randfunc = Random.new().read
+
+ if protection == 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC':
+ key_size = 24
+ module = DES3
+ protection = DES3.MODE_CBC
+ enc_oid = "1.2.840.113549.3.7"
+ elif protection == 'PBKDF2WithHMAC-SHA1AndAES128-CBC':
+ key_size = 16
+ module = AES
+ protection = AES.MODE_CBC
+ enc_oid = "2.16.840.1.101.3.4.1.2"
+ elif protection == 'PBKDF2WithHMAC-SHA1AndAES192-CBC':
+ key_size = 24
+ module = AES
+ protection = AES.MODE_CBC
+ enc_oid = "2.16.840.1.101.3.4.1.22"
+ elif protection == 'PBKDF2WithHMAC-SHA1AndAES256-CBC':
+ key_size = 32
+ module = AES
+ protection = AES.MODE_CBC
+ enc_oid = "2.16.840.1.101.3.4.1.42"
+ else:
+ raise ValueError("Unknown mode")
+
+ # Get random data
+ iv = randfunc(module.block_size)
+ salt = randfunc(prot_params.get("salt_size", 8))
+
+ # Derive key from password
+ count = prot_params.get("iteration_count", 1000)
+ key = PBKDF2(passphrase, salt, key_size, count)
+ key_derivation_func = newDerSequence(
+ DerObjectId("1.2.840.113549.1.5.12"), # PBKDF2
+ newDerSequence(
+ DerOctetString(salt),
+ DerInteger(count)
+ )
+ )
+
+ # Create cipher and use it
+ cipher = module.new(key, protection, iv)
+ encrypted_data = cipher.encrypt(pad(data, cipher.block_size))
+ encryption_scheme = newDerSequence(
+ DerObjectId(enc_oid),
+ DerOctetString(iv)
+ )
+
+ # Result
+ encrypted_private_key_info = newDerSequence(
+ # encryptionAlgorithm
+ newDerSequence(
+ DerObjectId("1.2.840.113549.1.5.13"), # PBES2
+ newDerSequence(
+ key_derivation_func,
+ encryption_scheme
+ ),
+ ),
+ DerOctetString(encrypted_data)
+ )
+ return encrypted_private_key_info.encode()
+ encrypt = staticmethod(encrypt)
+
+ def decrypt(data, passphrase):
+ """Decrypt a piece of data using a passphrase and *PBES2*.
+
+ The algorithm to use is automatically detected.
+
+ :Parameters:
+ data : byte string
+ The piece of data to decrypt.
+ passphrase : byte string
+ The passphrase to use for decrypting the data.
+ :Returns:
+ The decrypted data, as a binary string.
+ """
+
+ encrypted_private_key_info = decode_der(DerSequence, data)
+ encryption_algorithm = decode_der(
+ DerSequence,
+ encrypted_private_key_info[0]
+ )
+ encrypted_data = decode_der(
+ DerOctetString,
+ encrypted_private_key_info[1]
+ ).payload
+
+ pbe_oid = decode_der(DerObjectId, encryption_algorithm[0]).value
+ if pbe_oid != "1.2.840.113549.1.5.13":
+ raise ValueError("Not a PBES2 object")
+
+ pbes2_params = decode_der(DerSequence, encryption_algorithm[1])
+
+ ### Key Derivation Function selection
+ key_derivation_func = decode_der(DerSequence, pbes2_params[0])
+ key_derivation_oid = decode_der(
+ DerObjectId,
+ key_derivation_func[0]
+ ).value
+
+ # For now, we only support PBKDF2
+ if key_derivation_oid != "1.2.840.113549.1.5.12":
+ raise ValueError("Unknown KDF")
+
+ pbkdf2_params = decode_der(DerSequence, key_derivation_func[1])
+ salt = decode_der(DerOctetString, pbkdf2_params[0]).payload
+ iteration_count = pbkdf2_params[1]
+ if len(pbkdf2_params) > 2:
+ pbkdf2_key_length = pbkdf2_params[2]
+ else:
+ pbkdf2_key_length = None
+ if len(pbkdf2_params) > 3:
+ raise ValueError("Unsupported PRF for PBKDF2")
+
+ ### Cipher selection
+ encryption_scheme = decode_der(DerSequence, pbes2_params[1])
+ encryption_oid = decode_der(
+ DerObjectId,
+ encryption_scheme[0]
+ ).value
+
+ if encryption_oid == "1.2.840.113549.3.7":
+ # DES_EDE3_CBC
+ ciphermod = DES3
+ key_size = 24
+ elif encryption_oid == "2.16.840.1.101.3.4.1.2":
+ # AES128_CBC
+ ciphermod = AES
+ key_size = 16
+ elif encryption_oid == "2.16.840.1.101.3.4.1.22":
+ # AES192_CBC
+ ciphermod = AES
+ key_size = 24
+ elif encryption_oid == "2.16.840.1.101.3.4.1.42":
+ # AES256_CBC
+ ciphermod = AES
+ key_size = 32
+ else:
+ raise ValueError("Unsupported cipher")
+
+ if pbkdf2_key_length and pbkdf2_key_length != key_size:
+ raise ValueError("Mismatch between PBKDF2 parameters"
+ " and selected cipher")
+
+ IV = decode_der(DerOctetString, encryption_scheme[1]).payload
+
+ # Create cipher
+ key = PBKDF2(passphrase, salt, key_size, iteration_count)
+ cipher = ciphermod.new(key, ciphermod.MODE_CBC, IV)
+
+ # Decrypt data
+ pt = cipher.decrypt(encrypted_data)
+ return unpad(pt, cipher.block_size)
+ decrypt = staticmethod(decrypt)
diff --git a/lib/Crypto/IO/__init__.py b/lib/Crypto/IO/__init__.py
new file mode 100644
index 0000000..86776c4
--- /dev/null
+++ b/lib/Crypto/IO/__init__.py
@@ -0,0 +1,32 @@
+# -*- coding: utf-8 -*-
+#
+# ===================================================================
+# 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.
+# ===================================================================
+
+"""
+Modules for reading and writing cryptographic data.
+
+======================== =============================================
+Module Description
+======================== =============================================
+Crypto.Util.PEM Set of functions for encapsulating data according to the PEM format.
+Crypto.Util.PKCS8 Set of functions for wrapping/unwrapping private keys.
+======================== =============================================
+"""
+
+__all__ = ['PEM', 'PKCS8']
diff --git a/lib/Crypto/PublicKey/RSA.py b/lib/Crypto/PublicKey/RSA.py
index 01ee84f..f73cf5b 100644
--- a/lib/Crypto/PublicKey/RSA.py
+++ b/lib/Crypto/PublicKey/RSA.py
@@ -65,31 +65,39 @@ it is recommended to use one of the standardized schemes instead (like
__revision__ = "$Id$"
-__all__ = ['generate', 'construct', 'error', 'importKey', 'RSAImplementation', '_RSAobj']
+__all__ = ['generate', 'construct', 'error', 'importKey', 'RSAImplementation',
+ '_RSAobj', 'oid' , 'algorithmIdentifier' ]
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.IO import PKCS8, PEM
from Crypto import Random
-from Crypto.Util.asn1 import DerObject, DerSequence, DerNull
+from Crypto.Util.asn1 import *
+
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
+def decode_der(obj_class, binstr):
+ """Instantiate a DER object class, decode a DER binary string in it, and
+ return the object."""
+ der = obj_class()
+ der.decode(binstr)
+ return der
+
class _RSAobj(pubkey.pubkey):
"""Class defining an actual RSA key.
@@ -307,36 +315,66 @@ class _RSAobj(pubkey.pubkey):
# 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):
+ def exportKey(self, format='PEM', passphrase=None, pkcs=1, protection=None):
"""Export this RSA key.
- :Parameter format: The format to use for wrapping the key.
+ :Parameters:
+ format : string
+ The format to use for wrapping the key:
- - *'DER'*. Binary encoding, always unencrypted.
+ - *'DER'*. Binary encoding.
- *'PEM'*. Textual encoding, done according to `RFC1421`_/`RFC1423`_.
- Unencrypted (default) or encrypted.
- *'OpenSSH'*. Textual encoding, done according to OpenSSH specification.
Only suitable for public keys (not private keys).
- :Type format: string
- :Parameter passphrase: In case of PEM, the pass phrase to derive the encryption key from.
- :Type passphrase: string
+ 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.
- :Parameter pkcs: The PKCS standard to follow for assembling the key.
- You have two choices:
+ - For *PEM*, the obsolete PEM encryption scheme is used.
+ It is based on MD5 for key derivation, and Triple DES for encryption.
- - with **1**, the public key is embedded into an X.509 `SubjectPublicKeyInfo` DER SEQUENCE.
- The private key is embedded into a `PKCS#1`_ `RSAPrivateKey` DER SEQUENCE.
- This mode is the default.
- - with **8**, the private key is embedded into a `PKCS#8`_ `PrivateKeyInfo` DER SEQUENCE.
- This mode is not available for public keys.
+ Specifying a value for ``protection`` is only meaningful for PKCS#8
+ (that is, ``pkcs=8``) and only if a pass phrase is present too.
- PKCS standards are not relevant for the *OpenSSH* format.
- :Type pkcs: integer
+ The supported schemes for PKCS#8 are listed in the
+ `Crypto.IO.PKCS8` module (see ``wrap_algo`` parameter).
- :Return: A byte string with the encoded public or private half.
+ :Return: A byte string with the encoded public or private half
+ of the key.
:Raise ValueError:
- When the format is unknown.
+ 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!
.. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt
.. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt
@@ -356,52 +394,45 @@ class _RSAobj(pubkey.pubkey):
# DER format is always used, even in case of PEM, which simply
# encodes it into BASE64.
- der = DerSequence()
if self.has_private():
- keyType= { 1: 'RSA PRIVATE', 8: 'PRIVATE' }[pkcs]
- der[:] = [ 0, self.n, self.e, self.d, self.p, self.q,
- self.d % (self.p-1), self.d % (self.q-1),
- inverse(self.q, self.p) ]
- if pkcs==8:
- derkey = der.encode()
- der = DerSequence([0])
- der.append(algorithmIdentifier)
- der.append(DerObject('OCTET STRING', derkey).encode())
+ binary_key = newDerSequence(
+ 0,
+ self.n,
+ self.e,
+ self.d,
+ self.p,
+ self.q,
+ self.d % (self.p-1),
+ self.d % (self.q-1),
+ inverse(self.q, self.p)
+ ).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
else:
- keyType = "PUBLIC"
- der.append(algorithmIdentifier)
- bitmap = DerObject('BIT STRING')
- derPK = DerSequence( [ self.n, self.e ] )
- bitmap.payload = bchr(0x00) + derPK.encode()
- der.append(bitmap.encode())
+ keyType = "RSA PUBLIC"
+ binary_key = newDerSequence(
+ algorithmIdentifier,
+ newDerBitString(
+ newDerSequence( self.n, self.e )
+ )
+ ).encode()
if format=='DER':
- return der.encode()
+ return binary_key
if format=='PEM':
- pem = b("-----BEGIN " + keyType + " KEY-----\n")
- objenc = None
- if passphrase and keyType.endswith('PRIVATE'):
- # We only support 3DES for encryption
- import Crypto.Hash.MD5
- from Crypto.Cipher import DES3
- from Crypto.Protocol.KDF import PBKDF1
- salt = self._randfunc(8)
- key = PBKDF1(passphrase, salt, 16, 1, Crypto.Hash.MD5)
- key += PBKDF1(key+passphrase, salt, 8, 1, Crypto.Hash.MD5)
- objenc = DES3.new(key, Crypto.Cipher.DES3.MODE_CBC, salt)
- pem += b('Proc-Type: 4,ENCRYPTED\n')
- pem += b('DEK-Info: DES-EDE3-CBC,') + binascii.b2a_hex(salt).upper() + b('\n\n')
-
- binaryKey = der.encode()
- if objenc:
- # Add PKCS#7-like padding
- padding = objenc.block_size-len(binaryKey)%objenc.block_size
- binaryKey = objenc.encrypt(binaryKey+bchr(padding)*padding)
-
- # Each BASE64 line can take up to 64 characters (=48 bytes of data)
- chunks = [ binascii.b2a_base64(binaryKey[i:i+48]) for i in range(0, len(binaryKey), 48) ]
- pem += b('').join(chunks)
- pem += b("-----END " + keyType + " KEY-----")
- return pem
+ pem_str = PEM.encode(binary_key, keyType+" KEY", passphrase, self._randfunc)
+ return tobytes(pem_str)
raise ValueError("Unknown key format '%s'. Cannot export the RSA key." % format)
class RSAImplementation(object):
@@ -541,159 +572,139 @@ class RSAImplementation(object):
key = self._math.rsa_construct(*tup)
return _RSAobj(self, key)
- def _importKeyDER(self, externKey):
+ def _importKeyDER(self, extern_key, passphrase=None):
"""Import an RSA key (public or private half), encoded in DER form."""
try:
- der = DerSequence()
- der.decode(externKey, True)
+ der = decode_der(DerSequence, extern_key)
# Try PKCS#1 first, for a private key
- if len(der)==9 and der.hasOnlyInts() and der[0]==0:
+ 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(inverse(der[4],der[5])) # Add p^{-1} mod q
+ del der[6:] # Remove d mod (p-1),
+ # d mod (q-1), and
+ # q^{-1} mod p
+ der.append(inverse(der[4], der[5])) # Add p^{-1} mod q
del der[0] # Remove version
return self.construct(der[:])
# Keep on trying PKCS#1, but now for a public key
- if len(der)==2:
- # The DER object is an RSAPublicKey SEQUENCE with two elements
- if der.hasOnlyInts():
- return self.construct(der[:])
- # The DER object is a SubjectPublicKeyInfo SEQUENCE with two elements:
- # an 'algorithm' (or 'algorithmIdentifier') SEQUENCE and a 'subjectPublicKey' BIT STRING.
- # 'algorithm' takes the value given a few lines above.
- # 'subjectPublicKey' encapsulates the actual ASN.1 RSAPublicKey element.
- if der[0]==algorithmIdentifier:
- bitmap = DerObject()
- bitmap.decode(der[1], True)
- if bitmap.isType('BIT STRING') and bord(bitmap.payload[0])==0x00:
- der.decode(bitmap.payload[1:], True)
- if len(der)==2 and der.hasOnlyInts():
- return self.construct(der[:])
-
- # Try unencrypted PKCS#8
- if der[0]==0:
- # The second element in the SEQUENCE is algorithmIdentifier.
- # It must say RSA (see above for description).
- if der[1]==algorithmIdentifier:
- privateKey = DerObject()
- privateKey.decode(der[2], True)
- if privateKey.isType('OCTET STRING'):
- return self._importKeyDER(privateKey.payload)
-
- except (ValueError, IndexError):
+ if len(der) == 2:
+ try:
+ # The DER object is an RSAPublicKey SEQUENCE with
+ # two elements
+ if der.hasOnlyInts():
+ return self.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:
+ bitmap = decode_der(DerBitString, der[1])
+ rsaPub = decode_der(DerSequence, bitmap.value)
+ if len(rsaPub) == 2 and rsaPub.hasOnlyInts():
+ return self.construct(rsaPub[:])
+ except (ValueError, EOFError):
+ pass
+
+ # Try PKCS#8 (possibly encrypted)
+ k = PKCS8.unwrap(extern_key, passphrase)
+ if k[0] == oid:
+ return self._importKeyDER(k[1], passphrase)
+
+ except (ValueError, EOFError):
pass
raise ValueError("RSA key format is not supported")
- def importKey(self, externKey, passphrase=None):
- """Import an RSA key (public or private half), encoded in standard form.
+ def importKey(self, extern_key, passphrase=None):
+ """Import an RSA key (public or private half), encoded in standard
+ form.
- :Parameter externKey:
+ :Parameter extern_key:
The RSA key to import, encoded as a string.
An RSA public key can be in any of the following formats:
- - X.509 `subjectPublicKeyInfo` DER SEQUENCE (binary or PEM encoding)
- - `PKCS#1`_ `RSAPublicKey` DER SEQUENCE (binary or PEM encoding)
+ - 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` DER SEQUENCE (binary or PEM encoding)
+ - 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`_.
-
- In case of PEM encoding, the private key can be encrypted with DES or 3TDES according to a certain ``pass phrase``.
- Only OpenSSL-compatible pass phrases are supported.
- :Type externKey: string
+
+ 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 PEM key, this is the pass phrase from which the encryption key is derived.
+ In case of an encrypted private key, this is the pass phrase from
+ which the decryption key is derived.
:Type passphrase: string
-
+
:Return: An RSA key object (`_RSAobj`).
:Raise ValueError/IndexError/TypeError:
- When the given key cannot be parsed (possibly because the pass phrase is wrong).
+ 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
"""
- externKey = tobytes(externKey)
+ extern_key = tobytes(extern_key)
if passphrase is not None:
passphrase = tobytes(passphrase)
- if externKey.startswith(b('-----')):
- # This is probably a PEM encoded key
- lines = externKey.replace(b(" "),b('')).split()
- keyobj = None
-
- # The encrypted PEM format
- if lines[1].startswith(b('Proc-Type:4,ENCRYPTED')):
- DEK = lines[2].split(b(':'))
- if len(DEK)!=2 or DEK[0]!=b('DEK-Info') or not passphrase:
- raise ValueError("PEM encryption format not supported.")
- algo, salt = DEK[1].split(b(','))
- salt = binascii.a2b_hex(salt)
- import Crypto.Hash.MD5
- from Crypto.Cipher import DES, DES3
- from Crypto.Protocol.KDF import PBKDF1
- if algo==b("DES-CBC"):
- # This is EVP_BytesToKey in OpenSSL
- key = PBKDF1(passphrase, salt, 8, 1, Crypto.Hash.MD5)
- keyobj = DES.new(key, Crypto.Cipher.DES.MODE_CBC, salt)
- elif algo==b("DES-EDE3-CBC"):
- # Note that EVP_BytesToKey is note exactly the same as PBKDF1
- key = PBKDF1(passphrase, salt, 16, 1, Crypto.Hash.MD5)
- key += PBKDF1(key+passphrase, salt, 8, 1, Crypto.Hash.MD5)
- keyobj = DES3.new(key, Crypto.Cipher.DES3.MODE_CBC, salt)
- else:
- raise ValueError("Unsupport PEM encryption algorithm.")
- lines = lines[2:]
-
- der = binascii.a2b_base64(b('').join(lines[1:-1]))
- if keyobj:
- der = keyobj.decrypt(der)
- padding = bord(der[-1])
- der = der[:-padding]
- return self._importKeyDER(der)
-
- if externKey.startswith(b('ssh-rsa ')):
+ 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
+ return self._importKeyDER(der, passphrase)
+
+ if extern_key.startswith(b('ssh-rsa ')):
# This is probably an OpenSSH key
- keystring = binascii.a2b_base64(externKey.split(b(' '))[1])
+ 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:]
+ while len(keystring) > 4:
+ l = struct.unpack(">I", keystring[:4])[0]
+ keyparts.append(keystring[4:4 + l])
+ keystring = keystring[4 + l:]
e = bytes_to_long(keyparts[1])
n = bytes_to_long(keyparts[2])
return self.construct([n, e])
- if bord(externKey[0])==0x30:
+
+ if bord(extern_key[0]) == 0x30:
# This is probably a DER encoded key
- return self._importKeyDER(externKey)
-
+ return self._importKeyDER(extern_key, passphrase)
+
raise ValueError("RSA key format is not supported")
-#: This is the ASN.1 DER object that qualifies an algorithm as
-#: compliant to PKCS#1 (that is, the standard RSA).
-# It is found in all 'algorithm' fields (also called 'algorithmIdentifier').
-# It is a SEQUENCE with the oid assigned to RSA and with its parameters (none).
-# 0x06 0x09 OBJECT IDENTIFIER, 9 bytes of payload
-# 0x2A 0x86 0x48 0x86 0xF7 0x0D 0x01 0x01 0x01
-# rsaEncryption (1 2 840 113549 1 1 1) (PKCS #1)
-# 0x05 0x00 NULL
+#: `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).
algorithmIdentifier = DerSequence(
- [ b('\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01'),
- DerNull().encode() ]
+ [DerObjectId(oid).encode(), # algorithm field
+ DerNull().encode()] # parameters field
).encode()
_impl = RSAImplementation()
diff --git a/lib/Crypto/SelfTest/Hash/common.py b/lib/Crypto/SelfTest/Hash/common.py
index e722800..48cebe7 100644
--- a/lib/Crypto/SelfTest/Hash/common.py
+++ b/lib/Crypto/SelfTest/Hash/common.py
@@ -222,7 +222,7 @@ def make_hash_tests(module, module_name, test_data, digest_size, oid=None):
name = "%s #%d: digest_size" % (module_name, i+1)
tests.append(HashDigestSizeSelfTest(module, name, digest_size))
if oid is not None:
- tests.append(HashTestOID(module, b(oid)))
+ tests.append(HashTestOID(module, oid))
tests.append(HashDocStringTest(module))
if getattr(module, 'name', None) is not None:
tests.append(GenericHashConstructorTest(module))
diff --git a/lib/Crypto/SelfTest/Hash/test_MD2.py b/lib/Crypto/SelfTest/Hash/test_MD2.py
index db636d4..fd03e78 100644
--- a/lib/Crypto/SelfTest/Hash/test_MD2.py
+++ b/lib/Crypto/SelfTest/Hash/test_MD2.py
@@ -54,7 +54,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(MD2, "MD2", test_data,
digest_size=16,
- oid="\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02")
+ oid="1.2.840.113549.2.2")
if __name__ == '__main__':
import unittest
diff --git a/lib/Crypto/SelfTest/Hash/test_MD4.py b/lib/Crypto/SelfTest/Hash/test_MD4.py
index 1727bb6..7dbf49f 100644
--- a/lib/Crypto/SelfTest/Hash/test_MD4.py
+++ b/lib/Crypto/SelfTest/Hash/test_MD4.py
@@ -54,7 +54,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(MD4, "MD4", test_data,
digest_size=16,
- oid="\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04")
+ oid="1.2.840.113549.2.4")
if __name__ == '__main__':
import unittest
diff --git a/lib/Crypto/SelfTest/Hash/test_MD5.py b/lib/Crypto/SelfTest/Hash/test_MD5.py
index 2e293fc..0683113 100644
--- a/lib/Crypto/SelfTest/Hash/test_MD5.py
+++ b/lib/Crypto/SelfTest/Hash/test_MD5.py
@@ -54,7 +54,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(MD5, "MD5", test_data,
digest_size=16,
- oid="\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05")
+ oid="1.2.840.113549.2.5")
if __name__ == '__main__':
import unittest
diff --git a/lib/Crypto/SelfTest/Hash/test_RIPEMD160.py b/lib/Crypto/SelfTest/Hash/test_RIPEMD160.py
index d476249..b0d6980 100644
--- a/lib/Crypto/SelfTest/Hash/test_RIPEMD160.py
+++ b/lib/Crypto/SelfTest/Hash/test_RIPEMD160.py
@@ -63,7 +63,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(RIPEMD160, "RIPEMD160", test_data,
digest_size=20,
- oid="\x06\x05\x2b\x24\x03\02\x01")
+ oid="1.3.36.3.2.1")
if __name__ == '__main__':
import unittest
diff --git a/lib/Crypto/SelfTest/Hash/test_SHA1.py b/lib/Crypto/SelfTest/Hash/test_SHA1.py
index 83bd6d2..436f7de 100644
--- a/lib/Crypto/SelfTest/Hash/test_SHA1.py
+++ b/lib/Crypto/SelfTest/Hash/test_SHA1.py
@@ -54,7 +54,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(SHA1, "SHA1", test_data,
digest_size=20,
- oid="\x06\x05\x2B\x0E\x03\x02\x1A")
+ oid="1.3.14.3.2.26")
if __name__ == '__main__':
import unittest
diff --git a/lib/Crypto/SelfTest/Hash/test_SHA224.py b/lib/Crypto/SelfTest/Hash/test_SHA224.py
index a60f35a..eb28ebc 100644
--- a/lib/Crypto/SelfTest/Hash/test_SHA224.py
+++ b/lib/Crypto/SelfTest/Hash/test_SHA224.py
@@ -55,7 +55,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(SHA224, "SHA224", test_data,
digest_size=28,
- oid='\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04')
+ oid='2.16.840.1.101.3.4.2.4')
if __name__ == '__main__':
import unittest
diff --git a/lib/Crypto/SelfTest/Hash/test_SHA256.py b/lib/Crypto/SelfTest/Hash/test_SHA256.py
index 4b45110..50bdba8 100644
--- a/lib/Crypto/SelfTest/Hash/test_SHA256.py
+++ b/lib/Crypto/SelfTest/Hash/test_SHA256.py
@@ -81,7 +81,7 @@ def get_tests(config={}):
from common import make_hash_tests
tests = make_hash_tests(SHA256, "SHA256", test_data,
digest_size=32,
- oid="\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01")
+ oid="2.16.840.1.101.3.4.2.1")
if config.get('slow_tests'):
tests += [LargeSHA256Test()]
diff --git a/lib/Crypto/SelfTest/Hash/test_SHA384.py b/lib/Crypto/SelfTest/Hash/test_SHA384.py
index b7a72c0..27d16b3 100644
--- a/lib/Crypto/SelfTest/Hash/test_SHA384.py
+++ b/lib/Crypto/SelfTest/Hash/test_SHA384.py
@@ -53,7 +53,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(SHA384, "SHA384", test_data,
digest_size=48,
- oid='\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02')
+ oid='2.16.840.1.101.3.4.2.2')
if __name__ == '__main__':
import unittest
diff --git a/lib/Crypto/SelfTest/Hash/test_SHA512.py b/lib/Crypto/SelfTest/Hash/test_SHA512.py
index cb86177..04a505e 100644
--- a/lib/Crypto/SelfTest/Hash/test_SHA512.py
+++ b/lib/Crypto/SelfTest/Hash/test_SHA512.py
@@ -50,7 +50,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(SHA512, "SHA512", test_data,
digest_size=64,
- oid="\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03")
+ oid="2.16.840.1.101.3.4.2.3")
if __name__ == '__main__':
import unittest
diff --git a/lib/Crypto/SelfTest/IO/__init__.py b/lib/Crypto/SelfTest/IO/__init__.py
new file mode 100644
index 0000000..084904e
--- /dev/null
+++ b/lib/Crypto/SelfTest/IO/__init__.py
@@ -0,0 +1,34 @@
+#
+# SelfTest/IO/__init__.py: Self-test for input/output module
+#
+# ===================================================================
+# 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.
+# ===================================================================
+
+"""Self-test for I/O"""
+
+def get_tests(config={}):
+ tests = []
+ from Crypto.SelfTest.IO import test_PKCS8; tests += test_PKCS8.get_tests(config=config)
+ return tests
+
+if __name__ == '__main__':
+ import unittest
+ suite = lambda: unittest.TestSuite(get_tests())
+ unittest.main(defaultTest='suite')
+
+
diff --git a/lib/Crypto/SelfTest/IO/test_PKCS8.py b/lib/Crypto/SelfTest/IO/test_PKCS8.py
new file mode 100644
index 0000000..09d3554
--- /dev/null
+++ b/lib/Crypto/SelfTest/IO/test_PKCS8.py
@@ -0,0 +1,419 @@
+# -*- coding: utf-8 -*-
+#
+# SelfTest/PublicKey/test_PKCS8.py: Self-test for the PKCS8 module
+#
+# ===================================================================
+# 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.
+# ===================================================================
+
+"""Self-tests for Crypto.PublicKey.PKCS8 module"""
+
+__revision__ = "$Id$"
+
+import unittest
+import sys
+
+from Crypto.Util.py3compat import *
+from Crypto.Util.asn1 import *
+from Crypto.IO import PKCS8
+from binascii import *
+
+if sys.version_info[0] == 2 and sys.version_info[1] == 1:
+ from Crypto.Util.py21compat import *
+
+oid_key = '1.2.840.113549.1.1.1'
+
+# Original RSA key (in DER format)
+# hexdump -v -e '32/1 "%02x" "\n"' key.der
+clear_key="""
+308201ab020100025a00b94a7f7075ab9e79e8196f47be707781e80dd965cf16
+0c951a870b71783b6aaabbd550c0e65e5a3dfe15b8620009f6d7e5efec42a3f0
+6fe20faeebb0c356e79cdec6db4dd427e82d8ae4a5b90996227b8ba54ccfc4d2
+5c08050203010001025a00afa09c70d528299b7552fe766b5d20f9a221d66938
+c3b68371d48515359863ff96f0978d700e08cd6fd3d8a3f97066fc2e0d5f78eb
+3a50b8e17ba297b24d1b8e9cdfd18d608668198d724ad15863ef0329195dee89
+3f039395022d0ebe0518df702a8b25954301ec60a97efdcec8eaa4f2e76ca7e8
+8dfbc3f7e0bb83f9a0e8dc47c0f8c746e9df6b022d0c9195de13f09b7be1fdd7
+1f56ae7d973e08bd9fd2c3dfd8936bb05be9cc67bd32d663c7f00d70932a0be3
+c24f022d0ac334eb6cabf1933633db007b763227b0d9971a9ea36aca8b669ec9
+4fcf16352f6b3dcae28e4bd6137db4ddd3022d0400a09f15ee7b351a2481cb03
+09920905c236d09c87afd3022f3afc2a19e3b746672b635238956ee7e6dd62d5
+022d0cd88ed14fcfbda5bbf0257f700147137bbab9c797af7df866704b889aa3
+7e2e93df3ff1a0fd3490111dcdbc4c
+"""
+
+# Same key as above, wrapped in PKCS#8 but w/o password
+#
+# openssl pkcs8 -topk8 -inform DER -nocrypt -in key.der -outform DER -out keyp8.der
+# hexdump -v -e '32/1 "%02x" "\n"' keyp8.der
+wrapped_clear_key="""
+308201c5020100300d06092a864886f70d0101010500048201af308201ab0201
+00025a00b94a7f7075ab9e79e8196f47be707781e80dd965cf160c951a870b71
+783b6aaabbd550c0e65e5a3dfe15b8620009f6d7e5efec42a3f06fe20faeebb0
+c356e79cdec6db4dd427e82d8ae4a5b90996227b8ba54ccfc4d25c0805020301
+0001025a00afa09c70d528299b7552fe766b5d20f9a221d66938c3b68371d485
+15359863ff96f0978d700e08cd6fd3d8a3f97066fc2e0d5f78eb3a50b8e17ba2
+97b24d1b8e9cdfd18d608668198d724ad15863ef0329195dee893f039395022d
+0ebe0518df702a8b25954301ec60a97efdcec8eaa4f2e76ca7e88dfbc3f7e0bb
+83f9a0e8dc47c0f8c746e9df6b022d0c9195de13f09b7be1fdd71f56ae7d973e
+08bd9fd2c3dfd8936bb05be9cc67bd32d663c7f00d70932a0be3c24f022d0ac3
+34eb6cabf1933633db007b763227b0d9971a9ea36aca8b669ec94fcf16352f6b
+3dcae28e4bd6137db4ddd3022d0400a09f15ee7b351a2481cb0309920905c236
+d09c87afd3022f3afc2a19e3b746672b635238956ee7e6dd62d5022d0cd88ed1
+4fcfbda5bbf0257f700147137bbab9c797af7df866704b889aa37e2e93df3ff1
+a0fd3490111dcdbc4c
+"""
+
+###
+#
+# The key above will now be encrypted with different algorithms.
+# The password is always 'TestTest'.
+#
+# Each item in the wrapped_enc_keys list contains:
+# * wrap algorithm
+# * iteration count
+# * Salt
+# * IV
+# * Expected result
+###
+wrapped_enc_keys = []
+
+#
+# openssl pkcs8 -topk8 -passin pass:TestTest -inform DER -in key.der -outform DER -out keyenc.der -v2 des3
+# hexdump -v -e '32/1 "%02x" "\n"' keyenc.der
+#
+wrapped_enc_keys.append((
+'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC',
+2048,
+"47EA7227D8B22E2F", # IV
+"E3F7A838AB911A4D", # Salt
+"""
+30820216304006092a864886f70d01050d3033301b06092a864886f70d01050c
+300e0408e3f7a838ab911a4d02020800301406082a864886f70d0307040847ea
+7227d8b22e2f048201d0ea388b374d2d0e4ceb7a5139f850fdff274884a6e6c0
+64326e09d00dbba9018834edb5a51a6ae3d1806e6e91eebf33788ce71fee0637
+a2ebf58859dd32afc644110c390274a6128b50c39b8d907823810ec471bada86
+6f5b75d8ea04ad310fad2e73621696db8e426cd511ee93ec1714a1a7db45e036
+4bf20d178d1f16bbb250b32c2d200093169d588de65f7d99aad9ddd0104b44f1
+326962e1520dfac3c2a800e8a14f678dff2b3d0bb23f69da635bf2a643ac934e
+219a447d2f4460b67149e860e54f365da130763deefa649c72b0dcd48966a2d3
+4a477444782e3e66df5a582b07bbb19778a79bd355074ce331f4a82eb966b0c4
+52a09eab6116f2722064d314ae433b3d6e81d2436e93fdf446112663cde93b87
+9c8be44beb45f18e2c78fee9b016033f01ecda51b9b142091fa69f65ab784d2c
+5ad8d34be6f7f1464adfc1e0ef3f7848f40d3bdea4412758f2fcb655c93d8f4d
+f6fa48fc5aa4b75dd1c017ab79ac9d737233a6d668f5364ccf47786debd37334
+9c10c9e6efbe78430a61f71c89948aa32cdc3cc7338cf994147819ce7ab23450
+c8f7d9b94c3bb377d17a3fa204b601526317824b142ff6bc843fa7815ece89c0
+839573f234dac8d80cc571a045353d61db904a4398d8ef3df5ac
+"""
+))
+
+#
+# openssl pkcs8 -topk8 -passin pass:TestTest -inform DER -in key.der -outform DER -out keyenc.der
+# hexdump -v -e '32/1 "%02x" "\n"' keyenc.der
+#
+wrapped_enc_keys.append((
+-1, # pbeWithMD5AndDES-CBC, only decoding is supported
+-1,
+"",
+"",
+"""
+308201f1301b06092a864886f70d010503300e0408f9b990c89af1d41b020208
+00048201d0c6267fe8592903891933d559e71a7ca68b2e39150f19daca0f7921
+52f97e249d72f670d5140e9150433310ed7c7ee51927693fd39884cb9551cea5
+a7b746f7edf199f8787d4787a35dad930d7db057b2118851211b645ac8b90fa6
+b0e7d49ac8567cbd5fff226e87aa9129a0f52c45e9307752e8575c3b0ff756b7
+31fda6942d15ecb6b27ea19370ccc79773f47891e80d22b440d81259c4c28eac
+e0ca839524116bcf52d8c566e49a95ddb0e5493437279a770a39fd333f3fca91
+55884fad0ba5aaf273121f893059d37dd417da7dcfd0d6fa7494968f13b2cc95
+65633f2c891340193e5ec00e4ee0b0e90b3b93da362a4906360845771ade1754
+9df79140be5993f3424c012598eadd3e7c7c0b4db2c72cf103d7943a5cf61420
+93370b9702386c3dd4eb0a47f34b579624a46a108b2d13921fa1b367495fe345
+6aa128aa70f8ca80ae13eb301e96c380724ce67c54380bbea2316c1faf4d058e
+b4ca2e23442047606b9bc4b3bf65b432cb271bea4eb35dd3eb360d3be8612a87
+a50e96a2264490aeabdc07c6e78e5dbf4fe3388726d0e2a228346bf3c2907d68
+2a6276b22ae883fb30fa611f4e4193e7a08480fcd7db48308bacbd72bf4807aa
+11fd394859f97d22982f7fe890b2e2a0f7e7ffb693
+"""
+))
+
+#
+# openssl pkcs8 -topk8 -passin pass:TestTest -inform DER -in key.der
+# -outform DER -out keyenc.der -v1 PBE-SHA1-RC2-64
+# hexdump -v -e '32/1 "%02x" "\n"' keyenc.der
+#
+wrapped_enc_keys.append((
+-1, # pbeWithSHA1AndRC2-CBC, only decoding is supported
+-1,
+"",
+"",
+"""
+308201f1301b06092a864886f70d01050b300e04083ee943bdae185008020208
+00048201d0e4614d9371d3ff10ceabc2f6a7a13a0f449f9a714144e46518ea55
+e3e6f0cde24031d01ef1f37ec40081449ef01914faf45983dde0d2bc496712de
+8dd15a5527dff4721d9016c13f34fb93e3ce68577e30146266d71b539f854e56
+753a192cf126ed4812734d86f81884374f1100772f78d0646e9946407637c565
+d070acab413c55952f7237437f2e48cae7fa0ff8d370de2bf446dd08049a3663
+d9c813ac197468c02e2b687e7ca994cf7f03f01b6eca87dbfed94502c2094157
+ea39f73fe4e591df1a68b04d19d9adab90bb9898467c1464ad20bf2b8fb9a5ff
+d3ec91847d1c67fd768a4b9cfb46572eccc83806601372b6fad0243f58f623b7
+1c5809dea0feb8278fe27e5560eed8448dc93f5612f546e5dd7c5f6404365eb2
+5bf3396814367ae8b15c5c432b57eaed1f882c05c7f6517ee9e42b87b7b8d071
+9d6125d1b52f7b2cca1f6bd5f584334bf90bce1a7d938274cafe27b68e629698
+b16e27ae528db28593af9adcfccbebb3b9e1f2af5cd5531b51968389caa6c091
+e7de1f1b96f0d258e54e540d961a7c0ef51fda45d6da5fddd33e9bbfd3a5f8d7
+d7ab2e971de495cddbc86d38444fee9f0ac097b00adaf7802dabe0cff5b43b45
+4f26b7b547016f89be52676866189911c53e2f2477"""
+))
+
+#
+# openssl pkcs8 -topk8 -passin pass:TestTest -inform DER -in key.der
+# -outform DER -out keyenc.der -v1 PBE-MD5-RC2-64
+# hexdump -v -e '32/1 "%02x" "\n"' keyenc.der
+#
+wrapped_enc_keys.append((
+-1, # pbeWithMD5AndRC2-CBC, only decoding is supported
+-1,
+"",
+"",
+"""
+308201f1301b06092a864886f70d010506300e0408f5cd2fee56d9b4b8020208
+00048201d086454942d6166a19d6b108465bd111e7080911f573d54b1369c676
+df28600e84936bfec04f91023ff16499e2e07178c340904f12ffa6886ab66228
+32bf43c2bff5a0ed14e765918cf5fc543ad49566246f7eb3fc044fa5a9c25f40
+8fc8c8296b91658d3bb1067c0aba008c4fefd9e2bcdbbbd63fdc8085482bccf4
+f150cec9a084259ad441a017e5d81a1034ef2484696a7a50863836d0eeda45cd
+8cee8ecabfed703f8d9d4bbdf3a767d32a0ccdc38550ee2928d7fe3fa27eda5b
+5c7899e75ad55d076d2c2d3c37d6da3d95236081f9671dab9a99afdb1cbc890e
+332d1a91105d9a8ce08b6027aa07367bd1daec3059cb51f5d896124da16971e4
+0ca4bcadb06c854bdf39f42dd24174011414e51626d198775eff3449a982df7b
+ace874e77e045eb6d7c3faef0750792b29a068a6291f7275df1123fac5789c51
+27ace42836d81633faf9daf38f6787fff0394ea484bbcd465b57d4dbee3cf8df
+b77d1db287b3a6264c466805be5a4fe85cfbca180699859280f2dd8e2c2c10b5
+7a7d2ac670c6039d41952fbb0e4f99b560ebe1d020e1b96d02403283819c00cc
+529c51f0b0101555e4c58002ba3c6e3c12e3fde1aec94382792e96d9666a2b33
+3dc397b22ecab67ee38a552fec29a1d4ff8719c748"""
+))
+
+#
+# openssl pkcs8 -topk8 -passin pass:TestTest -inform DER -in key.der
+# -outform DER -out keyenc.der -v1 PBE-SHA1-DES
+# hexdump -v -e '32/1 "%02x" "\n"' keyenc.der
+#
+wrapped_enc_keys.append((
+-1, # pbeWithSHA1AndDES-CBC, only decoding is supported
+-1,
+"",
+"",
+"""
+308201f1301b06092a864886f70d01050a300e04089bacc9cf1e8f734e020208
+00048201d03e502f3ceafe8fd19ab2939576bfdded26d719b2441db1459688f5
+9673218b41ec1f739edf1e460bd927bc28470c87b2d4fc8ea02ba17b47a63c49
+c5c1bee40529dadfd3ef8b4472c730bc136678c78abfb34670ec9d7dcd17ee3f
+892f93f2629e6e0f4b24ecb9f954069bf722f466dece3913bb6abbd2c471d9a5
+c5eea89b14aaccda43d30b0dd0f6eb6e9850d9747aa8aa8414c383ad01c374ee
+26d3552abec9ba22669cc9622ccf2921e3d0c8ecd1a70e861956de0bec6104b5
+b649ac994970c83f8a9e84b14a7dff7843d4ca3dd4af87cea43b5657e15ae0b5
+a940ce5047f006ab3596506600724764f23757205fe374fee04911336d655acc
+03e159ec27789191d1517c4f3f9122f5242d44d25eab8f0658cafb928566ca0e
+8f6589aa0c0ab13ca7a618008ae3eafd4671ee8fe0b562e70b3623b0e2a16eee
+97fd388087d2e03530c9fe7db6e52eccc7c48fd701ede35e08922861a9508d12
+bc8bbf24f0c6bee6e63dbcb489b603d4c4a78ce45bf2eab1d5d10456c42a65a8
+3a606f4e4b9b46eb13b57f2624b651859d3d2d5192b45dbd5a2ead14ff20ca76
+48f321309aa56d8c0c4a192b580821cc6c70c75e6f19d1c5414da898ec4dd39d
+b0eb93d6ba387a80702dfd2db610757ba340f63230
+"""
+))
+
+#
+# openssl pkcs8 -topk8 -passin pass:TestTest -inform DER -in key.der
+# -outform DER -out keyenc.der -v2 aes128
+# hexdump -v -e '32/1 "%02x" "\n"' keyenc.der
+#
+wrapped_enc_keys.append((
+'PBKDF2WithHMAC-SHA1AndAES128-CBC',
+2048,
+"4F66EE5D3BCD531FE6EBF4B4E73016B8", # IV
+"479F25156176C53A", # Salt
+"""
+3082021f304906092a864886f70d01050d303c301b06092a864886f70d01050c
+300e0408479f25156176c53a02020800301d060960864801650304010204104f
+66ee5d3bcd531fe6ebf4b4e73016b8048201d0e33cfa560423f589d097d21533
+3b880a5ebac5b2ac58b4e73b0d787aee7764f034fe34ca1d1bd845c0a7c3316f
+afbfb2129e03dcaf5a5031394206492828dacef1e04639bee5935e0f46114202
+10bc6c37182f4889be11c5d0486c398f4be952e5740f65de9d8edeb275e2b406
+e19bc29ad5ebb97fa536344fc3d84c7e755696f12b810898de4e6f069b8a81c8
+0aab0d45d7d062303aaa4a10c2ce84fdb5a03114039cfe138e38bb15b2ced717
+93549cdad85e730b14d9e2198b663dfdc8d04a4349eb3de59b076ad40b116d4a
+25ed917c576bc7c883c95ef0f1180e28fc9981bea069594c309f1aa1b253ceab
+a2f0313bb1372bcb51a745056be93d77a1f235a762a45e8856512d436b2ca0f7
+dd60fbed394ba28978d2a2b984b028529d0a58d93aba46c6bbd4ac1e4013cbaa
+63b00988bc5f11ccc40141c346762d2b28f64435d4be98ec17c1884985e3807e
+e550db606600993efccf6de0dfc2d2d70b5336a3b018fa415d6bdd59f5777118
+16806b7bc17c4c7e20ad7176ebfa5a1aa3f6bc10f04b77afd443944642ac9cca
+d740e082b4a3bbb8bafdd34a0b3c5f2f3c2aceccccdccd092b78994b845bfa61
+706c3b9df5165ed1dbcbf1244fe41fc9bf993f52f7658e2f87e1baaeacb0f562
+9d905c
+"""
+))
+
+#
+# openssl pkcs8 -topk8 -passin pass:TestTest -inform DER -in key.der
+# -outform DER -out keyenc.der -v2 aes192
+# hexdump -v -e '32/1 "%02x" "\n"' keyenc.der
+#
+wrapped_enc_keys.append((
+'PBKDF2WithHMAC-SHA1AndAES192-CBC',
+2048,
+"5CFC2A4FF7B63201A4A8A5B021148186", # IV
+"D718541C264944CE", # Salt
+"""
+3082021f304906092a864886f70d01050d303c301b06092a864886f70d01050c
+300e0408d718541c264944ce02020800301d060960864801650304011604105c
+fc2a4ff7b63201a4a8a5b021148186048201d08e74aaa21b8bcfb15b9790fe95
+b0e09ddb0f189b6fb1682fdb9f122b804650ddec3c67a1df093a828b3e5fbcc6
+286abbcc5354c482fd796d972e919ca8a5eba1eaa2293af1d648013ddad72106
+75622264dfba55dafdda39e338f058f1bdb9846041ffff803797d3fdf3693135
+8a192729ea8346a7e5e58e925a2e2e4af0818581859e8215d87370eb4194a5ff
+bae900857d4c591dbc651a241865a817eaede9987c9f9ae4f95c0bf930eea88c
+4d7596e535ffb7ca369988aba75027a96b9d0bc9c8b0b75f359067fd145a378b
+02aaa15e9db7a23176224da48a83249005460cc6e429168657f2efa8b1af7537
+d7d7042f2d683e8271b21d591090963eeb57aea6172f88da139e1614d6a7d1a2
+1002d5a7a93d6d21156e2b4777f6fc069287a85a1538c46b7722ccde591ab55c
+630e1ceeb1ac42d1b41f3f654e9da86b5efced43775ea68b2594e50e4005e052
+0fe753c0898120c2c07265367ff157f6538a1e4080d6f9d1ca9eb51939c9574e
+f2e4e1e87c1434affd5808563cddd376776dbbf790c6a40028f311a8b58dafa2
+0970ed34acd6e3e89d063987893b2b9570ddb8cc032b05a723bba9444933ebf3
+c624204be72f4190e0245197d0cb772bec933fd8442445f9a28bd042d5a3a1e9
+9a8a07
+"""
+))
+
+#
+# openssl pkcs8 -topk8 -passin pass:TestTest -inform DER -in key.der
+# -outform DER -out keyenc.der -v2 aes192
+# hexdump -v -e '32/1 "%02x" "\n"' keyenc.der
+#
+wrapped_enc_keys.append((
+'PBKDF2WithHMAC-SHA1AndAES256-CBC',
+2048,
+"323351F94462AC563E053A056252C2C4", # IV
+"02A6CD0D12E727B5", # Salt
+"""
+3082021f304906092a864886f70d01050d303c301b06092a864886f70d01050c
+300e040802a6cd0d12e727b502020800301d060960864801650304012a041032
+3351f94462ac563e053a056252c2c4048201d07f4ef1c7be21aae738a20c5632
+b8bdbbb9083b6e7f68822267b1f481fd27fdafd61a90660de6e4058790e4c912
+bf3f319a7c37e6eb3d956daaa143865020d554bf6215e8d7492359aaeef45d6e
+d85a686ed26c0bf7c18d071d827a86f0b73e1db0c0e7f3d42201544093302a90
+551ad530692468c47ac15c69500b8ca67d4a17b64d15cecc035ae50b768a36cf
+07c395afa091e9e6f86f665455fbdc1b21ad79c0908b73da5de75a9b43508d5d
+44dc97a870cd3cd9f01ca24452e9b11c1b4982946702cfcbfda5b2fcc0203fb5
+0b52a115760bd635c94d4c95ac2c640ee9a04ffaf6ccff5a8d953dd5d88ca478
+c377811c521f2191639c643d657a9e364af88bb7c14a356c2b0b4870a23c2f54
+d41f8157afff731471dccc6058b15e1151bcf84b39b5e622a3a1d65859c912a5
+591b85e034a1f6af664f030a6bfc8c3d20c70f32b54bcf4da9c2da83cef49cf8
+e9a74f0e5d358fe50b88acdce6a9db9a7ad61536212fc5f877ebfc7957b8bda4
+b1582a0f10d515a20ee06cf768db9c977aa6fbdca7540d611ff953012d009dac
+e8abd059f8e8ffea637c9c7721f817aaf0bb23403e26a0ef0ff0e2037da67d41
+af728481f53443551a9bff4cea023164e9622b5441a309e1f4bff98e5bf76677
+8d7cd9
+"""
+))
+
+def txt2bin(inputs):
+ s = b('').join([b(x) for x in inputs if not (x in '\n\r\t ')])
+ return unhexlify(s)
+
+class Rng:
+ def __init__(self, output):
+ self.output=output
+ self.idx=0
+ def __call__(self, n):
+ output = self.output[self.idx:self.idx+n]
+ self.idx += n
+ return output
+
+class PKCS8_Decrypt(unittest.TestCase):
+
+ def setUp(self):
+ self.oid_key = oid_key
+ self.clear_key = txt2bin(clear_key)
+ self.wrapped_clear_key = txt2bin(wrapped_clear_key)
+ self.wrapped_enc_keys = []
+ for t in wrapped_enc_keys:
+ self.wrapped_enc_keys.append((
+ t[0],
+ t[1],
+ txt2bin(t[2]),
+ txt2bin(t[3]),
+ txt2bin(t[4])
+ ))
+
+ ### NO ENCRYTION
+
+ def test1(self):
+ """Verify unwrapping w/o encryption"""
+ res1, res2, res3 = PKCS8.unwrap(self.wrapped_clear_key)
+ self.assertEqual(res1, self.oid_key)
+ self.assertEqual(res2, self.clear_key)
+
+ def test2(self):
+ """Verify wrapping w/o encryption"""
+ wrapped = PKCS8.wrap(self.clear_key, self.oid_key)
+ res1, res2, res3 = PKCS8.unwrap(wrapped)
+ self.assertEqual(res1, self.oid_key)
+ self.assertEqual(res2, self.clear_key)
+
+ ## ENCRYPTION
+
+ def test3(self):
+ """Verify unwrapping with encryption"""
+
+ for t in self.wrapped_enc_keys:
+ res1, res2, res3 = PKCS8.unwrap(t[4], b("TestTest"))
+ self.assertEqual(res1, self.oid_key)
+ self.assertEqual(res2, self.clear_key)
+
+ def test4(self):
+ """Verify wrapping with encryption"""
+
+ for t in self.wrapped_enc_keys:
+ if t[0]==-1:
+ continue
+ rng = Rng(t[2]+t[3])
+ params = { 'iteration_count':t[1] }
+ wrapped = PKCS8.wrap(
+ self.clear_key,
+ self.oid_key,
+ b("TestTest"),
+ protection=t[0],
+ prot_params=params,
+ key_params=None,
+ randfunc=rng)
+ self.assertEqual(wrapped, t[4])
+
+def get_tests(config={}):
+ from Crypto.SelfTest.st_common import list_test_cases
+ listTests = []
+ listTests += list_test_cases(PKCS8_Decrypt)
+ return listTests
+
+if __name__ == '__main__':
+ suite = lambda: unittest.TestSuite(get_tests())
+ unittest.main(defaultTest='suite')
+
diff --git a/lib/Crypto/SelfTest/PublicKey/test_importKey.py b/lib/Crypto/SelfTest/PublicKey/test_importKey.py
index 4710440..ff65e77 100644
--- a/lib/Crypto/SelfTest/PublicKey/test_importKey.py
+++ b/lib/Crypto/SelfTest/PublicKey/test_importKey.py
@@ -66,7 +66,8 @@ BX85JB8zqwHB
# The same RSA private key as in rsaKeyPEM, but now encrypted
rsaKeyEncryptedPEM=(
-
+
+ # PEM encryption
# With DES and passphrase 'test'
('test', u'''-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
@@ -79,29 +80,27 @@ BCNRMdcexozWtAFNNqSzfW58MJL2OdMi21ED184EFytIc1BlB+FZiGZduwKGuaKy
9bMbdb/1PSvsSzPsqW7KSSrTw6MgJAFJg6lzIYvR5F4poTVBxwBX3+EyEmShiaNY
IRX3TgQI0IjrVuLmvlZKbGWP18FXj7I7k9tSsNOOzllTTdq3ny5vgM3A+ynfAaxp
dysKznQ6P+IoqML1WxAID4aGRMWka+uArOJ148Rbj9s=
------END RSA PRIVATE KEY-----''',
- "\xAF\x8F\x9A\x40\xBD\x2F\xA2\xFC"),
-
- # With Triple-DES and passphrase 'rocking'
- ('rocking', u'''-----BEGIN RSA PRIVATE KEY-----
-Proc-Type: 4,ENCRYPTED
-DEK-Info: DES-EDE3-CBC,C05D6C07F7FC02F6
-
-w4lwQrXaVoTTJ0GgwY566htTA2/t1YlimhxkxYt9AEeCcidS5M0Wq9ClPiPz9O7F
-m6K5QpM1rxo1RUE/ZyI85gglRNPdNwkeTOqit+kum7nN73AToX17+irVmOA4Z9E+
-4O07t91GxGMcjUSIFk0ucwEU4jgxRvYscbvOMvNbuZszGdVNzBTVddnShKCsy9i7
-nJbPlXeEKYi/OkRgO4PtfqqWQu5GIEFVUf9ev1QV7AvC+kyWTR1wWYnHX265jU5c
-sopxQQtP8XEHIJEdd5/p1oieRcWTCNyY8EkslxDSsrf0OtZp6mZH9N+KU47cgQtt
-9qGORmlWnsIoFFKcDohbtOaWBTKhkj5h6OkLjFjfU/sBeV1c+7wDT3dAy5tawXjG
-YSxC7qDQIT/RECvV3+oQKEcmpEujn45wAnkTi12BH30=
------END RSA PRIVATE KEY-----''',
- "\xC0\x5D\x6C\x07\xF7\xFC\x02\xF6"),
+-----END RSA PRIVATE KEY-----'''),
+
+ # PKCS8 encryption
+ ('winter', u'''-----BEGIN ENCRYPTED PRIVATE KEY-----
+MIIBpjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIeZIsbW3O+JcCAggA
+MBQGCCqGSIb3DQMHBAgSM2p0D8FilgSCAWBhFyP2tiGKVpGj3mO8qIBzinU60ApR
+3unvP+N6j7LVgnV2lFGaXbJ6a1PbQXe+2D6DUyBLo8EMXrKKVLqOMGkFMHc0UaV6
+R6MmrsRDrbOqdpTuVRW+NVd5J9kQQh4xnfU/QrcPPt7vpJvSf4GzG0n666Ki50OV
+M/feuVlIiyGXY6UWdVDpcOV72cq02eNUs/1JWdh2uEBvA9fCL0c07RnMrdT+CbJQ
+NjJ7f8ULtp7xvR9O3Al/yJ4Wv3i4VxF1f3MCXzhlUD4I0ONlr0kJWgeQ80q/cWhw
+ntvgJwnCn2XR1h6LA8Wp+0ghDTsL2NhJpWd78zClGhyU4r3hqu1XDjoXa7YCXCix
+jCV15+ViDJzlNCwg+W6lRg18sSLkCT7alviIE0U5tHc6UPbbHwT5QqAxAABaP+nZ
+CGqJGyiwBzrKebjgSm/KRd4C91XqcsysyH2kKPfT51MLAoD4xelOURBP
+-----END ENCRYPTED PRIVATE KEY-----'''
+ ),
)
- rsaPublicKeyPEM = u'''-----BEGIN PUBLIC KEY-----
+ rsaPublicKeyPEM = u'''-----BEGIN RSA PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+T
Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQ==
------END PUBLIC KEY-----'''
+-----END RSA PUBLIC KEY-----'''
# Obtained using 'ssh-keygen -i -m PKCS8 -f rsaPublicKeyPEM'
rsaPublicKeyOpenSSH = b('''ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQC/HieQCqCLI1EaXBKBrm2TMSw+/pE/ky6+1JLxLRa0YQwyjLbiCKtfRay+KVCDMpjzEiwZ94SS3t9A8OPBkDOF comment\n''')
@@ -298,15 +297,6 @@ Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQ==
self.assertEqual(openssh_1[0], openssh_2[0])
self.assertEqual(openssh_1[1], openssh_2[1])
- def testExportKey6(self):
- key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
- # Tuple with index #1 is encrypted with 3DES
- t = map(b,self.rsaKeyEncryptedPEM[1])
- # Force the salt being used when exporting
- key._randfunc = lambda N: (t[2]*divmod(N+len(t[2]),len(t[2]))[0])[:N]
- pemKey = key.exportKey("PEM", t[0])
- self.assertEqual(pemKey, t[1])
-
def testExportKey7(self):
key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
derKey = key.exportKey("DER", pkcs=8)
@@ -321,6 +311,71 @@ Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQ==
key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
self.assertRaises(ValueError, key.exportKey, "invalid-format")
+ def testExportKey10(self):
+ # Export and re-import the encrypted key. It must match.
+ # PEM envelope, PKCS#1, old PEM encryption
+ key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
+ outkey = key.exportKey('PEM', 'test')
+ self.failUnless(tostr(outkey).find('4,ENCRYPTED')!=-1)
+ self.failUnless(tostr(outkey).find('BEGIN RSA PRIVATE KEY')!=-1)
+ inkey = RSA.importKey(outkey, 'test')
+ self.assertEqual(key.n, inkey.n)
+ self.assertEqual(key.e, inkey.e)
+ self.assertEqual(key.d, inkey.d)
+
+ def testExportKey11(self):
+ # Export and re-import the encrypted key. It must match.
+ # PEM envelope, PKCS#1, old PEM encryption
+ key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
+ outkey = key.exportKey('PEM', 'test', pkcs=1)
+ self.failUnless(tostr(outkey).find('4,ENCRYPTED')!=-1)
+ self.failUnless(tostr(outkey).find('BEGIN RSA PRIVATE KEY')!=-1)
+ inkey = RSA.importKey(outkey, 'test')
+ self.assertEqual(key.n, inkey.n)
+ self.assertEqual(key.e, inkey.e)
+ self.assertEqual(key.d, inkey.d)
+
+ def testExportKey12(self):
+ # Export and re-import the encrypted key. It must match.
+ # PEM envelope, PKCS#8, old PEM encryption
+ key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
+ outkey = key.exportKey('PEM', 'test', pkcs=8)
+ self.failUnless(tostr(outkey).find('4,ENCRYPTED')!=-1)
+ self.failUnless(tostr(outkey).find('BEGIN PRIVATE KEY')!=-1)
+ inkey = RSA.importKey(outkey, 'test')
+ self.assertEqual(key.n, inkey.n)
+ self.assertEqual(key.e, inkey.e)
+ self.assertEqual(key.d, inkey.d)
+
+ def testExportKey13(self):
+ # Export and re-import the encrypted key. It must match.
+ # PEM envelope, PKCS#8, PKCS#8 encryption
+ key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
+ outkey = key.exportKey('PEM', 'test', pkcs=8,
+ protection='PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC')
+ self.failUnless(tostr(outkey).find('4,ENCRYPTED')==-1)
+ self.failUnless(tostr(outkey).find('BEGIN ENCRYPTED PRIVATE KEY')!=-1)
+ inkey = RSA.importKey(outkey, 'test')
+ self.assertEqual(key.n, inkey.n)
+ self.assertEqual(key.e, inkey.e)
+ self.assertEqual(key.d, inkey.d)
+
+ def testExportKey14(self):
+ # Export and re-import the encrypted key. It must match.
+ # DER envelope, PKCS#8, PKCS#8 encryption
+ key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
+ outkey = key.exportKey('DER', 'test', pkcs=8)
+ inkey = RSA.importKey(outkey, 'test')
+ self.assertEqual(key.n, inkey.n)
+ self.assertEqual(key.e, inkey.e)
+ self.assertEqual(key.d, inkey.d)
+
+ def testExportKey15(self):
+ # Verify that that error an condition is detected when trying to
+ # use a password with DER encoding and PKCS#1.
+ key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
+ self.assertRaises(ValueError, key.exportKey, 'DER', 'test', 1)
+
class ImportKeyTestsSlow(ImportKeyTests):
def setUp(self):
self.rsa = RSA.RSAImplementation(use_fast_math=0)
diff --git a/lib/Crypto/SelfTest/Util/__init__.py b/lib/Crypto/SelfTest/Util/__init__.py
index abd640a..f404d0b 100644
--- a/lib/Crypto/SelfTest/Util/__init__.py
+++ b/lib/Crypto/SelfTest/Util/__init__.py
@@ -34,6 +34,7 @@ def get_tests(config={}):
from Crypto.SelfTest.Util import test_winrandom; tests += test_winrandom.get_tests(config=config)
from Crypto.SelfTest.Util import test_number; tests += test_number.get_tests(config=config)
from Crypto.SelfTest.Util import test_Counter; tests += test_Counter.get_tests(config=config)
+ from Crypto.SelfTest.Util import test_Padding; tests += test_Padding.get_tests(config=config)
return tests
if __name__ == '__main__':
diff --git a/lib/Crypto/SelfTest/Util/test_Padding.py b/lib/Crypto/SelfTest/Util/test_Padding.py
new file mode 100644
index 0000000..03c28ea
--- /dev/null
+++ b/lib/Crypto/SelfTest/Util/test_Padding.py
@@ -0,0 +1,140 @@
+# -*- coding: utf-8 -*-
+#
+# SelfTest/Util/test_Padding.py: Self-test for padding functions
+#
+# ===================================================================
+# 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.
+# ===================================================================
+
+import unittest
+from binascii import unhexlify as uh
+
+from Crypto.Util.py3compat import *
+from Crypto.SelfTest.st_common import list_test_cases
+from Crypto.Util.Padding import *
+
+class PKCS7_Tests(unittest.TestCase):
+
+ def test1(self):
+ padded = pad(b(""), 4)
+ self.failUnless(padded == uh("04040404"))
+ padded = pad(b(""), 4, 'pkcs7')
+ self.failUnless(padded == uh("04040404"))
+ back = unpad(padded, 4)
+ self.failUnless(back == b(""))
+
+ def test2(self):
+ padded = pad(uh("12345678"), 4)
+ self.failUnless(padded == uh("1234567804040404"))
+ back = unpad(padded, 4)
+ self.failUnless(back == uh("12345678"))
+
+ def test3(self):
+ padded = pad(uh("123456"), 4)
+ self.failUnless(padded == uh("12345601"))
+ back = unpad(padded, 4)
+ self.failUnless(back == uh("123456"))
+
+ def test4(self):
+ padded = pad(uh("1234567890"), 4)
+ self.failUnless(padded == uh("1234567890030303"))
+ back = unpad(padded, 4)
+ self.failUnless(back == uh("1234567890"))
+
+ def testn1(self):
+ self.assertRaises(ValueError, pad, uh("12"), 4, 'pkcs8')
+
+ def testn2(self):
+ self.assertRaises(ValueError, unpad, b("\0\0\0"), 4)
+
+ def testn3(self):
+ self.assertRaises(ValueError, unpad, b("123456\x02"), 4)
+ self.assertRaises(ValueError, unpad, b("123456\x00"), 4)
+ self.assertRaises(ValueError, unpad, b("123456\x05\x05\x05\x05\x05"), 4)
+
+class X923_Tests(unittest.TestCase):
+
+ def test1(self):
+ padded = pad(b(""), 4, 'x923')
+ self.failUnless(padded == uh("00000004"))
+ back = unpad(padded, 4, 'x923')
+ self.failUnless(back == b(""))
+
+ def test2(self):
+ padded = pad(uh("12345678"), 4, 'x923')
+ self.failUnless(padded == uh("1234567800000004"))
+ back = unpad(padded, 4, 'x923')
+ self.failUnless(back == uh("12345678"))
+
+ def test3(self):
+ padded = pad(uh("123456"), 4, 'x923')
+ self.failUnless(padded == uh("12345601"))
+ back = unpad(padded, 4, 'x923')
+ self.failUnless(back == uh("123456"))
+
+ def test4(self):
+ padded = pad(uh("1234567890"), 4, 'x923')
+ self.failUnless(padded == uh("1234567890000003"))
+ back = unpad(padded, 4, 'x923')
+ self.failUnless(back == uh("1234567890"))
+
+ def testn1(self):
+ self.assertRaises(ValueError, unpad, b("123456\x02"), 4, 'x923')
+ self.assertRaises(ValueError, unpad, b("123456\x00"), 4, 'x923')
+ self.assertRaises(ValueError, unpad, b("123456\x00\x00\x00\x00\x05"), 4, 'x923')
+
+class ISO7816_Tests(unittest.TestCase):
+
+ def test1(self):
+ padded = pad(b(""), 4, 'iso7816')
+ self.failUnless(padded == uh("80000000"))
+ back = unpad(padded, 4, 'iso7816')
+ self.failUnless(back == b(""))
+
+ def test2(self):
+ padded = pad(uh("12345678"), 4, 'iso7816')
+ self.failUnless(padded == uh("1234567880000000"))
+ back = unpad(padded, 4, 'iso7816')
+ self.failUnless(back == uh("12345678"))
+
+ def test3(self):
+ padded = pad(uh("123456"), 4, 'iso7816')
+ self.failUnless(padded == uh("12345680"))
+ #import pdb; pdb.set_trace()
+ back = unpad(padded, 4, 'iso7816')
+ self.failUnless(back == uh("123456"))
+
+ def test4(self):
+ padded = pad(uh("1234567890"), 4, 'iso7816')
+ self.failUnless(padded == uh("1234567890800000"))
+ back = unpad(padded, 4, 'iso7816')
+ self.failUnless(back == uh("1234567890"))
+
+ def testn1(self):
+ self.assertRaises(ValueError, unpad, b("123456\x81"), 4, 'iso7816')
+
+def get_tests(config={}):
+ tests = []
+ tests += list_test_cases(PKCS7_Tests)
+ tests += list_test_cases(X923_Tests)
+ tests += list_test_cases(ISO7816_Tests)
+ return tests
+
+if __name__ == '__main__':
+ suite = lambda: unittest.TestSuite(get_tests())
+ unittest.main(defaultTest='suite')
+
diff --git a/lib/Crypto/SelfTest/__init__.py b/lib/Crypto/SelfTest/__init__.py
index 7110cd2..cb5782f 100644
--- a/lib/Crypto/SelfTest/__init__.py
+++ b/lib/Crypto/SelfTest/__init__.py
@@ -85,6 +85,7 @@ def get_tests(config={}):
from Crypto.SelfTest import Random; tests += Random.get_tests(config=config)
from Crypto.SelfTest import Util; tests += Util.get_tests(config=config)
from Crypto.SelfTest import Signature; tests += Signature.get_tests(config=config)
+ from Crypto.SelfTest import IO; tests += IO.get_tests(config=config)
return tests
if __name__ == '__main__':
diff --git a/lib/Crypto/Signature/PKCS1_v1_5.py b/lib/Crypto/Signature/PKCS1_v1_5.py
index 22bb340..be48aee 100644
--- a/lib/Crypto/Signature/PKCS1_v1_5.py
+++ b/lib/Crypto/Signature/PKCS1_v1_5.py
@@ -62,7 +62,7 @@ __all__ = [ 'new', 'PKCS115_SigScheme' ]
import Crypto.Util.number
from Crypto.Util.number import ceil_div
-from Crypto.Util.asn1 import DerSequence, DerNull, DerOctetString
+from Crypto.Util.asn1 import DerSequence, DerNull, DerOctetString, DerObjectId
from Crypto.Util.py3compat import *
class PKCS115_SigScheme:
@@ -208,7 +208,10 @@ def EMSA_PKCS1_V1_5_ENCODE(hash, emLen):
# { OID id-sha512 PARAMETERS NULL }
# }
#
- digestAlgo = DerSequence([_HASH_OIDS[hash.name], DerNull().encode()])
+ digestAlgo = DerSequence([
+ DerObjectId(_HASH_OIDS[hash.name]).encode(),
+ DerNull().encode()
+ ])
digest = DerOctetString(hash.digest())
digestInfo = DerSequence([
digestAlgo.encode(),
@@ -245,62 +248,64 @@ _HASH_OIDS = {
#: iso(1) member-body(2) us(840) rsadsi(113549)
#: digestAlgorithm(2) 2
#: }
- "MD2": b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02'),
- "md2": b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02'),
+ "MD2": "1.2.840.113549.2.2",
+ "md2": "1.2.840.113549.2.2",
#: id-md4 OBJECT IDENTIFIER ::= {
#: iso(1) member-body(2) us(840) rsadsi(113549)
#: digestAlgorithm(2) 4
#: }
- "MD4": b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04'),
- "md4": b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04'),
+ "MD4": "1.2.840.113549.2.4",
+ "md4": "1.2.840.113549.2.4",
#: id-md5 OBJECT IDENTIFIER ::= {
#: iso(1) member-body(2) us(840) rsadsi(113549)
#: digestAlgorithm(2) 5
#: }
- "MD5": b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05'),
- "md5": b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05'),
+ "MD5": "1.2.840.113549.2.5",
+ "md5": "1.2.840.113549.2.5",
#: id-ripemd160 OBJECT IDENTIFIER ::= {
#: iso(1) identified-organization(3) teletrust(36)
#: algorithm(3) hashAlgorithm(2) ripemd160(1)
#: }
- "RIPEMD160": b("\x06\x05\x2b\x24\x03\x02\x01"),
- "ripemd160": b("\x06\x05\x2b\x24\x03\x02\x01"),
+ "RIPEMD160": "1.3.36.3.2.1",
+ "ripemd160": "1.3.36.3.2.1",
#: id-sha1 OBJECT IDENTIFIER ::= {
#: iso(1) identified-organization(3) oiw(14) secsig(3)
#: algorithms(2) 26
#: }
- "SHA1": b('\x06\x05\x2b\x0e\x03\x02\x1a'),
- "sha1": b('\x06\x05\x2b\x0e\x03\x02\x1a'),
+ "SHA1": "1.3.14.3.2.26",
+ "sha1": "1.3.14.3.2.26",
#: id-sha224 OBJECT IDENTIFIER ::= {
#: joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3)
#: nistalgorithm(4) hashalgs(2) 4
#: }
- "SHA224": b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04'),
- "sha224": b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04'),
+ "SHA224": '2.16.840.1.101.3.4.2.4',
+ "sha224": '2.16.840.1.101.3.4.2.4',
#: id-sha256 OBJECT IDENTIFIER ::= {
#: joint-iso-itu-t(2) country(16) us(840) organization(1)
#: gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1
#: }
- "SHA256": b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01'),
- "sha256": b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01'),
+ "SHA256": "2.16.840.1.101.3.4.2.1",
+ "sha256": "2.16.840.1.101.3.4.2.1",
#: id-sha384 OBJECT IDENTIFIER ::= {
#: joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3)
#: nistalgorithm(4) hashalgs(2) 2
#: }
- "SHA384": b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02'),
- "sha384": b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02'),
+ "SHA384": '2.16.840.1.101.3.4.2.2',
+ "sha384": '2.16.840.1.101.3.4.2.2',
#: id-sha512 OBJECT IDENTIFIER ::= {
#: joint-iso-itu-t(2)
#: country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3
#: }
- "SHA512": b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03'),
- "sha512": b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03'),
+ "SHA512": "2.16.840.1.101.3.4.2.3",
+ "sha512": "2.16.840.1.101.3.4.2.3",
+
}
+
diff --git a/lib/Crypto/Util/Padding.py b/lib/Crypto/Util/Padding.py
new file mode 100644
index 0000000..b8498a3
--- /dev/null
+++ b/lib/Crypto/Util/Padding.py
@@ -0,0 +1,103 @@
+#
+# -*- coding: utf-8 -*-
+#
+# Util/Padding.py : Functions to manage padding
+#
+# ===================================================================
+# 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.
+# ===================================================================
+
+""" Functions to manage padding
+
+This module provides minimal support for adding and removing standard padding
+from data.
+"""
+
+__all__ = [ 'PaddingError', 'pad', 'unpad' ]
+
+from Crypto.Util.py3compat import *
+
+class PaddingError(ValueError):
+ """Exception raised when padding is incorrect and cannot be removed."""
+ pass
+
+def pad(data_to_pad, block_size, style='pkcs7'):
+ """Apply standard padding.
+
+ :Parameters:
+ data_to_pad : byte string
+ The data that needs to be padded.
+ block_size : integer
+ The block boundary to use for padding. The output length is guaranteed
+ to be a multiple of ``block_size``.
+ style : string
+ Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*.
+ :Return:
+ The original data with the appropriate padding added at the end.
+ """
+
+ padding_len = block_size-len(data_to_pad)%block_size
+ if style == 'pkcs7':
+ padding = bchr(padding_len)*padding_len
+ elif style == 'x923':
+ padding = bchr(0)*(padding_len-1) + bchr(padding_len)
+ elif style == 'iso7816':
+ padding = bchr(128) + bchr(0)*(padding_len-1)
+ else:
+ raise ValueError("Unknown padding style")
+ return data_to_pad + padding
+
+def unpad(padded_data, block_size, style='pkcs7'):
+ """Remove standard padding.
+
+ :Parameters:
+ padded_data : byte string
+ A piece of data with padding that needs to be stripped.
+ block_size : integer
+ The block boundary to use for padding. The input length
+ must be a multiple of ``block_size``.
+ style : string
+ Padding algorithm. It can be *'pkcs7'* (default), *'iso7816'* or *'x923'*.
+ :Return:
+ Data without padding.
+ :Raises PaddingError:
+ if the padding is incorrect.
+ """
+
+ pdata_len = len(padded_data)
+ if pdata_len % block_size:
+ raise PaddingError("Input data is not padded")
+ if style in ('pkcs7', 'x923'):
+ padding_len = bord(padded_data[-1])
+ if padding_len<1 or padding_len>min(block_size, pdata_len):
+ raise PaddingError("Padding is incorrect.")
+ if style == 'pkcs7':
+ if padded_data[-padding_len:]!=bchr(padding_len)*padding_len:
+ raise PaddingError("PKCS#7 padding is incorrect.")
+ else:
+ if padded_data[-padding_len:-1]!=bchr(0)*(padding_len-1):
+ raise PaddingError("ANSI X.923 padding is incorrect.")
+ elif style == 'iso7816':
+ padding_len = pdata_len - padded_data.rfind(bchr(128))
+ if padding_len<1 or padding_len>min(block_size, pdata_len):
+ raise PaddingError("Padding is incorrect.")
+ if padding_len>1 and padded_data[1-padding_len:]!=bchr(0)*(padding_len-1):
+ raise PaddingError("ISO 7816-4 padding is incorrect.")
+ else:
+ raise ValueError("Unknown padding style")
+ return padded_data[:-padding_len]
+
diff --git a/lib/Crypto/Util/__init__.py b/lib/Crypto/Util/__init__.py
index 18df5e0..f81a8c0 100644
--- a/lib/Crypto/Util/__init__.py
+++ b/lib/Crypto/Util/__init__.py
@@ -23,16 +23,21 @@
Contains useful modules that don't belong into any of the
other Crypto.* subpackages.
+======================== =============================================
+Module Description
+======================== =============================================
Crypto.Util.number Number-theoretic functions (primality testing, etc.)
Crypto.Util.Counter Fast counter functions for CTR cipher modes.
Crypto.Util.randpool Random number generation
-Crypto.Util.RFC1751 Converts between 128-bit keys and human-readable
- strings of words.
+Crypto.Util.RFC1751 Converts between 128-bit keys and human-readable strings of words.
Crypto.Util.asn1 Minimal support for ASN.1 DER encoding
+Crypto.Util.Padding Set of functions for adding and removing padding.
+======================== =============================================
"""
-__all__ = ['randpool', 'RFC1751', 'number', 'strxor', 'asn1', 'Counter' ]
+__all__ = ['randpool', 'RFC1751', 'number', 'strxor', 'asn1', 'Counter',
+ 'Padding' ]
__revision__ = "$Id$"
diff --git a/lib/Crypto/Util/py21compat.py b/lib/Crypto/Util/py21compat.py
index 624408b..658fd36 100644
--- a/lib/Crypto/Util/py21compat.py
+++ b/lib/Crypto/Util/py21compat.py
@@ -81,4 +81,21 @@ except TypeError:
return True
return False
+#
+# Python 2.2 introduces the built-in staticmethod(). Python 2.4 turns
+# it into a function decorator (@staticmethod).
+#
+# The following recipe for achieving the same thing in Python 2.1 comes
+# from the Python Cookbok ("Implementanting Static Methods").
+#
+try:
+ class A:
+ def a(): pass
+ a = staticmethod(a)
+except NameError:
+ class staticmethod:
+ def __init__(self, anycallable):
+ self.__call__ = anycallable
+ __all__ += ['staticmethod']
+
# vim:set ts=4 sw=4 sts=4 expandtab:
diff --git a/lib/Crypto/Util/py3compat.py b/lib/Crypto/Util/py3compat.py
index e2ca20f..b8b89bf 100644
--- a/lib/Crypto/Util/py3compat.py
+++ b/lib/Crypto/Util/py3compat.py
@@ -77,12 +77,16 @@ if sys.version_info[0] == 2:
return s.encode('latin-1')
except:
return ''.join(s)
+ def tostr(bs):
+ return unicode(bs, 'latin-1')
else:
def tobytes(s):
if isinstance(s, unicode):
return s.encode("latin-1")
else:
return ''.join(s)
+ def tostr(bs):
+ return bs.decode('latin-1')
# In Pyton 2.x, StringIO is a stand-alone module
from StringIO import StringIO as BytesIO
else:
@@ -105,6 +109,8 @@ else:
return s.encode("latin-1")
else:
return bytes(s)
+ def tostr(bs):
+ return bs.decode("latin-1")
# In Pyton 3.x, StringIO is a sub-module of io
from io import BytesIO
diff --git a/lib/Crypto/__init__.py b/lib/Crypto/__init__.py
index cea887c..79c8286 100644
--- a/lib/Crypto/__init__.py
+++ b/lib/Crypto/__init__.py
@@ -41,7 +41,7 @@ Crypto.Util
generation, number theoretic functions)
"""
-__all__ = ['Cipher', 'Hash', 'Protocol', 'PublicKey', 'Util', 'Signature']
+__all__ = ['Cipher', 'Hash', 'Protocol', 'PublicKey', 'Util', 'Signature', 'IO']
__version__ = '2.6' # See also below and setup.py
__revision__ = "$Id$"
diff --git a/setup.py b/setup.py
index 5af83ac..903a81f 100644
--- a/setup.py
+++ b/setup.py
@@ -402,9 +402,11 @@ kw = {'name':"pycrypto",
"Crypto.SelfTest.Random.OSRNG",
"Crypto.SelfTest.Util",
"Crypto.SelfTest.Signature",
+ "Crypto.SelfTest.IO",
"Crypto.Protocol",
"Crypto.PublicKey",
- "Crypto.Signature"],
+ "Crypto.Signature",
+ "Crypto.IO"],
'package_dir' : { "Crypto": "lib/Crypto" },
'ext_modules': plat_ext + [
# _fastmath (uses GNU mp library)