我有一个已加密的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"