Python 和 Golang 之间的 RSA Encryption/Decryption 不起作用?

RSA Encryption/Decryption between Python and Golang not working?

当我用 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 之间执行 encryption/decryption 确实有效。感谢那些回复的人。