def from_bytes(cls, data, network=network.default, backend=default_backend()): """Create a public key from its raw binary encoding (in SEC1 format). For more info on this format, see: http://www.secg.org/sec1-v2.pdf, section 2.3.4 """ data = bytearray(data) # A public key is a point (x, y) in the elliptic curve, and each # coordinate is represented by a unsigned integer of key_size bytes key_size = tools.elliptic_curve_key_size(network.curve) # The first byte determines whether the key is compressed try: prefix = data.pop(0) except IndexError: raise InvalidEncoding('Invalid key length (buffer is empty)') # If the key is compressed-encoded, only the x coordinate is present compressed = True if len(data) == key_size else False if not compressed and len(data) != 2 * key_size: raise InvalidEncoding('Invalid key length') # The first key_size bytes after the prefix are the x coordinate x = encoding.b2i_bigendian(bytes(data[:key_size])) if compressed: # If the key is compressed, the y coordinate should be computed if prefix == SEC1_MAGIC_COMPRESSED_0: y_parity = 0 elif prefix == SEC1_MAGIC_COMPRESSED_1: y_parity = 1 else: raise InvalidEncoding('Invalid prefix for compressed key') y = tools.ec_public_y_from_x_and_curve(x, y_parity, network.curve) if y is None: raise InvalidPoint() else: # If the key isn't compressed, the last key_size bytes are the y # coordinate if prefix != SEC1_MAGIC_NOT_COMPRESSED: raise InvalidEncoding('Invalid prefix for non-compressed key') y = encoding.b2i_bigendian(bytes(data[key_size:])) return cls.from_point(x, y, network, compressed, backend)
def test_bitcoind_valid_wifs(self, valid_wifs): for wif, secret_hex, attrs in valid_wifs: secret = encoding.b2i_bigendian(encoding.a2b_hex(secret_hex)) network_ = network.testnet if attrs['isTestnet'] else network.livenet compressed = attrs['isCompressed'] k = PrivateKey.from_wif(wif) assert k.key.private_numbers().private_value == secret assert k.network is network_ assert k.compressed == compressed
def from_bytes(cls, data, network=network.default, compressed=True, backend=default_backend()): """Create a private key from its raw binary encoding (in SEC1 format). The input buffer should be a zero-padded big endian unsigned integer. For more info on this format, see: http://www.secg.org/sec1-v2.pdf, section 2.3.6 """ if len(data) != tools.elliptic_curve_key_size(network.curve): raise InvalidEncoding('Invalid key length') exponent = encoding.b2i_bigendian(data) try: return cls.from_secret_exponent(exponent, network, compressed, backend) except InvalidExponent as e: raise InvalidEncoding(e.message)