For context
我正在使用azurerm_key_vault_key
terraform资源创建一个secp256k1密钥.我可以将这个键的X和Y坐标输出为如下所示的字符串(看起来是一个Base64 URL编码的,但我找不到任何明确定义这一点的文档)
"x": "ARriqkpHlC1Ia1Tk86EM_bqH_9a88Oh2zMYF3fUUGJw"
"y": "wTYd3CEiwTk1n-lFPdpZ51P4Z0EzlVNXLvJMY-k55pQ"
The problem
我需要将其转换为十六进制格式的公钥.我已经在Python中try 了以下内容:
import ecdsa
import binascii
import base64
def base64url_to_bytes(base64url_string):
padding = '=' * (4 - (len(base64url_string) % 4))
base64_string = base64url_string.replace('-', '+').replace('_', '/') + padding
return base64.b64decode(base64_string)
def compress_point(x, y):
"""Compresses the point (x, y) to a 33-byte compressed public key."""
prefix = "02" if y % 2 == 0 else "03"
return prefix + x
def decompress_point(compressed_key):
"""Decompresses the compressed public key to (x, y)."""
prefix = compressed_key[:2]
x = compressed_key[2:]
y = ecdsa.ellipticcurve.Point(ecdsa.SECP256k1.curve, int(x, 16), int(prefix, 16))
return x, y.y()
x_value = base64url_to_bytes("ARriqkpHlC1Ia1Tk86EM_bqH_9a88Oh2zMYF3fUUGJw")
y_value = base64url_to_bytes("wTYd3CEiwTk1n-lFPdpZ51P4Z0EzlVNXLvJMY-k55pQ")
x, y = int.from_bytes(x_value, byteorder='big'), int.from_bytes(y_value, byteorder='big')
# Compress the point
compressed_key = compress_point(format(x, 'x'), y)
print(compressed_key)
decompressed_x, decompressed_y = decompress_point(compressed_key)
print("Decompressed X:", decompressed_x)
print("Decompressed Y:", decompressed_y)
它会压缩,但decompress_point
会抛出一个断言错误,这表明我在压缩或解压缩步骤中做错了什么.
以下是上述脚本的完整输出:
0211ae2aa4a47942d486b54e4f3a10cfdba87ffd6bcf0e876ccc605ddf514189c
Traceback (most recent call last):
File "get_public_key3.py", line 32, in <module>
decompressed_x, decompressed_y = decompress_point(compressed_key)
File "get_public_key3.py", line 19, in decompress_point
y = ecdsa.ellipticcurve.Point(ecdsa.SECP256k1.curve, int(x, 16), int(prefix, 16))
File "/home/ubuntu/.local/lib/python3.8/site-packages/ecdsa/ellipticcurve.py", line 1090, in __init__
assert self.__curve.contains_point(x, y)
AssertionError
我对这里使用的包一点都不熟悉,上面的代码大多是从我可以在网上找到的各种零碎东西中拼凑而成的.
有人能就如何做到这一点给我一个明确的答案吗?