def _get_private_key(private_key_pkcs8_text): """Get an RSA private key object from a pkcs8 representation.""" der = rsa.pem.load_pem(private_key_pkcs8_text, 'PRIVATE KEY') asn1_private_key, _ = decoder.decode(der, asn1Spec=PrivateKeyInfo()) return rsa.PrivateKey.load_pkcs1( asn1_private_key.getComponentByName('privateKey').asOctets(), format='DER')
def _pkcs8_extract_pubkey(der_form): try: pkcs8 = der_decoder.decode(der_form, asn1Spec=PrivateKeyInfo())[0] pkcs8_key_algo = der_decoder.decode(pkcs8['privateKeyAlgorithm']['parameters'])[0] except PyAsn1Error as asn1_err: return None, None pubkey, key_algo = _x9_62_extract_pubkey(pkcs8['privateKey']) if key_algo is None: # Try to fall back to a PKCS8-extracted value: key_algo = pkcs8_key_algo return pubkey, key_algo
_PKCS12_ERROR = r"""\ PKCS12 format is not supported by the RSA library. Either install PyOpenSSL, or please convert .p12 format to .pem format: $ cat key.p12 | \ > openssl pkcs12 -nodes -nocerts -passin pass:notasecret | \ > openssl rsa > key.pem """ _POW2 = (128, 64, 32, 16, 8, 4, 2, 1) _PKCS1_MARKER = ('-----BEGIN RSA PRIVATE KEY-----', '-----END RSA PRIVATE KEY-----') _PKCS8_MARKER = ('-----BEGIN PRIVATE KEY-----', '-----END PRIVATE KEY-----') _PKCS8_SPEC = PrivateKeyInfo() def _bit_list_to_bytes(bit_list): """Converts an iterable of 1's and 0's to bytes. Combines the list 8 at a time, treating each group of 8 bits as a single byte. """ num_bits = len(bit_list) byte_vals = bytearray() for start in six.moves.xrange(0, num_bits, 8): curr_bits = bit_list[start:start + 8] char_val = sum(val * digit for val, digit in zip(_POW2, curr_bits)) byte_vals.append(char_val)