def from_pem(cls, ledger, pem) -> 'PrivateKey': der = pem_to_der(pem.encode()) try: key_int = ECPrivateKey.load(der).native['private_key'] except ValueError: key_int = PrivateKeyInfo.load(der).native['private_key']['private_key'] private_key = cPrivateKey.from_int(key_int) return cls(ledger, private_key, bytes((0,)*32), 0, 0)
def pk_to_c_array(name, pk_der): # parse der format pk = ECPrivateKey.load(pk_der) # extract private key pk_native = pk['private_key'].native # translate to hex string pk_hex = format(pk_native, '064x') # split by pairs of characters hex_bytes = ["0x" + pk_hex[i:i + 2] for i in range(0, len(pk_hex), 2)] # make string C array declaration return "const uint8_t " + name + "[32] = {" + ", ".join(hex_bytes) + "};"
def decode_ec_private_key(der): """ Decode a DER-encoded EC private key as stored by OpenSSL into a dictionary of attributes able to be passed to :meth:`pkcs11.Session.create_object`. :param bytes der: DER-encoded key :rtype: dict(Attribute,*) """ asn1 = ECPrivateKey.load(der) return { Attribute.KEY_TYPE: KeyType.EC, Attribute.CLASS: ObjectClass.PRIVATE_KEY, Attribute.EC_PARAMS: asn1['parameters'].dump(), Attribute.VALUE: asn1['private_key'], }
else: offset = fsize - 0x800 # load and parse private key if not args.key: print("Key not modified") else: key_offset = offset print("Injecting key from %s at 0x%0X" % (args.key, key_offset)) if args.key == "stdin": stdin = sys.stdin.buffer if hasattr(sys.stdin, "buffer") else sys.stdin der = stdin.read() else: with open(args.key, "rb") as f: der = f.read() key = ECPrivateKey.load(der) # convert key into raw bytes and calculate it's sha256 key_bytes = bytearray.fromhex(format(key["private_key"].native, '064x')) key_hash = hashlib.sha256(key_bytes).digest() # pad key to 1KiB key_blob = (key_bytes + key_hash).ljust(1024, b"\x00") assert len(key_blob) == 1024 with open(args.bin, 'r+b') as f: f.seek(key_offset) f.write(key_blob) if not args.ctr: print("Counter not modified") else: