Search code examples
c#pythonencryptionrsabouncycastle

Decrypting RSA data encrypted in python with cryptodome in C# using bouncycastle gives error block incorrect


I am using the following function to encrypt RSA data in PHP:

    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;

}

I am decoding this in C# with the following function:

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;
}

I want to replace the PHP function with python, and tried the following:

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

However, when decoding I get the following error:

InvalidCipherTextException: block incorrect

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

If I try to use PKCS1_OAEP (in python and c#, see commented code), I am getting a data wrong exception.

Not sure what am I missing


Solution

  • After some research, it seems python lirary does not allow to make private key encryption as it is not a standard operation, however in my case I still wanted to do it, and used the code here: 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()