首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C#使用私有非对称密钥解密对称密钥

C#使用私有非对称密钥解密对称密钥
EN

Stack Overflow用户
提问于 2013-10-24 19:07:32
回答 1查看 784关注 0票数 0

我们收到了一个加密的XML文档,其中一些内容是用对称密钥加密的,对称密钥是在XML中提供的,用我们证书的公钥加密。我试图用我们的私钥解密后半部分,但它总是抛出错误。

这是我的代码,非常感谢。

代码语言:javascript
复制
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);            
}
EN

回答 1

Stack Overflow用户

发布于 2015-03-24 01:17:07

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

使用您的xml X509Certificate2 x509ServiceProvider (使用私钥的证书)创建XmlDocument文档对象

代码语言:javascript
复制
        // 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;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19564226

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档