C#解密具有私有非对称密钥的对称密钥

时间:2013-10-24 11:07:32

标签: c# xml encryption

我们收到了一份加密XML文档,其中一些内容使用对称密钥加密,对称密钥以XML格式提供,并使用我们证书的公钥加密。 我试图用我们的私钥解密后一部分,但它不断抛出错误

这是我的代码,非常感谢帮助

public static void Decrypt(XmlDocument Doc, RSA privateKey, string KeyName)
{
      XmlElement xmlelement = Doc.GetElementsByTagName("bla")[0] as XmlElement;
      EncryptedKey encryptedKey = new EncryptedKey();
      encryptedKey.LoadXml(xmlelement);

       //How is the privateKey mapped to encryptedKey??
       //DecryptEncryptedKey throws a value null exception

       EncryptedXml exml = new EncryptedXml(Doc); 
       byte[] decrOut = exml.DecryptEncryptedKey(encryptedKey);            
}

1 个答案:

答案 0 :(得分:0)

你必须预先加载XmlDocument和证书,即

使用xml的XmlDocument doc对象 X509Certificate2 x509ServiceProvider(带私钥的证书)

        // Go and get the encrypted key node
        XmlElement encryptedCipherValueElement = (XmlElement)doc.SelectSingleNode("/XPATH to CipherValue i.e. encrypted symmetric key");

        // These are the input bytes to be decrypted
        byte[] encryptedCipherBytes = Convert.FromBase64String(encryptedCipherValueElement.InnerText);

        // The RSA service provider is necessary as we can't just rely on IIS to decrypt stuff
        RSACryptoServiceProvider rsaServiceProvider = x509ServiceProvider.PrivateKey as RSACryptoServiceProvider;

        // We want to use PKCS1 v1.5 padding which corresponds to OEAP padding being false 
        // This is what other vendors appear to be using. This may become a parameter
        // in time
        const bool OeapPadding = false;
        byte[] decryptedCipherBytes = rsaServiceProvider.Decrypt(encryptedCipherBytes, OeapPadding);

        // We want to wipe out any lingering references to keys or algorithms as
        // soon as possible
        rsaServiceProvider.Clear();

        return decryptedCipherBytes;