def testDecode6(self): # Two integers der = DerSequence() der.decode(b('0\x08\x02\x02\x01\x80\x02\x02\x00\xff')) self.assertEquals(len(der),2) self.assertEquals(der[0],0x180L) self.assertEquals(der[1],0xFFL)
def testDecode4(self): # One very long integer der = DerSequence() der.decode(b('0\x82\x01\x05')+ b('\x02\x82\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00')) self.assertEquals(len(der),1) self.assertEquals(der[0],2L**2048)
def testDecode7(self): # One integer and 2 other types der = DerSequence() der.decode(b('0\x0A\x02\x02\x01\x80\x24\x02\xb6\x63\x12\x00')) self.assertEquals(len(der),3) self.assertEquals(der[0],0x180L) self.assertEquals(der[1],b('\x24\x02\xb6\x63')) self.assertEquals(der[2],b('\x12\x00'))
def _create_subject_public_key_info(algo_oid, secret_key, params=None): if params is None: params = DerNull() spki = DerSequence([ DerSequence([ DerObjectId(algo_oid), params]), DerBitString(secret_key) ]) return spki.encode()
def verify(self, msg_hash, signature): """Verify that a certain DSS signature is authentic. This function checks if the party holding the private half of the key really signed the message. :Parameters: msg_hash : hash object The hash that was carried out over the message. This is an object belonging to the `Cryptodome.Hash` module. Under mode *'fips-186-3'*, the hash must be a FIPS approved secure hash (SHA-1 or a member of the SHA-2 family), of cryptographic strength appropriate for the DSA key. For instance, a 3072/256 DSA key can only be used in combination with SHA-512. signature : byte string The signature that needs to be validated. :Raise ValueError: If the signature is not authentic. """ if not self._valid_hash(msg_hash): raise ValueError("Hash does not belong to SHS") if self._encoding == 'binary': if len(signature) != (2 * self._order_bytes): raise ValueError("The signature is not authentic (length)") r_prime, s_prime = [Integer.from_bytes(x) for x in (signature[:self._order_bytes], signature[self._order_bytes:])] else: try: der_seq = DerSequence().decode(signature) except (ValueError, IndexError): raise ValueError("The signature is not authentic (DER)") if len(der_seq) != 2 or not der_seq.hasOnlyInts(): raise ValueError("The signature is not authentic (DER content)") r_prime, s_prime = der_seq[0], der_seq[1] if not (0 < r_prime < self._order) or not (0 < s_prime < self._order): raise ValueError("The signature is not authentic (d)") z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes]) result = self._key._verify(z, (r_prime, s_prime)) if not result: raise ValueError("The signature is not authentic") # Make PyCryptodome code to fail return False
def testEncode2(self): # Indexing der = DerSequence() der.append(0) der[0] = 1 self.assertEquals(len(der),1) self.assertEquals(der[0],1) self.assertEquals(der[-1],1) self.assertEquals(der.encode(), b('0\x03\x02\x01\x01')) # der[:] = [1] self.assertEquals(len(der),1) self.assertEquals(der[0],1) self.assertEquals(der.encode(), b('0\x03\x02\x01\x01'))
def der2rsa(der): # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280) cert = DerSequence() cert.decode(der) tbs_certificate = DerSequence() tbs_certificate.decode(cert[0]) subject_public_key_info = tbs_certificate[6] # Initialize RSA key return RSA.importKey(subject_public_key_info)
def verify(self, msg_hash, signature): """Check if a certain (EC)DSA signature is authentic. Args: msg_hash (hash object): The hash that was carried out over the message. This is an object belonging to the :mod:`Cryptodome.Hash` module. Under mode ``'fips-186-3'``, the hash must be a FIPS approved secure hash (SHA-2 or SHA-3). signature (``bytes``): The signature that needs to be validated. :raise ValueError: if the signature is not authentic """ if not self._valid_hash(msg_hash): raise ValueError("Hash is not sufficiently strong") if self._encoding == 'binary': if len(signature) != (2 * self._order_bytes): raise ValueError("The signature is not authentic (length)") r_prime, s_prime = [ Integer.from_bytes(x) for x in (signature[:self._order_bytes], signature[self._order_bytes:]) ] else: try: der_seq = DerSequence().decode(signature, strict=True) except (ValueError, IndexError): raise ValueError("The signature is not authentic (DER)") if len(der_seq) != 2 or not der_seq.hasOnlyInts(): raise ValueError( "The signature is not authentic (DER content)") r_prime, s_prime = Integer(der_seq[0]), Integer(der_seq[1]) if not (0 < r_prime < self._order) or not (0 < s_prime < self._order): raise ValueError("The signature is not authentic (d)") z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes]) result = self._key._verify(z, (r_prime, s_prime)) if not result: raise ValueError("The signature is not authentic") # Make PyCryptodome code to fail return False
def testEncode8(self): # One integer and another type (yet to encode) der = DerSequence() der.append(0x180L) der.append(DerSequence([5])) self.assertEquals(der.encode(), b('0\x09\x02\x02\x01\x800\x03\x02\x01\x05')) self.failIf(der.hasOnlyInts())
def testEncode7(self): # One integer and another type (already encoded) der = DerSequence() der.append(0x180) der.append(b('0\x03\x02\x01\x05')) self.assertEquals(der.encode(), b('0\x09\x02\x02\x01\x800\x03\x02\x01\x05')) self.failIf(der.hasOnlyInts())
def import_key(extern_key, salt=None): der, marker, _ = PEM.decode(extern_key) ints = DerSequence().decode(der) if not marker.startswith('myDSA'): raise ValueError('Invalid format') key_dict = dict(zip(('p', 'q', 'g', 'y', 'x'), map(Integer, ints))) return myDSA(key_dict, salt)
def testDecode8(self): # Only 2 other types der = DerSequence() der.decode(b('0\x06\x24\x02\xb6\x63\x12\x00')) self.assertEquals(len(der), 2) self.assertEquals(der[0], b('\x24\x02\xb6\x63')) self.assertEquals(der[1], b('\x12\x00')) self.assertEquals(der.hasInts(), 0) self.assertEquals(der.hasInts(False), 0) self.failIf(der.hasOnlyInts()) self.failIf(der.hasOnlyInts(False))
def _extract_subject_public_key_info(x509_certificate): """Extract subjectPublicKeyInfo from a DER X.509 certificate.""" certificate = DerSequence().decode(x509_certificate, nr_elements=3) tbs_certificate = DerSequence().decode(certificate[0], nr_elements=list(range(6, 11))) index = 5 try: tbs_certificate[0] + 1 # Version not present version = 1 except TypeError: version = DerInteger(explicit=0).decode(tbs_certificate[0]).value if version not in (2, 3): raise ValueError("Incorrect X.509 certificate version") index = 6 return tbs_certificate[index]
def _import_pkcs8(encoded, passphrase, params): if params: raise ValueError("PKCS#8 already includes parameters") k = PKCS8.unwrap(encoded, passphrase) if k[0] != oid: raise ValueError("No PKCS#8 encoded DSA key") x = DerInteger().decode(k[1]).value p, q, g = list(DerSequence().decode(k[2])) tup = (pow(g, x, p), g, p, q, x) return construct(tup)
def test_expected_only_integers(self): der_bin1 = DerSequence([1, 2, 3]).encode() der_bin2 = DerSequence([1, 2, DerSequence([3, 4])]).encode() DerSequence().decode(der_bin1, only_ints_expected=True) DerSequence().decode(der_bin1, only_ints_expected=False) DerSequence().decode(der_bin2, only_ints_expected=False) self.assertRaises(ValueError, DerSequence().decode, der_bin2, only_ints_expected=True)
def testErrDecode3(self): # Wrong length format der = DerSequence() # Missing length in sub-item self.assertRaises(ValueError, der.decode, b('\x30\x04\x02\x01\x01\x00')) # Valid BER, but invalid DER length self.assertRaises(ValueError, der.decode, b('\x30\x81\x03\x02\x01\x01')) self.assertRaises(ValueError, der.decode, b('\x30\x04\x02\x81\x01\x01'))
def testDecode1(self): # Empty sequence der = DerSequence() der.decode(b('0\x00')) self.assertEquals(len(der), 0) # One single-byte integer (zero) der.decode(b('0\x03\x02\x01\x00')) self.assertEquals(len(der), 1) self.assertEquals(der[0], 0) # Invariant der.decode(b('0\x03\x02\x01\x00')) self.assertEquals(len(der), 1) self.assertEquals(der[0], 0)
def generate_rsa_key_pair(): rsa_key = RSA.generate(2048) private_key = DerSequence([0, rsa_key.n, rsa_key.e, rsa_key.d, rsa_key.p, rsa_key.q, rsa_key.d % (rsa_key.p - 1), rsa_key.d % (rsa_key.q - 1), Integer(rsa_key.q).inverse(rsa_key.p) ]).encode() pub_key = rsa_key.publickey() public_key = DerSequence([pub_key.n, pub_key.e ]).encode() return private_key, public_key
def _import_subjectPublicKeyInfo(encoded, passphrase, params): algoid, encoded_key, emb_params = _expand_subject_public_key_info(encoded) if algoid != oid: raise ValueError("No DSA subjectPublicKeyInfo") if params and emb_params: raise ValueError("Too many DSA parameters") y = DerInteger().decode(encoded_key).value p, q, g = list(DerSequence().decode(params or emb_params)) tup = (y, g, p, q) return construct(tup)
def rsa_public_from_der_certificate(certificate): # Extract subject_public_key_info field from X.509 certificate (see RFC3280) try: # try to extract pubkey from scapy.layers.x509 X509Cert type in case # der_certificate is of type X509Cert # Note: der_certificate may not be of type X509Cert if it wasn't # received completely, in that case, we'll try to extract it anyway # using the old method. # TODO: get rid of the old method and always expect X509Cert obj ? return RSA.importKey(str(certificate.tbsCertificate.subjectPublicKeyInfo)) except AttributeError: pass # Fallback method, may pot. allow to extract pubkey from incomplete der streams cert = DerSequence() cert.decode(certificate) tbs_certificate = DerSequence() tbs_certificate.decode(cert[0]) # first DER SEQUENCE # search for pubkey OID: rsaEncryption: "1.2.840.113549.1.1.1" # hex: 06 09 2A 86 48 86 F7 0D 01 01 01 subject_public_key_info = None for seq in tbs_certificate: if not isinstance(seq, basestring): continue # skip numerics and non sequence stuff if "\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01" in seq: subject_public_key_info = seq if subject_public_key_info is None: raise ValueError("could not find OID rsaEncryption 1.2.840.113549.1.1.1 in certificate") # Initialize RSA key return RSA.importKey(subject_public_key_info)
def test_verify(self): # Ecdsa signature is not unique, so we only test if we can verify it pri_key = ECC.generate(curve="P-256") key = pri_key.export_key(format="DER") pub_key = pri_key.public_key() signer = Sha256WithEcdsaSigner("/K/KEY/x", key) pkt = make_data("/test", MetaInfo(), b"test content", signer=signer) _, _, _, sig_ptrs = parse_data(pkt) # Test its format is ASN.1 der format DerSequence().decode(bytes(sig_ptrs.signature_value_buf)) validator = EccChecker.from_key( "/K/KEY/x", bytes(pub_key.export_key(format='DER'))) assert aio.run(validator(Name.from_str("/test"), sig_ptrs))
def rsa_public_from_der_certificate(certificate): # Extract subject_public_key_info field from X.509 certificate (see RFC3280) try: # try to extract pubkey from scapy.layers.x509 X509Cert type in case # der_certificate is of type X509Cert # Note: der_certificate may not be of type X509Cert if it wasn't # received completely, in that case, we'll try to extract it anyway # using the old method. # TODO: get rid of the old method and always expect X509Cert obj ? """ Rebuild ASN1 SubjectPublicKeyInfo since X509Cert does not provide the full struct ASN1F_SEQUENCE( ASN1F_SEQUENCE(ASN1F_OID("pubkey_algo","1.2.840.113549.1.1.1"), ASN1F_field("pk_value",ASN1_NULL(0))), ASN1F_BIT_STRING("pubkey","") ), """ subject_public_key_info = ASN1_SEQUENCE([ ASN1_SEQUENCE([certificate.pubkey_algo, certificate.pk_value]), certificate.pubkey ]) return RSA.importKey(str(subject_public_key_info)) except AttributeError: pass # Fallback method, may pot. allow to extract pubkey from incomplete der streams cert = DerSequence() cert.decode(certificate) tbs_certificate = DerSequence() tbs_certificate.decode(cert[0]) # first DER SEQUENCE # search for pubkey OID: rsaEncryption: "1.2.840.113549.1.1.1" # hex: 06 09 2A 86 48 86 F7 0D 01 01 01 subject_public_key_info = None for seq in tbs_certificate: if not isinstance(seq, basestring): continue # skip numerics and non sequence stuff if "\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01" in seq: subject_public_key_info = seq if subject_public_key_info is None: raise ValueError( "could not find OID rsaEncryption 1.2.840.113549.1.1.1 in certificate" ) # Initialize RSA key return RSA.importKey(subject_public_key_info)
def testDecode8(self): # Only 2 other types der = DerSequence() der.decode(b('0\x06\x24\x02\xb6\x63\x12\x00')) self.assertEquals(len(der),2) self.assertEquals(der[0],b('\x24\x02\xb6\x63')) self.assertEquals(der[1],b('\x12\x00')) self.assertEquals(der.hasInts(), 0) self.assertEquals(der.hasInts(False), 0) self.failIf(der.hasOnlyInts()) self.failIf(der.hasOnlyInts(False))
def get_public_key_from_file(file_name): with open(file_name) as f: pem = f.read() lines = pem.replace(" ", '').split() der = a2b_base64(''.join(lines[1:-1])) # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280) cert = DerSequence() cert.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] # Initialize RSA key publicKey = RSA.importKey(subjectPublicKeyInfo) return publicKey.publickey()
def _import_private_der(encoded, passphrase, curve_oid=None): # See RFC5915 https://tools.ietf.org/html/rfc5915 # # ECPrivateKey ::= SEQUENCE { # version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), # privateKey OCTET STRING, # parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, # publicKey [1] BIT STRING OPTIONAL # } private_key = DerSequence().decode(encoded, nr_elements=(3, 4)) if private_key[0] != 1: raise ValueError("Incorrect ECC private key version") try: parameters = DerObjectId(explicit=0).decode(private_key[2]).value if curve_oid is not None and parameters != curve_oid: raise ValueError("Curve mismatch") curve_oid = parameters except ValueError: pass if curve_oid is None: raise ValueError("No curve found") for curve_name, curve in _curves.items(): if curve.oid == curve_oid: break else: raise UnsupportedEccFeature("Unsupported ECC curve (OID: %s)" % curve_oid) scalar_bytes = DerOctetString().decode(private_key[1]).payload modulus_bytes = curve.p.size_in_bytes() if len(scalar_bytes) != modulus_bytes: raise ValueError("Private key is too small") d = Integer.from_bytes(scalar_bytes) # Decode public key (if any) if len(private_key) == 4: public_key_enc = DerBitString(explicit=1).decode(private_key[3]).value public_key = _import_public_der(public_key_enc, curve_oid=curve_oid) point_x = public_key.pointQ.x point_y = public_key.pointQ.y else: point_x = point_y = None return construct(curve=curve_name, d=d, point_x=point_x, point_y=point_y)
def testDecode1(self): # Empty sequence der = DerSequence() der.decode(b('0\x00')) self.assertEquals(len(der),0) # One single-byte integer (zero) der.decode(b('0\x03\x02\x01\x00')) self.assertEquals(len(der),1) self.assertEquals(der[0],0) # Invariant der.decode(b('0\x03\x02\x01\x00')) self.assertEquals(len(der),1) self.assertEquals(der[0],0)
def export_key(self, keytype): ints = [self.p, self.q, self.g, self.y] if keytype == 'priv': ints.append(self.x) key_type = 'myDSA PRIVATE KEY' elif keytype == 'pub': key_type = 'myDSA PUBLIC KEY' else: raise ValueError('keytype should be one of "pub" or "priv"') binary = DerSequence(ints).encode() return PEM.encode(binary, key_type)
def _expand_subject_public_key_info(encoded): """Parse a SubjectPublicKeyInfo structure. It returns a triple with: * OID (string) * encoded public key (bytes) * Algorithm parameters (bytes or None) """ # # SubjectPublicKeyInfo ::= SEQUENCE { # algorithm AlgorithmIdentifier, # subjectPublicKey BIT STRING # } # # AlgorithmIdentifier ::= SEQUENCE { # algorithm OBJECT IDENTIFIER, # parameters ANY DEFINED BY algorithm OPTIONAL # } # spki = DerSequence().decode(encoded, nr_elements=2) algo = DerSequence().decode(spki[0], nr_elements=(1, 2)) algo_oid = DerObjectId().decode(algo[0]) spk = DerBitString().decode(spki[1]).value if len(algo) == 1: algo_params = None else: try: DerNull().decode(algo[1]) algo_params = None except: algo_params = algo[1] return algo_oid.value, spk, algo_params
def testEncode4(self): # One very long integer der = DerSequence() der.append(2L**2048) self.assertEquals(der.encode(), b('0\x82\x01\x05')+ b('\x02\x82\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00'))
def testEncode4(self): # One very long integer der = DerSequence() der.append(2**2048) self.assertEquals(der.encode(), b('0\x82\x01\x05')+ b('\x02\x82\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+ b('\x00\x00\x00\x00\x00\x00\x00\x00\x00'))
def test_verify(self): # Ecdsa signature is not unique, so we only test if we can verify it pri_key = ECC.generate(curve="P-256") key = pri_key.export_key(format="DER") pub_key = pri_key.public_key() signer = Sha256WithEcdsaSigner("/K/KEY/x", key) pkt = make_data("/test", MetaInfo(), b"test content", signer=signer) _, _, _, sig_ptrs = parse_data(pkt) # Test its format is ASN.1 der format DerSequence().decode(bytes(sig_ptrs.signature_value_buf)) verifier = DSS.new(pub_key, 'fips-186-3', 'der') h = SHA256.new() for content in sig_ptrs.signature_covered_part: h.update(content) # verify() throws ValueError if it fails, the return value is undefined # So do not assert its value verifier.verify(h, bytes(sig_ptrs.signature_value_buf))
def sign(self, msg_hash): """Produce the DSA/ECDSA signature of a message. :parameter msg_hash: The hash that was carried out over the message. The object belongs to the :mod:`Cryptodome.Hash` package. Under mode *'fips-186-3'*, the hash must be a FIPS approved secure hash (SHA-1 or a member of the SHA-2 family), of cryptographic strength appropriate for the DSA key. For instance, a 3072/256 DSA key can only be used in combination with SHA-512. :type msg_hash: hash object :return: The signature as a *byte string* :raise ValueError: if the hash algorithm is incompatible to the (EC)DSA key :raise TypeError: if the (EC)DSA key has no private half """ if not self._valid_hash(msg_hash): raise ValueError("Hash is not sufficiently strong") # Generate the nonce k (critical!) nonce = self._compute_nonce(msg_hash) # Perform signature using the raw API z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes]) sig_pair = self._key._sign(z, nonce) # Encode the signature into a single byte string if self._encoding == 'binary': output = b"".join([long_to_bytes(x, self._order_bytes) for x in sig_pair]) else: # Dss-sig ::= SEQUENCE { # r INTEGER, # s INTEGER # } # Ecdsa-Sig-Value ::= SEQUENCE { # r INTEGER, # s INTEGER # } output = DerSequence(sig_pair).encode() return output
def _import_pkcs1_private(encoded, *kwargs): # RSAPrivateKey ::= SEQUENCE { # version Version, # modulus INTEGER, -- n # publicExponent INTEGER, -- e # privateExponent INTEGER, -- d # prime1 INTEGER, -- p # prime2 INTEGER, -- q # exponent1 INTEGER, -- d mod (p-1) # exponent2 INTEGER, -- d mod (q-1) # coefficient INTEGER -- (inverse of q) mod p # } # # Version ::= INTEGER der = DerSequence().decode(encoded, nr_elements=9, only_ints_expected=True) if der[0] != 0: raise ValueError("No PKCS#1 encoding of an RSA private key") return construct(der[1:6] + [Integer(der[4]).inverse(der[5])])
def sign(self, msg_hash): """Compute the DSA/ECDSA signature of a message. Args: msg_hash (hash object): The hash that was carried out over the message. The object belongs to the :mod:`Cryptodome.Hash` package. Under mode ``'fips-186-3'``, the hash must be a FIPS approved secure hash (SHA-2 or SHA-3). :return: The signature as ``bytes`` :raise ValueError: if the hash algorithm is incompatible to the (EC)DSA key :raise TypeError: if the (EC)DSA key has no private half """ if not self._key.has_private(): raise TypeError("Private key is needed to sign") if not self._valid_hash(msg_hash): raise ValueError("Hash is not sufficiently strong") # Generate the nonce k (critical!) nonce = self._compute_nonce(msg_hash) # Perform signature using the raw API z = Integer.from_bytes(msg_hash.digest()[:self._order_bytes]) sig_pair = self._key._sign(z, nonce) # Encode the signature into a single byte string if self._encoding == 'binary': output = b"".join( [long_to_bytes(x, self._order_bytes) for x in sig_pair]) else: # Dss-sig ::= SEQUENCE { # r INTEGER, # s INTEGER # } # Ecdsa-Sig-Value ::= SEQUENCE { # r INTEGER, # s INTEGER # } output = DerSequence(sig_pair).encode() return output
def testEncode2(self): # Indexing der = DerSequence() der.append(0) der[0] = 1 self.assertEquals(len(der), 1) self.assertEquals(der[0], 1) self.assertEquals(der[-1], 1) self.assertEquals(der.encode(), b('0\x03\x02\x01\x01')) # der[:] = [1] self.assertEquals(len(der), 1) self.assertEquals(der[0], 1) self.assertEquals(der.encode(), b('0\x03\x02\x01\x01'))
def rsa_public_from_der_certificate(certificate): # Extract subject_public_key_info field from X.509 certificate (see RFC3280) try: # try to extract pubkey from scapy.layers.x509 X509Cert type in case # der_certificate is of type X509Cert # Note: der_certificate may not be of type X509Cert if it wasn't # received completely, in that case, we'll try to extract it anyway # using the old method. # TODO: get rid of the old method and always expect X509Cert obj ? return RSA.importKey( str(certificate.tbsCertificate.subjectPublicKeyInfo)) except AttributeError: pass # Fallback method, may pot. allow to extract pubkey from incomplete der streams cert = DerSequence() cert.decode(certificate) tbs_certificate = DerSequence() tbs_certificate.decode(cert[0]) # first DER SEQUENCE # search for pubkey OID: rsaEncryption: "1.2.840.113549.1.1.1" # hex: 06 09 2A 86 48 86 F7 0D 01 01 01 subject_public_key_info = None for seq in tbs_certificate: if not isinstance(seq, bytes) and not isinstance(seq, str): continue # skip numerics and non sequence stuff if b"\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01" in seq: subject_public_key_info = seq if subject_public_key_info is None: raise ValueError( "could not find OID rsaEncryption 1.2.840.113549.1.1.1 in certificate" ) # Initialize RSA key return RSA.importKey(subject_public_key_info)
def public_key_import_from_x509_certificate_string(certificate_string): if certificate_string.find('-----BEGIN CERTIFICATE-----') \ and not certificate_string.find('-----BEGIN CERTIFICATE-----\n') \ and not certificate_string.find('-----BEGIN CERTIFICATE-----\r\n'): certificate_string = certificate_string.replace( '-----BEGIN CERTIFICATE-----', '-----BEGIN CERTIFICATE-----\n') if certificate_string.find('\n-----END CERTIFICATE-----') \ and not certificate_string.find('\n-----END CERTIFICATE-----') \ and not certificate_string.find('\r\n-----END CERTIFICATE-----'): certificate_string = certificate_string.replace( '-----END CERTIFICATE-----', '\n-----END CERTIFICATE-----') lines = certificate_string.replace(" ", '').split() der = a2b_base64(''.join(lines[1:-1])) # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280) cert = DerSequence() cert.decode(der) tbs_certificate = DerSequence() tbs_certificate.decode(cert[0]) subject_public_key_info = tbs_certificate[6] # Initialize RSA key public_key = RSA.importKey(subject_public_key_info) return public_key.publickey()
def _import_private_der(encoded, passphrase, curve_name=None): # ECPrivateKey ::= SEQUENCE { # version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), # privateKey OCTET STRING, # parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, # publicKey [1] BIT STRING OPTIONAL # } private_key = DerSequence().decode(encoded, nr_elements=(3, 4)) if private_key[0] != 1: raise ValueError("Incorrect ECC private key version") try: curve_name = DerObjectId(explicit=0).decode(private_key[2]).value except ValueError: pass if curve_name != _curve.oid: raise UnsupportedEccFeature("Unsupported ECC curve (OID: %s)" % curve_name) scalar_bytes = DerOctetString().decode(private_key[1]).payload order_bytes = _curve.order.size_in_bytes() if len(scalar_bytes) != order_bytes: raise ValueError("Private key is too small") d = Integer.from_bytes(scalar_bytes) # Decode public key (if any, it must be P-256) if len(private_key) == 4: public_key_enc = DerBitString(explicit=1).decode(private_key[3]).value public_key = _import_public_der(curve_name, public_key_enc) point_x = public_key.pointQ.x point_y = public_key.pointQ.y else: point_x = point_y = None return construct(curve="P-256", d=d, point_x=point_x, point_y=point_y)
def testEncode5(self): der = DerSequence() der += 1 der += b('\x30\x00') self.assertEquals(der.encode(), b('\x30\x05\x02\x01\x01\x30\x00'))
def testDecode2(self): # One single-byte integer (non-zero) der = DerSequence() der.decode(b('0\x03\x02\x01\x7f')) self.assertEquals(len(der),1) self.assertEquals(der[0],127)
def export_key(self, format='PEM', passphrase=None, pkcs=1, protection=None, randfunc=None): """Export this RSA key. Args: format (string): The format to use for wrapping the key: - *'PEM'*. (*Default*) Text encoding, done according to `RFC1421`_/`RFC1423`_. - *'DER'*. Binary encoding. - *'OpenSSH'*. Textual encoding, done according to OpenSSH specification. Only suitable for public keys (not private keys). passphrase (string): (*For private keys only*) The pass phrase used for protecting the output. pkcs (integer): (*For private keys only*) The ASN.1 structure to use for serializing the key. Note that even in case of PEM encoding, there is an inner ASN.1 DER structure. With ``pkcs=1`` (*default*), the private key is encoded in a simple `PKCS#1`_ structure (``RSAPrivateKey``). With ``pkcs=8``, the private key is encoded in a `PKCS#8`_ structure (``PrivateKeyInfo``). .. note:: This parameter is ignored for a public key. For DER and PEM, an ASN.1 DER ``SubjectPublicKeyInfo`` structure is always used. protection (string): (*For private keys only*) The encryption scheme to use for protecting the private key. If ``None`` (default), the behavior depends on :attr:`format`: - For *'DER'*, the *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC* scheme is used. The following operations are performed: 1. A 16 byte Triple DES key is derived from the passphrase using :func:`Cryptodome.Protocol.KDF.PBKDF2` with 8 bytes salt, and 1 000 iterations of :mod:`Cryptodome.Hash.HMAC`. 2. The private key is encrypted using CBC. 3. The encrypted key is encoded according to PKCS#8. - For *'PEM'*, the obsolete PEM encryption scheme is used. It is based on MD5 for key derivation, and Triple DES for encryption. Specifying a value for :attr:`protection` is only meaningful for PKCS#8 (that is, ``pkcs=8``) and only if a pass phrase is present too. The supported schemes for PKCS#8 are listed in the :mod:`Cryptodome.IO.PKCS8` module (see :attr:`wrap_algo` parameter). randfunc (callable): A function that provides random bytes. Only used for PEM encoding. The default is :func:`Cryptodome.Random.get_random_bytes`. Returns: byte string: the encoded key Raises: ValueError:when the format is unknown or when you try to encrypt a private key with *DER* format and PKCS#1. .. warning:: 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 .. _`PKCS#1`: http://www.ietf.org/rfc/rfc3447.txt .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt """ if passphrase is not None: passphrase = tobytes(passphrase) if randfunc is None: randfunc = Random.get_random_bytes if format == 'OpenSSH': e_bytes, n_bytes = [x.to_bytes() for x in (self._e, self._n)] if bord(e_bytes[0]) & 0x80: e_bytes = bchr(0) + e_bytes if bord(n_bytes[0]) & 0x80: n_bytes = bchr(0) + n_bytes keyparts = [b('ssh-rsa'), e_bytes, n_bytes] keystring = b('').join( [struct.pack(">I", len(kp)) + kp for kp in keyparts]) return b('ssh-rsa ') + binascii.b2a_base64(keystring)[:-1] # DER format is always used, even in case of PEM, which simply # encodes it into BASE64. if self.has_private(): binary_key = DerSequence([ 0, self.n, self.e, self.d, self.p, self.q, self.d % (self.p - 1), self.d % (self.q - 1), Integer(self.q).inverse(self.p) ]).encode() if pkcs == 1: key_type = 'RSA PRIVATE KEY' if format == 'DER' and passphrase: raise ValueError("PKCS#1 private key cannot be encrypted") else: # PKCS#8 if format == 'PEM' and protection is None: key_type = 'PRIVATE KEY' binary_key = PKCS8.wrap(binary_key, oid, None) else: key_type = 'ENCRYPTED PRIVATE KEY' if not protection: protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC' binary_key = PKCS8.wrap(binary_key, oid, passphrase, protection) passphrase = None else: key_type = "PUBLIC KEY" binary_key = _create_subject_public_key_info( oid, DerSequence([self.n, self.e])) if format == 'DER': return binary_key if format == 'PEM': pem_str = PEM.encode(binary_key, key_type, passphrase, randfunc) return tobytes(pem_str) raise ValueError( "Unknown key format '%s'. Cannot export the RSA key." % format)
def testEncode3(self): # One multi-byte integer (non-zero) der = DerSequence() der.append(0x180L) self.assertEquals(der.encode(), b('0\x04\x02\x02\x01\x80'))
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 | | | (called *N* or CPU/memory cost in scrypt). | | | | | | The default value for PBKDF2 is 1 000. | | | The default value for scrypt is 16 384. | +------------------+-----------------------------------------------+ | salt_size | Salt is used to thwart dictionary and rainbow | | | attacks on passwords. The default value is 8 | | | bytes. | +------------------+-----------------------------------------------+ | block_size | *(scrypt only)* Memory-cost (r). The default | | | value is 8. | +------------------+-----------------------------------------------+ | parallelization | *(scrypt only)* CPU-cost (p). The default | | | value is 1. | +------------------+-----------------------------------------------+ 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 ``Cryptodome.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 cipher_mode = DES3.MODE_CBC enc_oid = _OID_DES_EDE3_CBC elif protection in ('PBKDF2WithHMAC-SHA1AndAES128-CBC', 'scryptAndAES128-CBC'): key_size = 16 module = AES cipher_mode = AES.MODE_CBC enc_oid = _OID_AES128_CBC elif protection in ('PBKDF2WithHMAC-SHA1AndAES192-CBC', 'scryptAndAES192-CBC'): key_size = 24 module = AES cipher_mode = AES.MODE_CBC enc_oid = _OID_AES192_CBC elif protection in ('PBKDF2WithHMAC-SHA1AndAES256-CBC', 'scryptAndAES256-CBC'): key_size = 32 module = AES cipher_mode = AES.MODE_CBC enc_oid = _OID_AES256_CBC else: raise ValueError("Unknown PBES2 mode") # Get random data iv = randfunc(module.block_size) salt = randfunc(prot_params.get("salt_size", 8)) # Derive key from password if protection.startswith('PBKDF2'): count = prot_params.get("iteration_count", 1000) key = PBKDF2(passphrase, salt, key_size, count) kdf_info = DerSequence([ DerObjectId(_OID_PBKDF2), # PBKDF2 DerSequence([DerOctetString(salt), DerInteger(count)]) ]) else: # It must be scrypt count = prot_params.get("iteration_count", 16384) scrypt_r = prot_params.get('block_size', 8) scrypt_p = prot_params.get('parallelization', 1) key = scrypt(passphrase, salt, key_size, count, scrypt_r, scrypt_p) kdf_info = DerSequence([ DerObjectId(_OID_SCRYPT), # scrypt DerSequence([ DerOctetString(salt), DerInteger(count), DerInteger(scrypt_r), DerInteger(scrypt_p) ]) ]) # Create cipher and use it cipher = module.new(key, cipher_mode, iv) encrypted_data = cipher.encrypt(pad(data, cipher.block_size)) enc_info = DerSequence([DerObjectId(enc_oid), DerOctetString(iv)]) # Result enc_private_key_info = DerSequence([ # encryptionAlgorithm DerSequence([ DerObjectId(_OID_PBES2), DerSequence([kdf_info, enc_info]), ]), DerOctetString(encrypted_data) ]) return enc_private_key_info.encode()
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. """ enc_private_key_info = DerSequence().decode(data, nr_elements=2) enc_algo = DerSequence().decode(enc_private_key_info[0]) encrypted_data = DerOctetString().decode( enc_private_key_info[1]).payload pbe_oid = DerObjectId().decode(enc_algo[0]).value if pbe_oid != _OID_PBES2: raise PbesError("Not a PBES2 object") pbes2_params = DerSequence().decode(enc_algo[1], nr_elements=2) ### Key Derivation Function selection kdf_info = DerSequence().decode(pbes2_params[0], nr_elements=2) kdf_oid = DerObjectId().decode(kdf_info[0]).value kdf_key_length = None # We only support PBKDF2 or scrypt if kdf_oid == _OID_PBKDF2: pbkdf2_params = DerSequence().decode(kdf_info[1], nr_elements=(2, 3, 4)) salt = DerOctetString().decode(pbkdf2_params[0]).payload iteration_count = pbkdf2_params[1] left = len(pbkdf2_params) - 2 idx = 2 if left > 0: try: kdf_key_length = pbkdf2_params[idx] - 0 left -= 1 idx += 1 except TypeError: pass # Default is HMAC-SHA1 pbkdf2_prf_oid = "1.2.840.113549.2.7" if left > 0: pbkdf2_prf_algo_id = DerSequence().decode(pbkdf2_params[idx]) pbkdf2_prf_oid = DerObjectId().decode( pbkdf2_prf_algo_id[0]).value elif kdf_oid == _OID_SCRYPT: scrypt_params = DerSequence().decode(kdf_info[1], nr_elements=(4, 5)) salt = DerOctetString().decode(scrypt_params[0]).payload iteration_count, scrypt_r, scrypt_p = [ scrypt_params[x] for x in (1, 2, 3) ] if len(scrypt_params) > 4: kdf_key_length = scrypt_params[4] else: kdf_key_length = None else: raise PbesError("Unsupported PBES2 KDF") ### Cipher selection enc_info = DerSequence().decode(pbes2_params[1]) enc_oid = DerObjectId().decode(enc_info[0]).value if enc_oid == _OID_DES_EDE3_CBC: # DES_EDE3_CBC ciphermod = DES3 key_size = 24 elif enc_oid == _OID_AES128_CBC: # AES128_CBC ciphermod = AES key_size = 16 elif enc_oid == _OID_AES192_CBC: # AES192_CBC ciphermod = AES key_size = 24 elif enc_oid == _OID_AES256_CBC: # AES256_CBC ciphermod = AES key_size = 32 else: raise PbesError("Unsupported PBES2 cipher") if kdf_key_length and kdf_key_length != key_size: raise PbesError("Mismatch between PBES2 KDF parameters" " and selected cipher") IV = DerOctetString().decode(enc_info[1]).payload # Create cipher if kdf_oid == _OID_PBKDF2: if pbkdf2_prf_oid == _OID_HMAC_SHA1: hmac_hash_module = SHA1 elif pbkdf2_prf_oid == _OID_HMAC_SHA224: hmac_hash_module = SHA224 elif pbkdf2_prf_oid == _OID_HMAC_SHA256: hmac_hash_module = SHA256 elif pbkdf2_prf_oid == _OID_HMAC_SHA384: hmac_hash_module = SHA384 elif pbkdf2_prf_oid == _OID_HMAC_SHA512: hmac_hash_module = SHA512 else: raise PbesError("Unsupported HMAC %s" % pbkdf2_prf_oid) key = PBKDF2(passphrase, salt, key_size, iteration_count, hmac_hash_module=hmac_hash_module) else: key = scrypt(passphrase, salt, key_size, iteration_count, scrypt_r, scrypt_p) cipher = ciphermod.new(key, ciphermod.MODE_CBC, IV) # Decrypt data pt = cipher.decrypt(encrypted_data) return unpad(pt, cipher.block_size)
def testDecode9(self): # Verify that decode returns itself der = DerSequence() self.assertEqual(der, der.decode(b('0\x06\x24\x02\xb6\x63\x12\x00')))
def _EMSA_PKCS1_V1_5_ENCODE(msg_hash, emLen, with_hash_parameters=True): """ Implement the ``EMSA-PKCS1-V1_5-ENCODE`` function, as defined in PKCS#1 v2.1 (RFC3447, 9.2). ``_EMSA-PKCS1-V1_5-ENCODE`` actually accepts the message ``M`` as input, and hash it internally. Here, we expect that the message has already been hashed instead. :Parameters: msg_hash : hash object The hash object that holds the digest of the message being signed. emLen : int The length the final encoding must have, in bytes. with_hash_parameters : bool If True (default), include NULL parameters for the hash algorithm in the ``digestAlgorithm`` SEQUENCE. :attention: the early standard (RFC2313) stated that ``DigestInfo`` had to be BER-encoded. This means that old signatures might have length tags in indefinite form, which is not supported in DER. Such encoding cannot be reproduced by this function. :Return: An ``emLen`` byte long string that encodes the hash. """ # First, build the ASN.1 DER object DigestInfo: # # DigestInfo ::= SEQUENCE { # digestAlgorithm AlgorithmIdentifier, # digest OCTET STRING # } # # where digestAlgorithm identifies the hash function and shall be an # algorithm ID with an OID in the set PKCS1-v1-5DigestAlgorithms. # # PKCS1-v1-5DigestAlgorithms ALGORITHM-IDENTIFIER ::= { # { OID id-md2 PARAMETERS NULL }| # { OID id-md5 PARAMETERS NULL }| # { OID id-sha1 PARAMETERS NULL }| # { OID id-sha256 PARAMETERS NULL }| # { OID id-sha384 PARAMETERS NULL }| # { OID id-sha512 PARAMETERS NULL } # } # # Appendix B.1 also says that for SHA-1/-2 algorithms, the parameters # should be omitted. They may be present, but when they are, they shall # have NULL value. digestAlgo = DerSequence([ DerObjectId(msg_hash.oid).encode() ]) if with_hash_parameters: digestAlgo.append(DerNull().encode()) digest = DerOctetString(msg_hash.digest()) digestInfo = DerSequence([ digestAlgo.encode(), digest.encode() ]).encode() # We need at least 11 bytes for the remaining data: 3 fixed bytes and # at least 8 bytes of padding). if emLen<len(digestInfo)+11: raise TypeError("Selected hash algorith has a too long digest (%d bytes)." % len(digest)) PS = bchr(0xFF) * (emLen - len(digestInfo) - 3) return b("\x00\x01") + PS + bchr(0x00) + digestInfo
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 | | | (called *N* or CPU/memory cost in scrypt). | | | | | | The default value for PBKDF2 is 1 000. | | | The default value for scrypt is 16 384. | +------------------+-----------------------------------------------+ | salt_size | Salt is used to thwart dictionary and rainbow | | | attacks on passwords. The default value is 8 | | | bytes. | +------------------+-----------------------------------------------+ | block_size | *(scrypt only)* Memory-cost (r). The default | | | value is 8. | +------------------+-----------------------------------------------+ | parallelization | *(scrypt only)* CPU-cost (p). The default | | | value is 1. | +------------------+-----------------------------------------------+ 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 ``Cryptodome.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 cipher_mode = DES3.MODE_CBC enc_oid = "1.2.840.113549.3.7" elif protection in ('PBKDF2WithHMAC-SHA1AndAES128-CBC', 'scryptAndAES128-CBC'): key_size = 16 module = AES cipher_mode = AES.MODE_CBC enc_oid = "2.16.840.1.101.3.4.1.2" elif protection in ('PBKDF2WithHMAC-SHA1AndAES192-CBC', 'scryptAndAES192-CBC'): key_size = 24 module = AES cipher_mode = AES.MODE_CBC enc_oid = "2.16.840.1.101.3.4.1.22" elif protection in ('PBKDF2WithHMAC-SHA1AndAES256-CBC', 'scryptAndAES256-CBC'): key_size = 32 module = AES cipher_mode = AES.MODE_CBC enc_oid = "2.16.840.1.101.3.4.1.42" else: raise ValueError("Unknown PBES2 mode") # Get random data iv = randfunc(module.block_size) salt = randfunc(prot_params.get("salt_size", 8)) # Derive key from password if protection.startswith('PBKDF2'): count = prot_params.get("iteration_count", 1000) key = PBKDF2(passphrase, salt, key_size, count) kdf_info = DerSequence([ DerObjectId("1.2.840.113549.1.5.12"), # PBKDF2 DerSequence([ DerOctetString(salt), DerInteger(count) ]) ]) else: # It must be scrypt count = prot_params.get("iteration_count", 16384) scrypt_r = prot_params.get('block_size', 8) scrypt_p = prot_params.get('parallelization', 1) key = scrypt(passphrase, salt, key_size, count, scrypt_r, scrypt_p) kdf_info = DerSequence([ DerObjectId("1.3.6.1.4.1.11591.4.11"), # scrypt DerSequence([ DerOctetString(salt), DerInteger(count), DerInteger(scrypt_r), DerInteger(scrypt_p) ]) ]) # Create cipher and use it cipher = module.new(key, cipher_mode, iv) encrypted_data = cipher.encrypt(pad(data, cipher.block_size)) enc_info = DerSequence([ DerObjectId(enc_oid), DerOctetString(iv) ]) # Result enc_private_key_info = DerSequence([ # encryptionAlgorithm DerSequence([ DerObjectId("1.2.840.113549.1.5.13"), # PBES2 DerSequence([ kdf_info, enc_info ]), ]), DerOctetString(encrypted_data) ]) return enc_private_key_info.encode()
def testEncode1(self): # Empty sequence der = DerSequence() self.assertEquals(der.encode(), b('0\x00')) self.failIf(der.hasOnlyInts()) # One single-byte integer (zero) der.append(0) self.assertEquals(der.encode(), b('0\x03\x02\x01\x00')) self.assertEquals(der.hasInts(),1) self.assertEquals(der.hasInts(False),1) self.failUnless(der.hasOnlyInts()) self.failUnless(der.hasOnlyInts(False)) # Invariant self.assertEquals(der.encode(), b('0\x03\x02\x01\x00'))
def testInit1(self): der = DerSequence([1, DerInteger(2), b('0\x00')]) self.assertEquals(der.encode(), b('0\x08\x02\x01\x01\x02\x01\x020\x00'))
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 | | | (called *N* or CPU/memory cost in scrypt). | | | | | | The default value for PBKDF2 is 1 000. | | | The default value for scrypt is 16 384. | +------------------+-----------------------------------------------+ | salt_size | Salt is used to thwart dictionary and rainbow | | | attacks on passwords. The default value is 8 | | | bytes. | +------------------+-----------------------------------------------+ | block_size | *(scrypt only)* Memory-cost (r). The default | | | value is 8. | +------------------+-----------------------------------------------+ | parallelization | *(scrypt only)* CPU-cost (p). The default | | | value is 1. | +------------------+-----------------------------------------------+ 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 ``Cryptodome.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 = DerSequence([ 0, DerSequence([ DerObjectId(key_oid), key_params ]), DerOctetString(private_key) ]) pk_info_der = pk_info.encode() if passphrase is None: return pk_info_der if not passphrase: raise ValueError("Empty passphrase") # 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 testEncode6(self): # Two positive integers der = DerSequence() der.append(0x180L) der.append(0xFFL) self.assertEquals(der.encode(), b('0\x08\x02\x02\x01\x80\x02\x02\x00\xff')) self.failUnless(der.hasOnlyInts()) self.failUnless(der.hasOnlyInts(False)) # Two mixed integers der = DerSequence() der.append(2) der.append(-2) self.assertEquals(der.encode(), b('0\x06\x02\x01\x02\x02\x01\xFE')) self.assertEquals(der.hasInts(), 1) self.assertEquals(der.hasInts(False), 2) self.failIf(der.hasOnlyInts()) self.failUnless(der.hasOnlyInts(False)) # der.append(0x01) der[1:] = [9,8] self.assertEquals(len(der),3) self.assertEqual(der[1:],[9,8]) self.assertEqual(der[1:-1],[9]) self.assertEquals(der.encode(), b('0\x09\x02\x01\x02\x02\x01\x09\x02\x01\x08'))