当我用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代码进行更改。反过来我也有同样的问题,但我希望是同样的问题。
任何想法都非常感谢。
pem格式的私钥有多行,也许您可以尝试从文件
中读取私钥PRIVATE_KEY = open('./private.pem', 'r').read()
下面的代码在我的测试服务器上运行
encrypt.go
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"log"
"os"
)
func main() {
s := "heloo"
publicKey, _ := os.ReadFile("./rsa_public_key.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)
}
fmt.Println(base64.StdEncoding.EncodeToString(ciphertext))
}
decrypt.py
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 = "CQMKIcEnqtkvyduwtVNNzdEH23DlQVBaI1rbo/5TA1syW4/ZUyXuHmGTuxqK6+d0gqF7/l2uFGoCY/gQ6FFaVk2JTZqJwYbX5AzZRYI77PuZdjhSROT01LIdDgdRJqO9kqDcIRr1M2b7tRp9a3nF6LwhL9DdX7Z9P1qnNHUEE30="
encrypted_message_bytes = base64.b64decode(encrypted_message.encode("utf-8"))
PRIVATE_KEY = open('./rsa_private_key.pem', 'r').read()
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)
RSA密钥生成命令
openssl genrsa -out rsa_private_key.pem 1024
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
猫。/rsa_private_key.pem
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDabYklPLIPvrwmPpuQZcIjfEnOLq5YtSdOzvDRrFcd0XXBz2Vc
THC+VzgE38l5DqMagdhea0/2UNRBIEQrpLPNwNbvVa7eRmgzOnv3P7R4ylOLorkw
CLpUedOHJ+9pe8mbJ2Z4npKw0Y+JPuqgNY1ZB/PcqaajCoZHgTvdYe14DwIDAQAB
AoGAdQSVorNfmXvPhJWp9bPuS+B8Ec+Ea9WxF1FaRpoTmc/rTEd1v/rbs706L7JM
V2R2EO9bIUpQbl9jNvi4TMFR6X103WdMpkcoUb9l7h583MNCoT7sblwXO5PfVjg7
UWSFv1eDJGWWpbcRCKYCLJ21jxt3smr95uLbvv9w8+GgysECQQDtgHHW5e4YjAcA
AdagVMRnoNUlIsZxMh0dnug2S67XPl53L8KXDk263B8zNGZgYZKBsr2or4rZPF3m
xaqtLONxAkEA63DG0Ood9K1A5OwnROyucxB55w1iOU0omCnBjUjWbI1s6zn+KjOt
Orq1Kx32hQXiMeqht+r94TXVR+x7zhtTfwJAFOyyGurbFVKQ81E2JZ4SR8cFwGXV
8fcmVYvAjbgRSWl3TSzqCgD6nDH0lcBSHL+79q1WxFvi8cy9wS09IlDIIQJBAN4L
TnZZVkcb3sgHsEFgtmXudAlkpe5ExrQ7LT+CIjfeaYqu9vX2JrnsvFAdwhFSqzFI
h5xdE3MCwlNCxMBtJSECQQDATTfT3SquwB1RwIbJ4uD4DDs4ooilMi+6mcYvS+Uf
WGXGmdNHxflUM8HYgfN9nIpI36czrxJfURJ4ueQjZo4l
-----END RSA PRIVATE KEY-----
猫。/rsa_public_key.pem
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDabYklPLIPvrwmPpuQZcIjfEnO
Lq5YtSdOzvDRrFcd0XXBz2VcTHC+VzgE38l5DqMagdhea0/2UNRBIEQrpLPNwNbv
Va7eRmgzOnv3P7R4ylOLorkwCLpUedOHJ+9pe8mbJ2Z4npKw0Y+JPuqgNY1ZB/Pc
qaajCoZHgTvdYe14DwIDAQAB
-----END PUBLIC KEY-----
$ go run ./encrypt.go
wgM33DAJABF0MC0BkflewXPABVdyWpzYMsYhMVKs13OS7SB+fkW31kxL7dipxxEqmTPWXCGFu8o3QxDY82VgcfEywSdigml22KXUN1Qg1VIU6yZg6i34wuD07/8zalW+pza9F43Mj0/XRKnn10ZagfgkBYaytk1zQ4cKcYp4JrM=
$ python3 ./decrypt.py
b'heloo'
我不完全确定是什么改变了,但是当我重新访问它时,它确实开始工作了。我确实改变了我加载证书文件等的方式,所以可能有一个问题,不匹配的密钥或类似的东西,如这里所建议的。我可以确认在python/Go之间执行加密/解密确实有效。感谢那些回应的人。