.NET Core 3.1 - RSA.ImportRSAPrivateKey raises a CryptographicException

Viewed 2082

I'm training to asymmetric encryption with RSA. I created a key pair with ssh-keygen, and I managed to encrypt some data with my public key. But when I try to decrypt this data with my private key, this exception is raised :

System.Security.Cryptography.CryptographicException : 'ASN1 corrupted data.'

Here is my PEM file containing my private key :

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,E79376C1ECFD82F05A871D9245BFC958

iEL9aNdWIC3TckveRH2ADdHrnCAQeyg0GUFx0obx1sHOCDdiCIb2u46vFUQ8QP6H
vHHgA9Kf4lY8Jq6Qkv/Iyhh9WcWTR2nNjbN7Ndlb343MyjeNdlXdVrHsfR8Q98ul
06FiKZdnS640PzxAUvibbmkLVus8g3V14qZqeDTqN1rbOCAk2Kxfy5V4kd6M7wCm
fqABkYpp+2EYf4Z4YcJbLDXEEIg7HD/AI1gPpE5nRQoSib/9bm87j98VnG5dOYAJ
38ZMTvJjIImQveOUeSNyR/re71V+YUy0N/zvqMrlp4pDFsDb6infZga0jPFzGXGy
5S3XYXSs9iPReFHQnhWr/L3dRx9TpfZJcl4BJ6D8j9wxrWRcharGNNgCK/kV9FJw
BpwFu01jNESDHV3dyWTcOAzQit4pDkr0A9EK4N1vfWaLLO8vqyGtqlvtU5sD2rYQ
JvrMEsUsAYXJcBDUX2cksNEen+7s338cBGg4NdE+xAUeKv5EysYIKgojPJi6WQ39
FAgkr1TfWaffO/TgfL/DwC1wyHXleNyDQ87unyxRIRu/wWnqJaQQG8Z0BilIbDp8
KrKfkHW9CWaPCbldOzHJ5UDZmA5+AvfoaATRw/vW1Wg0GYkuNqqHzV7tNFKcnUG1
DmIaSI+Y55cngqeOStFfgRTehbXK84w3PzR3lnpuxG4rtOjDV8RfZSozaSValqju
ZWRYEbKn7Za2XZWJT4kkDa5O4nJUMbihBOUL+FWc6dmDIaZY/nUKJAm2pxmd0R1s
9PcXhqLEnBTvGh1CrOdhiqkHQ5A5OtIp/FrPhUltjsy129NC5/dPZaN9v4TgNYQu
zNd8vSlVXuimB+2OoXu3fNE75ywxmrs4H8M4y3u87GQWFdYwQFFnv2fyCzV8iqvy
ybQR599v5qL2IKvHdw68q9PDmasd4jSTAoFP/g6QQKMCaQuMUbrtlHzvPvNnCgk1
AChbFeuLK57c2rwVwTx0YEATcKz27/V5af0E2x6sLDoqQv5SBkREuuWyA6DsSO/S
vX1WR/hZWk2PVi24N/AG8T/sIfyBeTPw7Yx3RuT5MWLdR6haSEKkGGrGuxr1HnoF
lt3JruZczavGpAn5Q8DSVKb78Q8kqI/gdLYNIuq5Yy7Mz1ldocN0N2CarUGWgU7e
+z0TM2CWkTBE7Q0CU4Na5QusvaLYDgH4LW4WY9BNN86C4uKQFjJHz6gZoI3zx8/L
RxN2bGyd0H83k4xuQXml2RnnPPB6L5JwJxxme5ecWpMdp5c6xyXX1ZPKkkGuRbFs
OxeQqNNfPEExqtC2U/Jn5B1HYJqCYCeKlUNdqUoZv5vT8x9UDoE5vKtP3DtTckeB
+6n7S2viNWzV2qid8moh9DfWGMlF4i1y91pdcNJx+M01OfLOB1EPlD0MoTvkfU6s
x0VQh5t4wCbcJ7kcIrp2siPbBg4RPV8MNKtaBhTvFf+nH1TAEsUMjdi7FrnfBn3b
4o4BqC+ibQHC/+SkGAxRakdJjM5XcXO1BZp4zLYSBQyXGu7kp8ohOvHx65vtwvls
XCdbtnJs/iAORxAgLnuVPzLUfTd6bLlszOsyIvC8+j587GX5YFW+h4s+bicZMwCm
-----END RSA PRIVATE KEY-----

And here is the code sample using this private key :

static string RSA_Decrypt(byte[] value)
{
    byte[] deciphered;

    using (var reader = File.OpenText(@"C:\Users\???\.ssh\id_rsa"))
    {
        // Extracting the payload
        string privateKeyFile = reader.ReadToEnd();
        var exp = privateKeyFile.Split("\n\n");
        var privateKey = exp[1].Split("\n-----")[0];

        // using the payload to decrypt my data
        using(var rsa = RSA.Create())
        {
            rsa.ImportRSAPrivateKey(Convert.FromBase64String(privateKey), out _); //CryptographicException

            deciphered = rsa.Decrypt(value, RSAEncryptionPadding.Pkcs1);
        }
    }

    return Encoding.Default.GetString(deciphered);
}

What am I doing wrong?

2 Answers

The posted private key is a PEM encoded PKCS#1 key that is encrypted.

RSA.ImportRSAPrivateKey() can only import unencrypted keys of this format that are furthermore DER encoded. The DER encoding results from the PEM encoding by removing the header and footer and Base64 decoding the rest.

As far as I know, an encrypted PKCS#1 key cannot be imported with .NET Core 3.1 on-board means. But an import is possible with BouncyCastle and its Org.BouncyCastle.OpenSsl.PemReader class, see e.g. here.

Unlike the PKCS#1 format, a DER encoded private key in PKCS#8 format can be imported with .NET Core 3.1 out of the box (RSA.ImportPkcs8PrivateKey()), even if it is encrypted (RSA.ImportEncryptedPkcs8PrivateKey()).
Keys of this format can be generated e.g. with openssl genpkey. With OpenSSL it is also possible to convert between the formats.

Thanks Topaco, that's exactly what I needed! I used BouncyCastle to decrypt my private key, and now it's working perfectly! I don't know why RSA class does not have any method to do it...

So here is my code now :

static string RSA_Decrypt(byte[] value)
{
    string deciphered;

    using (var reader = File.OpenText(@"C:\Users\???\.ssh\id_rsa"))
    {
        string privateKeyFile = reader.ReadToEnd();
        var keyReader = new StringReader(privateKeyFile);

        var decryptEngine = new Pkcs1Encoding(new RsaEngine());

        object pemReader = new PemReader(keyReader, new PasswordFinder("azerty")).ReadObject();
        var keyPair = (AsymmetricCipherKeyPair)pemReader;
        decryptEngine.Init(false, keyPair.Private);

        deciphered = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(value, 0, value.Length));
    }

    return deciphered;
}

PS : Yeah, my private key password is "azerty" ^^ I wasn't inspired when I created my key pair ^^

Related