【发布时间】:2021-12-07 02:32:00
【问题描述】:
当我用 Go 加密一个字符串时,我无法用 Python 再次解密它。我显然做错了什么,但我无法确定问题所在。非常感谢任何帮助。
基本上,我正在使用以下函数加密一个字符串(然后我可以使用 Go 解密,但不能使用 Python):
func encryptString(s string) string {
publicKey, _ := os.ReadFile("public.pem")
block, _ := pem.Decode([]byte(publicKey))
if block.Type != "PUBLIC KEY" {
log.Fatal("error decoding public key from pem")
}
parsedKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
log.Fatal("error parsing key")
}
var ok bool
var pubkey *rsa.PublicKey
if pubkey, ok = parsedKey.(*rsa.PublicKey); !ok {
log.Fatal("unable to parse public key")
}
rng := rand.Reader
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rng, pubkey, []byte(s), nil)
if err != nil {
log.Fatal(err)
}
return base64.StdEncoding.EncodeToString(ciphertext)
}
这是我用来尝试解码加密字符串的 python 代码:
import os
import base64
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.padding import MGF1, OAEP
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
from cryptography.hazmat.primitives.serialization import load_pem_private_key
encrypted_message = "<REMOVED>"
encrypted_message_bytes = base64.b64decode(encrypted_message.encode("utf-8"))
PRIVATE_KEY = os.getenv("PRIVATE_KEY")
private_key_bytes = PRIVATE_KEY.encode("utf-8")
private_key: RSAPrivateKey = load_pem_private_key(private_key_bytes, None)
padding = OAEP(mgf=MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None)
decrypted_message = private_key.decrypt(encrypted_message_bytes, padding)
print(decrypted_message)
运行时,我只收到以下错误:
Traceback (most recent call last):
File "decrypt_test.py", line 14, in <module>
decrypted_message = private_key.decrypt(encrypted_message_bytes, padding)
File "venv/lib/python3.9/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 424, in decrypt
return _enc_dec_rsa(self._backend, self, ciphertext, padding)
File "venv/lib/python3.9/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 87, in _enc_dec_rsa
return _enc_dec_rsa_pkey_ctx(backend, key, data, padding_enum, padding)
File "venv/lib/python3.9/site-packages/cryptography/hazmat/backends/openssl/rsa.py", line 151, in _enc_dec_rsa_pkey_ctx
raise ValueError("Encryption/decryption failed.")
ValueError: Encryption/decryption failed.
我无法控制生产中的 python 代码,所以我只想对 Go 代码进行更改。反过来,我也有同样的问题,但我希望这是同样的问题。
任何想法都非常感谢。
【问题讨论】:
-
OAEP 不幸地被证明对许多实现者来说太复杂了,因此一些实现对 MGF1 哈希进行了假设,即它应该是 SHA1。我不熟悉 Go 的加密,所以我会尝试使用
OAEP(mgf=MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA256(), ...的 python 解密器。如果这不起作用(下面的答案表明这不是问题),那么其他可能性包括不匹配的公钥/私钥或密文损坏。 -
rsa.EncryptOAEP()将第一个参数中指定的摘要用于在 OAEP 上下文中应用的 both 摘要(seg here),因此此处为 SHA256,因此与Python 代码。我的密钥也无法重现问题(与发布的答案一致),因此代码本身很可能不是问题的原因。
标签: python go encryption rsa public-key-encryption