none
RSACrytoService Provider decrypt each element with seperate key gives Bad Data RRS feed

  • Question

  • I have spent about two days. Here is my code:
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.PreserveWhitespace = true;
    xmlDoc.Load("C:\\test.xml");
    
    CspParameters cspParams = new CspParameters();
    cspParams.KeyContainerName = "XML_ENC_RSA_KEY";
    RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);
    
    CspParameters cspParams2 = new CspParameters();
    cspParams2.KeyContainerName = "XML_ENC_RSA_KEY2";
    RSACryptoServiceProvider rsaKey2 = new RSACryptoServiceProvider(cspParams2);
     
    Encrypt(xmlDoc, "creditcard", "EncryptedElement1", rsaKey, "rsaKey");
    
    Encrypt(xmlDoc, "personal", "EncryptedElement2", rsaKey2, "rsaKey");
    

    This works gerat. Now I want to decrypt the 'creditcard' and 'personal' data elements seperately with 'rsakey' and 'rsakey2' . If do this I get Bad Data error

     public static void Decrypt(XmlDocument Doc, RSA Alg, string KeyName)
        {
          EncryptedXml exml = new EncryptedXml(Doc);
          exml.AddKeyNameMapping(KeyName, Alg);
          exml.DecryptDocument();
        }

    This gives bad data since the file has been encrypted with two different keys. So I tried something like this. But I don't know how to decrypt each data element seperately.  Can someone please help?

    public static void DecryptElement(string ElementToEncrypt, RSA Alg, string KeyName)
        {
                XmlDocument EncryptedXmlDoc = new XmlDocument();
          EncryptedXmlDoc.Load("test.xml");
          XmlElement EncryptedElement = EncryptedXmlDoc.GetElementsByTagName(ElementToEncrypt)[0] as XmlElement;
          EncryptedData edElement = new EncryptedData(); 
          edElement.Type = EncryptedXml.XmlEncElementUrl;
          edElement.LoadXml(EncryptedElement);
          EncryptedXml encryptXML = new EncryptedXml();
    ....I am lost here don't know how to decrypt data element individually?
    
    ...
    }
    Please let me know.
    • Moved by SamAgain Monday, August 30, 2010 3:03 AM not CLR question (From:Common Language Runtime)
    Sunday, August 29, 2010 4:54 AM

Answers