def _importKeyDER(self, externKey): der = DerSequence() der.decode(externKey, True) 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[0] # Remove version return self.construct(der[:]) if len(der)==2: # The DER object is a SEQUENCE with two elements: # a SubjectPublicKeyInfo SEQUENCE and an opaque BIT STRING. # # The first element is always the same: # 0x30 0x0D SEQUENCE, 12 bytes of payload # 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 # # The second encapsulates the actual ASN.1 RSAPublicKey element. if der[0]==b('\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01\x05\x00'): bitmap = DerObject() bitmap.decode(der[1], True) if bitmap.typeTag==b('\x03')[0] and bitmap.payload[0]==b('\x00')[0]: der.decode(bitmap.payload[1:], True) if len(der)==2 and der.hasOnlyInts(): return self.construct(der[:]) raise ValueError("RSA key format is not supported")
def read_RSA_key(key_data): """ Utility function for reading an RSA key half from encoded data :param key_data: PEM data containing raw key or X.509 certificate :return: An RSA key object """ try: # Handle data that is just a raw key key = RSA.importKey(key_data) except ValueError: # The RSA.importKey function cannot read X.509 certificates directly # (depending on the version of the Crypto library). Instead, we # may need to extract the key from the certificate before building # the key object # # We need to strip the BEGIN and END lines from PEM first x509lines = key_data.replace(' ', '').split() x509text = ''.join(x509lines[1:-1]) x509data = DerSequence() x509data.decode(a2b_base64(x509text)) # X.509 contains a few parts. The first part (index 0) is the # certificate itself, (TBS or "to be signed" cert) and the 7th field # of that cert is subjectPublicKeyInfo, which can be imported. # RFC3280 tbsCert = DerSequence() tbsCert.decode(x509data[0]) # Initialize RSA key from the subjectPublicKeyInfo field key = RSA.importKey(tbsCert[6]) return key
def get_public_key_from_pem(self, pem_cert): der = ssl.PEM_cert_to_DER_cert(pem_cert) cert = DerSequence() cert.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) return tbsCertificate[6]
def verify_signature_rs256(token, cert): """ Verifies an RS256 token using a public-key PEM certificate. """ from binascii import a2b_base64 from Crypto.Hash import SHA256 from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Util.asn1 import DerSequence # Split token into message and signature sections. message, signature = token.rsplit('.', 1) # Convert from PEM to DER. pem = cert 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. rsakey = RSA.importKey(subjectPublicKeyInfo) # Verify signature signer = PKCS1_v1_5.new(rsakey) digest = SHA256.new(message) # Assumes the data is base64 encoded to begin with return signer.verify(digest, base64url_decode(signature)) is True
def testDecode4(self): # One very long integer der = DerSequence() der.decode('0\x82\x01\x05' '\x02\x82\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' '\x00\x00\x00\x00\x00\x00\x00\x00\x00') self.assertEquals(len(der),1) self.assertEquals(der[0],2**2048)
def read_pubkey_from_der(blob): cert = DerSequence() cert.decode(blob) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] return RSA.importKey(subjectPublicKeyInfo)
def pem_to_der(pem): """Convert an ascii-armored PEM certificate to a DER encoded certificate See http://stackoverflow.com/a/12921889 for details. Python ``ssl`` module has it own method for this, but it shouldn't work properly and this method is required. :arg str pem: The PEM certificate as string. """ # TODO(rafaduran): report and/or fix Python ssl method. # Importing here since Crypto module is only require for the SSL security # provider plugin. from Crypto.Util.asn1 import DerSequence lines = pem.replace(" ", '').split() der = binascii.a2b_base64(''.join(lines[1:-1])) # Extract subject_public_key_info 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] # this can be passed to RSA.importKey() return subject_public_key_info
def csr_pem_to_der(csr_cert): certificate_key_der = DerSequence() certificate_key_der.decode( OpenSSL.crypto.dump_certificate_request(OpenSSL.crypto.FILETYPE_ASN1, csr_cert)) certificate_der = certificate_key_der.encode() return certificate_der
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],0x180) self.assertEquals(der[1],0xFF)
def from_string(key_pem, is_x509_cert): """Construct a Verified instance from a string. Args: key_pem: string, public key in PEM format. is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is expected to be an RSA key in PEM format. Returns: Verifier instance. Raises: NotImplementedError if is_x509_cert is true. """ if is_x509_cert: from Crypto.Util.asn1 import DerSequence from Crypto.PublicKey import RSA from binascii import a2b_base64 # Convert from PEM to DER lines = key_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] pubkey = RSA.importKey(subjectPublicKeyInfo) else: pubkey = RSA.importKey(key_pem) return PyCryptoVerifier(pubkey)
def privKeyXML(pemPrivateKeyFile): with open(pemPrivateKeyFile, 'rb') as pkFile: pemPrivKey = pkFile.read() # print(pemPrivKey) lines = pemPrivKey.replace(" ".encode('utf-8'), ''.encode('utf-8')).split() # print(lines) lines_str = [x.decode("utf-8") for x in lines] keyDer = DerSequence() keyDer.decode(a2b_base64(''.join(lines_str[1:-1]))) doc = minidom.Document() root = doc.createElement('RSAKeyValue') doc.appendChild(root) xml_tag_list = [ 'Modulus', 'Exponent', 'D', 'P', 'Q', 'DP', 'DQ', 'InverseQ' ] for idx, tag in enumerate(xml_tag_list, start=1): elem = doc.createElement(tag) textNode = doc.createTextNode( standard_b64encode(number.long_to_bytes( keyDer[idx])).decode("utf-8")) elem.appendChild(textNode) root.appendChild(elem) fileName = basename(pemPrivateKeyFile) with open(fileName + '.xml', 'w') as pkFile: pkFile.write(doc.toprettyxml()) return
def testDecode8(self): # Only 2 other types der = DerSequence() der.decode(b('0\x06\x24\x02\xb6\x63\x12\x00')) self.assertEqual(len(der), 2) self.assertEqual(der[0], b('\x24\x02\xb6\x63')) self.assertEqual(der[1], b('\x12\x00'))
def get_spki(self): """Get the Subject PublicKey info, DER encoded.""" der = DerSequence() der.decode(self.DER) cert = DerSequence() cert.decode(der[0]) return cert[6]
def verifier_from_pem_stack(sudi_certstack_raw): '''Generate a verifier object from the supplied certificate PEM stack where the last certificate in the stack should be the SUDI public certificate. - sudi_certstack_raw (str): The PEM stack returned by the\n``show platform sudi certificate``\nIOS command ''' logging.debug("Entering %s with parameters %s", inspect.currentframe().f_code.co_name, locals()) # convert certificate from PEM format to DER format for processing by # pycrypto methods sudi_pubcert_der = _pem_to_der(extract_sudi_pubcert(sudi_certstack_raw)) # get the public RSA key from the certificate cert = DerSequence() cert.decode(sudi_pubcert_der) tbs_cert = DerSequence() tbs_cert.decode(cert[0]) subj_pub_key_info = tbs_cert[6] sudi_rsa_pubkey = RSA.importKey(subj_pub_key_info) # generate a signature verification object from the RSA public key sig_verifier = PKCS1_v1_5.new(sudi_rsa_pubkey) return sig_verifier
def testDecode8(self): # Only 2 other types der = DerSequence() der.decode('0\x06\x24\x02\xb6\x63\x12\x00') self.assertEquals(len(der),2) self.assertEquals(der[0],'\x24\x02\xb6\x63') self.assertEquals(der[1],'\x12\x00')
def testDecode6(self): # Two integers der = DerSequence() der.decode('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],2**2048)
def get_service_id(private_key_file=None, cert=None): ''' service_id is the first half of the sha1 of the rsa public key encoded in base32 ''' if private_key_file: with open(private_key_file, 'rb') as fd: private_key = fd.read() public_key = RSA.importKey(private_key).publickey().exportKey('DER')[22:] # compute sha1 of public key and encode first half in base32 service_id = base64.b32encode(hashlib.sha1(public_key).digest()[:10]).lower().decode() ''' # compute public key from priate key and export in DER format # ignoring the SPKI header(22 bytes) key = load_privatekey(FILETYPE_PEM, private_key) cert = X509() cert.set_pubkey(key) public_key = dump_privatekey(FILETYPE_ASN1, cert.get_pubkey())[22:] # compute sha1 of public key and encode first half in base32 service_id = base64.b32encode(hashlib.sha1(public_key).digest()[:10]).lower().decode() ''' elif cert: # compute sha1 of public key and encode first half in base32 key = load_certificate(FILETYPE_ASN1, cert).get_pubkey() pub_der = DerSequence() pub_der.decode(dump_privatekey(FILETYPE_ASN1, key)) public_key = RSA.construct((pub_der._seq[1], pub_der._seq[2])).exportKey('DER')[22:] service_id = base64.b32encode(hashlib.sha1(public_key).digest()[:10]).lower().decode() return service_id
def get_spki_from_cert(cert): cert_dec = DerSequence() cert_dec.decode(cert) tbsCertificate = DerSequence() tbsCertificate.decode(cert_dec[0]) spki = tbsCertificate[6] return spki
def generate_spoofed_key(pubkey): x = int(pubkey[0:96], 16) y = int(pubkey[96:], 16) # Generate rogue generator # Generate degenerate case rogue generator privkey = '\x01' rogueG = unhexlify(b"04" + hex2(x).encode() + hex2(y).encode()) # Generate the file with explicit parameters der = get_der(ec_key_template) # Replace private key octet_der = DerOctetString(privkey) der[1] = octet_der.encode() # Replace public key der[3] = b"\xa1\x64\x03b\x00" + unhexlify(b"04" + pubkey) # Replace the generator seq_der = DerSequence() seq_der.decode(der[2][4:]) s = seq_der._seq octet_der = DerOctetString(rogueG) s[3] = octet_der.encode() seq_der = DerSequence(s) der[2] = der[2][:4] + seq_der.encode() seq_der = DerSequence(der) return PEMHelper.PEMEncode(seq_der.encode(), 'EC PRIVATE KEY')
def parseCertificate(payload, keys): certlen = struct.unpack(">L","\x00"+payload[7:10])[0] servercert = payload[10:10+certlen] cert = DerSequence() cert.decode(servercert) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) keys.server_pubkey = RSA.importKey(tbsCertificate[6])
def importCert(pem): lines = pem.replace(" ", '').split() der = a2b_base64(''.join(lines[1:-1])) cert = DerSequence() cert.decode(der) tbscert = DerSequence() tbscert.decode(cert[0]) return RSA.importKey(tbscert[6])
def parseCertificate(payload, keys): certlen = struct.unpack(">L", "\x00" + payload[7:10])[0] servercert = payload[10:10 + certlen] cert = DerSequence() cert.decode(servercert) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) keys.server_pubkey = RSA.importKey(tbsCertificate[6])
def testDecode7(self): # One integer and 2 other types der = DerSequence() der.decode('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],'\x24\x02\xb6\x63') self.assertEquals(der[2],'\x12\x00')
def _get_pubkey(self, pem): der = PEM_cert_to_DER_cert(pem) cert = DerSequence() cert.decode(der) tbs_cert = DerSequence() tbs_cert.decode(cert[0]) # TBSCertiFicate pubkey_info = tbs_cert[6] # SubjectPublicKeyInfo return RSA.importKey(pubkey_info)
def cert_to_public_rsa_key(pem): DER = ssl.PEM_cert_to_DER_cert(pem) cert = DerSequence() cert.decode(DER) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] rsa_key = RSA.importKey(subjectPublicKeyInfo) return rsa_key
def get_modulus_and_exponent(x509): if x509.get_pubkey().type() == TYPE_RSA: pub_der = DerSequence() pub_der.decode(dump_privatekey(FILETYPE_ASN1, x509.get_pubkey())) modulus = "%s:%s" % (format_split_int( pub_der._seq[0]), format_split_int(pub_der._seq[1])) exponent = pub_der._seq[2] return [modulus, exponent] return ''
def _process_cert(self, key): pemLines = key.replace(b' ', b'').split() certDer = base64url_decode(b''.join(pemLines[1:-1])) certSeq = DerSequence() certSeq.decode(certDer) tbsSeq = DerSequence() tbsSeq.decode(certSeq[0]) self.prepared_key = RSA.importKey(tbsSeq[6]) return
def pubkey_from_dercert(der): cert = DerSequence() cert.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] # Initialize RSA key rsa_key = RSA.importKey(subjectPublicKeyInfo) return rsa_key
def get_signature_bytes(x509): der = DerSequence() der.decode(dump_certificate(FILETYPE_ASN1, x509)) der_tbs = der[0] der_algo = der[1] der_sig = der[2] der_sig_in = DerObject() der_sig_in.decode(der_sig) sig = der_sig_in.payload[1:] #skip leading zeros return sig.encode('hex')
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 get_service_id(key): ''' service_id is the first half of the sha1 of the rsa public key encoded in base32 ''' # compute sha1 of public key and encode first half in base32 pub_der = DerSequence() pub_der.decode(dump_privatekey(FILETYPE_ASN1, key)) public_key = RSA.construct((pub_der._seq[1], pub_der._seq[2])).exportKey('DER')[22:] service_id = base64.b32encode(hashlib.sha1(public_key).digest()[:10]).lower().decode() return service_id
def x509_extract_pubkey_from_der(der_certificate): # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280) cert = DerSequence() cert.decode(der_certificate) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] # Initialize RSA key return RSA.importKey(subjectPublicKeyInfo)
def testDecode8(self): # Only 2 other types der = DerSequence() der.decode(b('0\x06\x24\x02\xb6\x63\x12\x00')) self.assertEqual(len(der),2) self.assertEqual(der[0],b('\x24\x02\xb6\x63')) self.assertEqual(der[1],b('\x12\x00')) self.assertEqual(der.hasInts(), 0) self.assertEqual(der.hasInts(False), 0) self.assertFalse(der.hasOnlyInts()) self.assertFalse(der.hasOnlyInts(False))
def convert_pem_to_rsa_string(pem): # Convert from PEM to DER 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]) return tbsCertificate[6]
def public_key(self): lines = self._certificate.replace(' ', '').split() der = a2b_base64(''.join(lines[1:-1])) cert = DerSequence() cert.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] return subjectPublicKeyInfo
def import_pubkey_from_x509(pem): b64der = ''.join(pem.split('\n')[1:][:-2]) cert = DerSequence() cert.decode(b64decode(b64der)) tbs_certificate = DerSequence() tbs_certificate.decode(cert[0]) subject_public_key_info = tbs_certificate[6] return RSA.importKey(subject_public_key_info)
def get_public_key_from_private_key(pkey): try: private_key_der = DerSequence() private_key_der.decode( OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_ASN1, pkey)) modulus = int2hex(private_key_der[1]) exp = int2hex(private_key_der[2]) return modulus, exp except TypeError as e: log.error(e) return None
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 `Crypto.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). signature : byte string The signature that needs to be validated. :Raise ValueError: If the signature is not authentic. """ if not self._deterministic: if self._n > msg_hash.digest_size * 8: raise ValueError("Hash is not long enough") if not msg_hash.name.lower().startswith("sha"): raise ValueError("Hash %s does not belong to SHS" % msg_hash.name) if self._encoding == 'binary': if len(signature) != (2 * self._n): raise ValueError("The signature is not authentic") r_prime, s_prime = [ bytes_to_long(x) for x in (signature[:self._n], signature[self._n:]) ] else: try: der_seq = DerSequence() der_seq.decode(signature) except (ValueError, IndexError): raise ValueError("The signature is not authentic") if len(der_seq) != 2 or not der_seq.hasOnlyInts(): raise ValueError("The signature is not authentic") r_prime, s_prime = der_seq[0], der_seq[1] if not (0 < r_prime < self._key.q) or not (0 < s_prime < self._key.q): raise ValueError("The signature is not authentic") z = bytes_to_long(msg_hash.digest()[:self._n]) result = self._key._verify(z, (r_prime, s_prime)) if not result: raise ValueError("The signature is not authentic") # Make PyCrypto code to fail return False
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_service_id(key): ''' service_id is the first half of the sha1 of the rsa public key encoded in base32 ''' # compute sha1 of public key and encode first half in base32 pub_der = DerSequence() pub_der.decode(dump_privatekey(FILETYPE_ASN1, key)) public_key = RSA.construct( (pub_der._seq[1], pub_der._seq[2])).exportKey('DER')[22:] service_id = base64.b32encode( hashlib.sha1(public_key).digest()[:10]).lower().decode() return service_id
def get_pubkey(pem): """ Extracts public key from x08 pem. """ der = ssl.PEM_cert_to_DER_cert(pem) # Extract subjectPublicKeyInfo field from X.509 certificate (see RFC3280) cert = DerSequence() cert.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] return subjectPublicKeyInfo
def pubkey_from_x509(cert): pem = open(cert).read() lines = pem.replace(" ", '').split() der = a2b_base64(''.join(lines[1:-1])) cert = DerSequence() cert.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] rsa_key = RSA.importKey(subjectPublicKeyInfo) return rsa_key
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 `Crypto.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). signature : byte string The signature that needs to be validated. :Raise ValueError: If the signature is not authentic. """ if not self._deterministic: if self._n > msg_hash.digest_size * 8: raise ValueError("Hash is not long enough") if not hash_is_shs(msg_hash): raise ValueError("Hash does not belong to SHS") if self._encoding == 'binary': if len(signature) != (2 * self._n): raise ValueError("The signature is not authentic") r_prime, s_prime = [bytes_to_long(x) for x in (signature[:self._n], signature[self._n:])] else: try: der_seq = DerSequence() der_seq.decode(signature) except (ValueError, IndexError): raise ValueError("The signature is not authentic") if len(der_seq) != 2 or not der_seq.hasOnlyInts(): raise ValueError("The signature is not authentic") r_prime, s_prime = der_seq[0], der_seq[1] if not (0 < r_prime < self._key.q) or not (0 < s_prime < self._key.q): raise ValueError("The signature is not authentic") z = bytes_to_long(msg_hash.digest()[:self._n]) result = self._key._verify(z, (r_prime, s_prime)) if not result: raise ValueError("The signature is not authentic") # Make PyCrypto code to fail return False
class Certificate(object): def __init__(self, path=''): with open(path, 'rb') as f: pem = f.read() lines = pem.replace(b' ', b'').split() der = a2b_base64(b''.join(lines[1:-1])) self.cert = DerSequence() self.cert.decode(der) def public_key(self): subject = DerSequence() subject.decode(self.cert[0]) return RSA.import_key(subject[6])
def HPKP(cert): der = crypto.dump_certificate(crypto.FILETYPE_ASN1, cert) cert = DerSequence() cert.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert[0]) subjectPublicKeyInfo = tbsCertificate[6] fp = fingerprint(subjectPublicKeyInfo, hashlib.sha1) print('HPKP sha1 fp %s' % fp) print('HPKP sha1 pin %s' % fingerprint_to_pin(fp)) fp = fingerprint(subjectPublicKeyInfo, hashlib.sha256) print('HPKP sha256 fp %s' % fp) print('HPKP sha256 pin %s' % fingerprint_to_pin(fp))
def get_rsa_key(cert_data): pem = cert_data 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] return RSA.importKey(subjectPublicKeyInfo)
def _cert_to_key(self, cert): # Convert from PEM to DER lines = cert.replace(" ",'').split() der = base64.b64decode(''.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 return RSA.importKey(subjectPublicKeyInfo)
def extract_rsa_key_from_x509_cert(pem): # Convert from PEM to DER der = ssl.PEM_cert_to_DER_cert(pem) # 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 rsa_key = RSA.importKey(subjectPublicKeyInfo) return rsa_key
def subject_public_key_info(self, deep=0): """ This method extract the SubjectPublicKeyInfo from the certificate and return it as der """ try: der = self._certs_der[deep] cert_dec = DerSequence() cert_dec.decode(der) tbsCertificate = DerSequence() tbsCertificate.decode(cert_dec[0]) spki = tbsCertificate[6] return spki except: raise Exception("subject_public_key_info issue")
def _get_from_x509(self, cert): """Extract public key from x.509 certificate. For details see https://github.com/google/oauth2client/blob/master/oauth2client/_pycrypto_crypt.py -> PyCryptoVerifier.from_string or http://stackoverflow.com/questions/12911373/how-do-i-use-a-x509-certificate-with-pycrypto """ cs = DerSequence() cs.decode(cert) ts = DerSequence() ts.decode(cert[0]) return ts[6]