Search code examples
c#asp.net-corersa

'ASN1 corrupted data.' error when replacing public key but not private key


learning the mechanics of signing with RSA and I have a block of code that works below.

var privateRSAKey = File.ReadAllText("RSAPrivateKey.txt").Trim();
Regex privateRSAKeyRegex = new Regex(@"-----(BEGIN|END) RSA PRIVATE KEY-----[\W]*");
privateRSAKey = privateRSAKeyRegex.Replace(privateRSAKey, "");

//byte[602]
byte[] rsaPrivateKeyBytes = Convert.FromBase64String(privateRSAKey);

RSA rsa = RSA.Create();
rsa.ImportRSAPrivateKey(new ReadOnlySpan<byte>(rsaPrivateKeyBytes), out _);

But a similar block won't work for replacing the public key on another rsa object.

publicRSAKey = File.ReadAllText("RSAPublicKey.txt").Trim(); 
Regex publicRSAKeyRegex = new Regex(@"-----(BEGIN|END) PUBLIC KEY-----[\W]*");
publicRSAKey = publicRSAKeyRegex.Replace(publicRSAKey, "");

//byte[162]
byte[] rsaPublicKeyBytes = Convert.FromBase64String(publicRSAKey); 

RSA recipientRSA = RSA.Create(); 
recipientRSA.ImportRSAPublicKey(new ReadOnlySpan<byte>(rsaPublicKeyBytes), out _);

I just want to replace the public rsa key from a string file with but i get the error

An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in System.Security.Cryptography.Algorithms.dll
ASN1 corrupted data.

Solution

  • I found this literally after posting https://vcsjones.dev/key-formats-dotnet-3/

    To summarize each PEM label and API pairing:
    
    “BEGIN RSA PRIVATE KEY” => RSA.ImportRSAPrivateKey
    “BEGIN PRIVATE KEY” => RSA.ImportPkcs8PrivateKey
    “BEGIN ENCRYPTED PRIVATE KEY” => RSA.ImportEncryptedPkcs8PrivateKey
    “BEGIN RSA PUBLIC KEY” => RSA.ImportRSAPublicKey
    “BEGIN PUBLIC KEY” => RSA.ImportSubjectPublicKeyInfo
    

    My issue was that my key was in the format -----BEGIN PUBLIC KEY----- and I was using ImportRSAPublicKey .

    I switched to .ImportSubjectPublicKeyInfo and all is well