简体   繁体   English

C# PEM 格式的 RSA 加密

[英]RSA Encryption in C# PEM format

I have a method in C# that I pass a public key string.我在 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));
    }

The public key string that I pass is我传递的公钥字符串是

string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlUCQZso6P43gKqw0CfTlwYb3N+m4v6IME 4nPA3WXe52wFpDM/JCFWSdXa7BewlwzDYjblgwL4u59CPxNTPTh7LTD4xXOaGDJHjX5+YgqK4fb9rs ImjMpIACrND/LAdrq5mctWWzw3UtW3F+o+sNwIZM8n65ysS+Vhq9IypFlfuQbWrKjAcWZ3u1iLtplz yf/pjhOEyyZiBUnh6D219+pMiE9nhCpc4xkH1gnlGszIDBqZMMULtGJvFXydA1vv5HxxCYJ2ydEzmA KYxVgA9BGXPEGE89dQbeJsieTj+FSsp9oTm+4vi345opRvH8DWhmZc4OPSwBEL8pwgS7cUnKPtwIDA QAB";

I get an error Org.BouncyCastle.Security.InvalidKeyException: 'Not an RSA key'.我收到一个错误 Org.BouncyCastle.Security.InvalidKeyException: 'Not an RSA key'。 Is the publickey format that I passed to the method is incorrect?我传递给方法的公钥格式不正确吗?

The posted key is an RSA key in X.509/SPKI format.发布的密钥是 X.509/SPKI 格式的 RSA 密钥。 PemReader expects a PEM encoded key. PemReader需要一个 PEM 编码的密钥。 However, the posted key is not PEM encoded, it is missing header, footer and line breaks after every 64 characters.但是,发布的密钥不是 PEM 编码的,它在每 64 个字符后缺少页眉、页脚和换行符。 The PEM encoded key looks like this: PEM 编码的密钥如下所示:

string publicKey = @"-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlUCQZso6P43gKqw0CfTl
wYb3N+m4v6IME4nPA3WXe52wFpDM/JCFWSdXa7BewlwzDYjblgwL4u59CPxNTPTh
7LTD4xXOaGDJHjX5+YgqK4fb9rsImjMpIACrND/LAdrq5mctWWzw3UtW3F+o+sNw
IZM8n65ysS+Vhq9IypFlfuQbWrKjAcWZ3u1iLtplzyf/pjhOEyyZiBUnh6D219+p
MiE9nhCpc4xkH1gnlGszIDBqZMMULtGJvFXydA1vv5HxxCYJ2ydEzmAKYxVgA9BG
XPEGE89dQbeJsieTj+FSsp9oTm+4vi345opRvH8DWhmZc4OPSwBEL8pwgS7cUnKP
twIDAQAB
-----END PUBLIC KEY-----";

Regarding line breaks PemReader is tolerant: Only header and footer must be in separate lines.关于换行符PemReader是可以容忍的:只有页眉和页脚必须在不同的行中。

Btw, as of .NET Core 3.0, import of a DER encoded RSA key in X.509/SPKI format is supported by RSA.ImportSubjectPublicKeyInfo() .顺便说一句,从 .NET Core 3.0 开始, RSA.ImportSubjectPublicKeyInfo()支持以 X.509/SPKI 格式导入 DER 编码的 RSA 密钥。 As of .NET 5, import of PEM encoded RSA keys is supported with RSA.ImportFromPem() .从 .NET 5 开始,使用RSA.ImportFromPem()支持导入 PEM 编码的 RSA 密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM