使用bouncycastle在C#中使用cryptodome对python中加密的RSA数据进行解密会产生错误块

2024-10-03 17:24:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下函数在PHP中加密RSA数据:

    function RSAEncrypt($text){
    $priv_key=file_get_contents("privateKey.key");
    //$passphrase is required if your key is encoded (suggested)
    $priv_key_res = openssl_get_privatekey($priv_key);



    if(!openssl_private_encrypt($text,$crypttext,$priv_key_res)){
        echo "Error: " . openssl_error_string ();
    }
    return $crypttext;

}

我正在用C#用以下函数对其进行解码:

public static string RSADecrypt(string b64cipher, string pemcert) {
    byte[] bytesCypherText = Convert.FromBase64String(b64cipher);

    Org.BouncyCastle.X509.X509Certificate cert = (Org.BouncyCastle.X509.X509Certificate)new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(pemcert)).ReadObject();
    var decryptEngine = new Pkcs1Encoding(new RsaEngine());
    //var decryptEngine = new OaepEncoding(new RsaEngine());

    decryptEngine.Init(false, cert.GetPublicKey());

    string decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesCypherText, 0, bytesCypherText.Length));
    return decrypted;
}

我想用python替换PHP函数,并尝试了以下操作:

from Cryptodome.PublicKey import RSA
from Cryptodome.Cipher import PKCS1_OAEP, AES, PKCS1_v1_5
import base64
from Cryptodome import Random
from Cryptodome.Random import get_random_bytes
import hashlib
def encrypt_private_key(a_message):
    with open("privateKey.key", 'r') as f:
        private_key = RSA.importKey(f.read())
    #encryptor = PKCS1_OAEP.new(private_key)
    encryptor= PKCS1_v1_5.new(private_key)
    encrypted_msg = encryptor.encrypt(a_message.encode())
    encoded_encrypted_msg = base64.b64encode(encrypted_msg)
    return encoded_encrypted_msg

但是,在解码时,我得到以下错误:

InvalidCipherTextException: block incorrect

at byte[] Org.BouncyCastle.Crypto.Encodings.Pkcs1Encoding.DecodeBlock
 (byte[] input, int inOff, int inLen) at string RSADecrypt (string
 b64cipher, string pemcert)

如果我尝试使用PKCS1_OAEP(在python和c#中,请参阅注释代码),我会得到一个数据错误的异常

不知道我错过了什么


Tags: key函数fromorgimportnewstringmsg
1条回答
网友
1楼 · 发布于 2024-10-03 17:24:10

经过一些研究,python lirary似乎不允许进行私钥加密,因为这不是一个标准操作,但在我的情况下,我仍然想这样做,并在这里使用了代码: https://www.php2python.com/wiki/function.openssl-private-encrypt/

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.serialization import load_pem_private_key
def openssl_private_encrypt(data):
    """Encrypt data with RSA private key.
    This is a rewrite of the function from PHP, using cryptography
    FFI bindings to the OpenSSL library. Private key encryption is
    non-standard operation and Python packages either don't offer
    it at all, or it's incompatible with the PHP version.
    The backend argument MUST be the OpenSSL cryptography backend.
    """
    # usage
    key = load_pem_private_key(open("key.pem").read().encode(
        'ascii'), None, backend=default_backend())
    backend = default_backend()
    length = backend._lib.EVP_PKEY_size(key._evp_pkey)
    buffer = backend._ffi.new('unsigned char[]', length)
    result = backend._lib.RSA_private_encrypt(
        len(data), data, buffer,
        backend._lib.EVP_PKEY_get1_RSA(key._evp_pkey),
        backend._lib.RSA_PKCS1_PADDING)
    backend.openssl_assert(result == length)
    res = backend._ffi.buffer(buffer)[:]
    print(res)
    return base64.b64encode(backend._ffi.buffer(buffer)[:]).decode()

相关问题 更多 >