gpt4 book ai didi

python - 将 base-64 spki 字符串转换为公钥

转载 作者:行者123 更新时间:2023-12-05 05:51:20 26 4
gpt4 key购买 nike

我正在尝试找到与此 js 函数等效的 python:

/**
* Generating the shared secret with the merchant private key and the ephemeral public key(part of the payment token data)
* using Elliptic Curve Diffie-Hellman (id-ecDH 1.3.132.1.12).
* As the Apple Pay certificate is issued using prime256v1 encryption, create elliptic curve key instances using the package - https://www.npmjs.com/package/ec-key
*/
sharedSecret (privatePem) {
const prv = new ECKey(privatePem, 'pem') // Create a new ECkey instance from PEM formatted string
const publicEc = new ECKey(this.ephemeralPublicKey, 'spki') // Create a new ECKey instance from a base-64 spki string
return prv.computeSecret(publicEc).toString('hex') // Compute secret using private key for provided ephemeral public key
}

我尝试转换的公钥:(应该是 base-64 spki 字符串?)

MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEYtpZKqPDqavs4KzNnMoxWdIThKe/ErKMI/l34Y9/xVkt4DU4BrCaQnGLlRGx+Pn/WHPkQg3BYoRH4xUWswNhEA==

我设法做到的:

from cryptography.hazmat.primitives.asymmetric.ec import SECP256R1, EllipticCurvePublicKey, ECDH
from cryptography.hazmat.primitives.serialization import load_pem_private_key

def __compute_shared_secret(ephemeral_public_key: str) -> bytes:
curve = SECP256R1()
key = base64.b64decode(ephemeral_public_key)
public_key = EllipticCurvePublicKey.from_encoded_point(curve, key) # problem here
server_private_key = load_pem_private_key(<private_key>, password=None)
shared_secret = server_private_key.exchange(ECDH(), public_key)
return shared_secret
ValueError: Unsupported elliptic curve point type

据我所知,在 EllipticCurvePublicKey 中使用它之前,我需要将公钥转换为某种东西,但我不知道应该进行哪种类型的转换。

最佳答案

根据documentation JavaScript 库的行

const publicEc = new ECKey(this.ephemeralPublicKey, 'spki')

导入 Base64 编码的 X.509/SPKI DER key 。


在 Python 中,这可以用 load_der_public_key() 来完成密码学库如下:

from cryptography.hazmat.primitives.serialization import load_der_public_key
import base64
...
public_key = load_der_public_key(base64.b64decode(ephemeral_public_key))

这里,ephemeral_public_key 是 Base64 编码的 X.509/SPKI DER key 。

通过更改 Python 代码,可以确定共享 key 。

关于python - 将 base-64 spki 字符串转换为公钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70394759/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com