最后我成功地解密了这个消息;看起来BouncyCastleAPI忽略了SHA-256OAEP指令,并坚持使用SHA-1OAEP,这导致了填充异常。此外,Microsoft API还利用
X509Certificate2
只支持
RsaCryptoServiceProvider
据我所知,有SHA-1 OAEP支持。一个人需要更新的
RsaCng
https://github.com/dotnet/corefx
)以及bc csharp(
https://github.com/bcgit/bc-csharp
下面的c代码将解密消息;使用Microsoft API:
var p8Data = File.ReadAllBytes(@"resources\private.p8");
CngKey key = CngKey.Import(p8Data, CngKeyBlobFormat.Pkcs8PrivateBlob);
var rsaprovider = new RSACng(key);
var p7Data = File.ReadAllBytes(@"resources\p7\ID-4.p7");
var envelopedCms = new System.Security.Cryptography.Pkcs.EnvelopedCms();
envelopedCms.Decode(p7Data);
var recipients = envelopedCms.RecipientInfos;
var firstRecipient = recipients[0];
var result = rsaprovider.Decrypt(firstRecipient.EncryptedKey, RSAEncryptionPadding.OaepSHA256);
RijndaelManaged alg = new RijndaelManaged();
alg.KeySize = 256;
alg.BlockSize = 128;
alg.Key = result;
string hexstring = "919D287AAB62B672D6912E72D5DA29CD";
var iv = StringToByteArray(hexstring);
alg.IV = iv;
alg.Mode = CipherMode.CBC;
alg.Padding = PaddingMode.PKCS7;
byte[] content = new byte[400];
Array.Copy(envelopedCms.ContentInfo.Content, content, 400);
string decrypted = null;
ICryptoTransform decryptor = alg.CreateDecryptor(alg.Key, alg.IV);
using (var memoryStream = new MemoryStream(content)) {
using (var cryptoStream = new CryptoStream(memoryStream, alg.CreateDecryptor(alg.Key, alg.IV), CryptoStreamMode.Read)) {
decrypted = new StreamReader(cryptoStream).ReadToEnd();
}
}
实施
StringToByteArray
具体如下:
public static byte[] StringToByteArray(String hex) {
NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}