“ASN1 损坏了数据。” 替换公钥但不替换私钥时出错

Jos*_*ilu 4 c# rsa asp.net-core

学习使用 RSA 签名的机制,我有一个可以在下面运行的代码块。

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 _);
Run Code Online (Sandbox Code Playgroud)

但类似的块无法用于替换另一个 rsa 对象上的公钥。

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 _);
Run Code Online (Sandbox Code Playgroud)

我只想替换字符串文件中的公共 rsa 密钥,但出现错误

An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in System.Security.Cryptography.Algorithms.dll
ASN1 corrupted data.
Run Code Online (Sandbox Code Playgroud)

Jos*_*ilu 21

我在发布后发现了这个字面意思\n https://vcsjones.dev/key-formats-dotnet-3/

\n
To summarize each PEM label and API pairing:\n\n\xe2\x80\x9cBEGIN RSA PRIVATE KEY\xe2\x80\x9d => RSA.ImportRSAPrivateKey\n\xe2\x80\x9cBEGIN PRIVATE KEY\xe2\x80\x9d => RSA.ImportPkcs8PrivateKey\n\xe2\x80\x9cBEGIN ENCRYPTED PRIVATE KEY\xe2\x80\x9d => RSA.ImportEncryptedPkcs8PrivateKey\n\xe2\x80\x9cBEGIN RSA PUBLIC KEY\xe2\x80\x9d => RSA.ImportRSAPublicKey\n\xe2\x80\x9cBEGIN PUBLIC KEY\xe2\x80\x9d => RSA.ImportSubjectPublicKeyInfo\n
Run Code Online (Sandbox Code Playgroud)\n

我的问题是我的密钥格式为-----BEGIN PUBLIC KEY-----\n 并且我正在使用ImportRSAPublicKey.

\n

我切换到.ImportSubjectPublicKeyInfo,一切都很好

\n