Python:根据以原始字节表示的私钥和公钥创建ECC密钥

问题描述 投票:2回答:1

我有以下ECC私钥和公钥对:

私钥:0x63bd3b01c5ce749d87f5f7481232a93540acdb0f7b5c014ecd9cd32b041d6f33

公钥:0x04017655e42a892cc71bccedcb1cd421d03530e1d7edb52cef143c5562c4c6f0129fa5a37738013e64a1ff0e6cb7068815a13000eb162cb7a0214dfcf3c8fa101c

曲线:SECP256R1

我想在Python中加载这些密钥以执行签名操作。您能否建议可能的步骤?

((如有必要,我很愿意使用“ openssl ec”工具。)

python cryptography ecdsa
1个回答
0
投票

您可以使用ECC.construct(**kwargs)调用从各个整数构造键。

我在下面显示了如何对未压缩的点以十六进制,然后是字节而不是数字进行此操作。未压缩的点本身就是非数字

私钥向量(通常表示为s或d,我更喜欢用s表示秘密)is一个数字,但通常也会使用字节来传输(如果每次传输)。

from Crypto.PublicKey import ECC

# --- ECC public key from "flat" uncompressed EC point representation ---

# lets assume that the input is binary, rather than an integer

uncompressedPointHex = "04017655e42a892cc71bccedcb1cd421d03530e1d7edb52cef143c5562c4c6f0129fa5a37738013e64a1ff0e6cb7068815a13000eb162cb7a0214dfcf3c8fa101c"
uncompressedPoint = bytes.fromhex(uncompressedPointHex)

# check if the point is uncompressed rather than compressed
# for compressed points ask a separate *question*

off = 0
if (uncompressedPoint[off] != 0x04):
    raise Exception("Not an uncompressed point")
off += 1

sizeBytes = (len(uncompressedPoint) - 1) // 2

xBin = uncompressedPoint[off:off + sizeBytes]
x = int.from_bytes(xBin, 'big', signed=False)
off += sizeBytes

yBin = uncompressedPoint[off:off + sizeBytes]
y = int.from_bytes(yBin, 'big', signed=False)
off += sizeBytes

# if you already have integers, this is all you need

publicKey = ECC.construct(curve="secp256r1", point_x=x, point_y=y)

# obviously just for testing the result

print(publicKey)

# --- ECC private key from "flat" uncompressed EC point representation ---

# lets assume that the input is binary, rather than an integer

sHex = "63bd3b01c5ce749d87f5f7481232a93540acdb0f7b5c014ecd9cd32b041d6f33"
sBin = bytes.fromhex(sHex)

# very straightforward conversion, as S is just there

s = int.from_bytes(sBin, 'big', signed=False)

# if you already have integers, this is all you need

privateKey = ECC.construct(curve="secp256r1", d=s)

# obviously just for testing the result

print(privateKey)

[请注意,我使用过Python 3,也许某些Python开发人员能够将其转换为Python 2,并将结果包含在此答案中。想法/呼吁毕竟应该相似。我看到在PyCryptoDome的最新版本中有一些新方法和ECPoint,这可能是个好主意。

© www.soinside.com 2019 - 2024. All rights reserved.