Error message
System.Security.Cryptography.CryptographicException: ASN1 corrupted data.
Also printed as
- ASN1 corrupted data.
- Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: ASN1 corrupted data.
On Linux and macOS the type is `CryptographicException`; on Windows it can appear as `WindowsCryptographicException` with the same text. The inner exception reads, e.g., "The provided data is tagged with 'Universal' class value '2', but it should have been 'Universal' class value '16'."
.NET System.Security.Cryptography — ImportSubjectPublicKeyInfo / ImportPkcs8PrivateKey / ImportRSAPrivateKey / ImportECPrivateKey
What it means
The bytes you passed to one of the `Import…` methods are not the ASN.1 structure that method decodes. Each method reads exactly one structure — PKCS#8, PKCS#1, SEC 1 or SubjectPublicKeyInfo — and the outer DER does not match, so .NET reports the data as corrupted even though the key itself may be perfectly fine in another format. The inner `AsnContentException` names the tag mismatch.
Why it happens
PKCS#1 vs PKCS#8 (or SEC 1)
common`RSA PRIVATE KEY` bytes given to `ImportPkcs8PrivateKey`, or `PRIVATE KEY` bytes given to `ImportRSAPrivateKey`. The structures differ in their first element (INTEGER vs SEQUENCE).
PEM text or base64 passed as DER
common`Encoding.ASCII.GetBytes(pem)` or `Convert.FromBase64String` over the whole file including the armour lines does not produce DER.
Public and private methods swapped
occasionalA private key passed to `ImportSubjectPublicKeyInfo` or a certificate (not a key) passed to any key import method.
How to fix it
- 1.
Use ImportFromPem for PEM files
It dispatches on the PEM label and avoids picking the wrong DER decoder by hand. Certificates go through `X509Certificate2` instead.
csharp // .NET 5+: ImportFromPem reads the label and picks the right decoder // (PRIVATE KEY, RSA PRIVATE KEY, EC PRIVATE KEY, PUBLIC KEY, RSA PUBLIC KEY). using var key = ECDsa.Create(); key.ImportFromPem(File.ReadAllText("key.pem")); - 2.
Match the method to the DER structure
If you must handle raw DER, choose the import method by what the data is; an ASN.1 viewer tells you which structure you have.
csharp // DER input: choose the method by structure rsa.ImportPkcs8PrivateKey(der, out _); // "PRIVATE KEY" rsa.ImportRSAPrivateKey(der, out _); // "RSA PRIVATE KEY" rsa.ImportSubjectPublicKeyInfo(der, out _); // "PUBLIC KEY" rsa.ImportRSAPublicKey(der, out _); // "RSA PUBLIC KEY" ecdsa.ImportECPrivateKey(der, out _); // "EC PRIVATE KEY"