如何使用BouncyCastle和.pem文件解密xml文件?

时间:2016-02-05 17:05:17

标签: c# bouncycastle pem

我有一个已加密的xml文件和一个包含私钥和证书的Pem文件。

var bytesToDecrypt = File.ReadAllBytes(@"Encrypted.xml.pem");

AsymmetricCipherKeyPair keyPair;

using (var reader = File.OpenText(@"privateKeyAndCert.pem"))
{
     keyPair = (AsymmetricCipherKeyPair)new Org.BouncyCastle.OpenSsl.PemReader(reader).ReadObject();
}

var decrypted = RSADecrypt(bytesToDecrypt, keyPair.Private);
var xml = Encoding.UTF8.GetString(decrypted);

第一次解码尝试抛出异常“输入对于RSA密码来说太大了。”

public static byte[] RSADecrypt(byte[] data, AsymmetricKeyParameter key)
{
    var decryptEngine = new RsaEngine();
    decryptEngine.Init(false, key);
    return decryptEngine.ProcessBlock(data, 0, data.Length);
}

第二次尝试完成但输出是随机字符而不是xml。

public static byte[] RSADecryptChunk(byte[] data, AsymmetricKeyParameter key)
{
    try
    {
        var engine = new RsaEngine();
        engine.Init(false, key);

        int blockSize = engine.GetInputBlockSize();

        List<byte> output = new List<byte>();

        for (int chunkPosition = 0; chunkPosition < data.Length; chunkPosition += blockSize)
        {
            int chunkSize = Math.Min(blockSize, data.Length - ((chunkPosition / blockSize) * blockSize));
            output.AddRange(engine.ProcessBlock(data, chunkPosition, chunkSize));
        }

        return output.ToArray();
    }
    catch (Exception ex)
    {

        return null;
    }
}

以下命令使用openssl成功解密,因此我知道文件是正确的:

openssl smime -decrypt -inform PEM -in "encrypted file path" -out "unencrypted file path" -inkey ".pem file path"

0 个答案:

没有答案