Error message
No supported key formats were found. Check that the input represents the contents of a PEM-encoded key file, not the path to such a file. (Parameter 'input')
Also printed as
- An encrypted key was found, but no password was provided. Use ImportFromEncryptedPem to import this key. (Parameter 'input')
- Key is not a valid public or private key.
An `ENCRYPTED PRIVATE KEY` block gives "An encrypted key was found, but no password was provided. Use ImportFromEncryptedPem to import this key."
.NET System.Security.Cryptography — ArgumentException from AsymmetricAlgorithm.ImportFromPem
What it means
`ImportFromPem` scanned the string for a PEM block whose label it can import into this algorithm object, and found none. The method takes the PEM text, not a file name, and an `ECDsa` object only accepts EC labels (`PRIVATE KEY`, `EC PRIVATE KEY`, `PUBLIC KEY` with an EC key), an `RSA` object only RSA ones. When the label fits but the key inside belongs to another algorithm, the error is "Key is not a valid public or private key." instead.
Why it happens
A file path instead of the file contents
common`ImportFromPem("/keys/private.pem")` searches the path string for PEM armour and finds none — the hint in the message is there for exactly this mistake.
An RSA PEM imported into ECDsa (or the reverse)
common`RSA PRIVATE KEY` / `RSA PUBLIC KEY` blocks are skipped by `ECDsa.ImportFromPem`, `EC PRIVATE KEY` by `RSA.ImportFromPem`.
A certificate or an unsupported block
occasional`CERTIFICATE`, `CERTIFICATE REQUEST` or `OPENSSH PRIVATE KEY` blocks are not key formats `ImportFromPem` reads.
The key is encrypted
occasionalEncrypted PKCS#8 needs `ImportFromEncryptedPem` with the password.
How to fix it
- 1.
Pass the file contents to the right algorithm
Read the file, create the object of the key's algorithm, and use the encrypted variant for encrypted keys.
csharp using var ecdsa = ECDsa.Create(); ecdsa.ImportFromPem(File.ReadAllText("/run/secrets/jwt-signing-key.pem")); // contents, not the path // encrypted PKCS#8: ecdsa.ImportFromEncryptedPem(File.ReadAllText(path), Environment.GetEnvironmentVariable("KEY_PASSPHRASE")); - 2.
Load certificates as certificates
Take the public key from an `X509Certificate2` instead of importing the certificate PEM as a key.
csharp // .NET 9+: certificates are loaded with X509CertificateLoader, then the key is taken from them var cert = X509CertificateLoader.LoadCertificate(File.ReadAllBytes("cert.der")); using ECDsa? publicKey = cert.GetECDsaPublicKey();