简体   繁体   English

Bouncy Castle pem Reader 在读取公钥时抛出异常

[英]Bouncy Castle pem Reader Throws exception When Reading Public Key

I am trying to encrypt a message in C# (in Unity) using a public key.我正在尝试使用公钥加密 C#(在 Unity 中)中的消息。 To do this I am using the Bouncy Castle library.为此,我使用了 Bouncy Castle 库。 I get an error when trying to read the public key using the bouncy castle pem reader.尝试使用充气城堡 pem 阅读器读取公钥时出现错误。 I took this code from here .我从这里拿了这个代码。 The specific error I get is:我得到的具体错误是:

ArgumentException: illegal object in GetInstance: Org.BouncyCastle.Asn1.Dersequence

Here is the code:这是代码:

     static string encrypt(string plainText) {
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        PemReader pr = new PemReader(
            new StringReader(m_publicKey)
        );
        RsaKeyParameters keys = (RsaKeyParameters)pr.ReadObject();

        OaepEncoding eng = new OaepEncoding(new RsaEngine());
        eng.Init(true, keys);

        int length = plainTextBytes.Length;
        int blockSize = eng.GetInputBlockSize();
        List<byte> cipherTextBytes = new List<byte>();
        for (int chunkPosition = 0;
            chunkPosition < length;
            chunkPosition += blockSize)
        {
            int chunkSize = Math.Min(blockSize, length - chunkPosition);
            cipherTextBytes.AddRange(eng.ProcessBlock(
                plainTextBytes, chunkPosition, chunkSize
            ));
        }
        return Convert.ToBase64String(cipherTextBytes.ToArray());
    }

The error occurs when instantiating the pem reader.实例化 pem 读取器时发生错误。 there is a slight difference in my code and the example code linked (I use a StringReader rather than reading from a file), but I get the same error if I read from a file.我的代码和链接的示例代码略有不同(我使用 StringReader 而不是从文件中读取),但是如果我从文件中读取,我会得到相同的错误。 Does anyone have any ideas?有没有人有任何想法?

Ok, I hope this helps anyone else who makes this silly mistake.好的,我希望这可以帮助其他犯这种愚蠢错误的人。 My public key was of the format:我的公钥格式如下:

-----END RSA PUBLIC KEY-----
...
-----END RSA PUBLIC KEY-----

Apparently this format is not accepted.显然这种格式不被接受。

after removing the "RSA" from the header and footer, it was able to load the public key.从页眉和页脚中删除“RSA”后,它能够加载公钥。

EDIT: If helpful for anyone, The key was generated by a go's crypto/rsa package.编辑:如果对任何人有帮助,密钥是由 go 的 crypto/rsa 包生成的。 (GenerateKey function) (GenerateKey 函数)

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

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