Home > OS >  decryption equivalent of openssl rsautl -decrypt -oaep -inkey xx.pem -in cyphertext.enc -out plainte
decryption equivalent of openssl rsautl -decrypt -oaep -inkey xx.pem -in cyphertext.enc -out plainte

Time:12-31

I can decrypt a base64 encoded encrypted string using an RSA private key (-----BEGIN RSA PRIVATE KEY----- ----MIIG4wIBAAKCAYEA1HZEO4eUxTjpA7eRzvs3Ew7tVQQ8i1zmr ZpSooF fVqm9VE ZVnE0WslHccLfkpoh8q Zr3lpGqTtiEzlX9BmRN2y7VrrJV7HMGQCB2eO4dpUVCZ vcI/5OChdYsswlFS.... -----END RSA PRIVATE KEY----- with openssl using

openssl rsautl -decrypt -oaep -inkey xx.pem -in cyphertext.enc -out plaintex.txt

I am trying to do the same in .net. I have tried the following using bouncycastle:

string cyphertext = File.ReadAllText(@"data_encoded.txt");
                var bytesToDecrypt = Convert.FromBase64String(cyphertext); // string to decrypt, base64 encoded

            AsymmetricCipherKeyPair keyPair;
            using (var reader = File.OpenText(@"private_key.pem")) // file containing RSA PKCS1 private key
                keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();

var decryptEngine = new Pkcs1Encoding(new RsaEngine());
                decryptEngine.Init(true, keyPair.Private);
                var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); //input data too large

var engine = new RsaEngine();
                engine.Init(false, keyPair.Private);  
                var decrted = Encoding.UTF8.GetString(engine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); //produced corrupted data : [6��oe쩪\u0017^p/\u0003�`M-�?6\u0019w1�\u0012�d"

CodePudding user response:

There are several issues in the code:

  • The OpenSSL statement loads the ciphertext as binary data. Therefore, in the C# code the ciphertext must not be loaded as string and then Base64 decoded, it just needs be loaded as binary data:

    byte[] bytesToDecrypt = File.ReadAllBytes(pathToCiphertextFile);
    

    However, if the ciphertext in the file is really Base64 encoded, then this was achieved with another OpenSSL statement or done afterwards. In this case the change would not be necessary.

  • As already mentioned in the comment, the padding is wrong. The OpenSSL statement applies OAEP with SHA1 for both digests, so the C# code must also use OAEP instead of Pkcs1Encoding():

    var decryptEngine = new OaepEncoding(new RsaEngine(), new Sha1Digest(), new Sha1Digest(), null);
    
  • For decryption the first parameter in decryptEngine.Init() must be false and not true:

    decryptEngine.Init(false, keyPair.Private);
    
  • All lines from and including var engine = new RsaEngine(); make no sense for decryption and must be removed.

With these changes, a ciphertext generated with the posted OpenSSL statement can be successfully decrypted.

  • Related