C#PEM格式的RSA加密
我在C#中有一个通过公共密钥字符串的方法。
public string RsaEncryptWithPublic(string clearText, string publicKey)
{
byte[] bytes = Encoding.UTF8.GetBytes(clearText);
Pkcs1Encoding pkcs1Encoding = new Pkcs1Encoding((IAsymmetricBlockCipher) new RsaEngine());
using (StringReader reader = new StringReader(publicKey))
{
AsymmetricKeyParameter parameters = (AsymmetricKeyParameter) new PemReader((TextReader) reader).ReadObject();
pkcs1Encoding.Init(true, (ICipherParameters) parameters);
}
return Convert.ToBase64String(pkcs1Encoding.ProcessBlock(bytes, 0, bytes.Length));
}
我通过的公共密钥字符串是
string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlUCQZso6P43gKqw0CfTlwYb3N+m4v6IME 4nPA3WXe52wFpDM/JCFWSdXa7BewlwzDYjblgwL4u59CPxNTPTh7LTD4xXOaGDJHjX5+YgqK4fb9rs ImjMpIACrND/LAdrq5mctWWzw3UtW3F+o+sNwIZM8n65ysS+Vhq9IypFlfuQbWrKjAcWZ3u1iLtplz yf/pjhOEyyZiBUnh6D219+pMiE9nhCpc4xkH1gnlGszIDBqZMMULtGJvFXydA1vv5HxxCYJ2ydEzmA KYxVgA9BGXPEGE89dQbeJsieTj+FSsp9oTm+4vi345opRvH8DWhmZc4OPSwBEL8pwgS7cUnKPtwIDA QAB";
我会收到错误org.bouncycastle.security.invalidkeyexception:“不是RSA键”。我传递给该方法的publicKey格式是否不正确?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
已发布的密钥是X.509/SPKI格式的RSA密钥。
Pemreader
期望PEM编码的密钥。但是,张贴的密钥未编码PEM,在每64个字符后缺少标头,页脚和线路断路。 PEM编码的密钥看起来像这样:关于线断裂
PemReader
是宽容的:只有标头和页脚必须在单独的行中。顺便说一句,从.NET CORE 3.0开始,X.509/SPKI格式的DER编码RSA键的导入由
rsa.importfrompem()
。The posted key is an RSA key in X.509/SPKI format.
PemReader
expects a PEM encoded key. However, the posted key is not PEM encoded, it is missing header, footer and line breaks after every 64 characters. The PEM encoded key looks like this:Regarding line breaks
PemReader
is tolerant: Only header and footer must be in separate lines.Btw, as of .NET Core 3.0, import of a DER encoded RSA key in X.509/SPKI format is supported by
RSA.ImportSubjectPublicKeyInfo()
. As of .NET 5, import of PEM encoded RSA keys is supported withRSA.ImportFromPem()
.