将secp256k1椭圆曲线x,y坐标字符串压缩成十六进制公钥

问题描述 投票:0回答:0

上下文

我正在使用

azurerm_key_vault_key
terraform 资源来创建 secp256k1 密钥。我可以将此键的 X 和 Y 坐标输出为如下所示的字符串(似乎是一个 base64 编码的 url,但我找不到任何明确定义这一点的文档)

"x": "ARriqkpHlC1Ia1Tk86EM_bqH_9a88Oh2zMYF3fUUGJw"
"y": "wTYd3CEiwTk1n-lFPdpZ51P4Z0EzlVNXLvJMY-k55pQ"

问题

我需要将其转换为十六进制格式的公钥。我在Python中尝试过以下方法:

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

我对这里使用的软件包一点也不熟悉,上面的代码大部分都是我在网上找到的各种零碎的东西组合而成的。

有人可以为我提供关于如何执行此操作的明确答案吗?

python elliptic-curve python-cryptography ecdh
© www.soinside.com 2019 - 2024. All rights reserved.