473,667 Members | 2,583 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

program when decrypting XML - Unable to retrieve the decryption key

When decrypt the xml, output "Unable to retrieve the decryption key."
Can anyone help me solve the problem?

I got the code from http://msdn.microsoft.com/en-us/library/ms229746.aspx
using System;
using System.Xml;
using System.Security .Cryptography;
using System.Security .Cryptography.X ml;

class Program
{
static void Main(string[] args)
{
// Create an XmlDocument object.
XmlDocument xmlDoc = new XmlDocument();

// Load an XML file into the XmlDocument object.
try
{
xmlDoc.Preserve Whitespace = true;
xmlDoc.Load("te st.xml");
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}

// Create a new CspParameters object to specify
// a key container.
CspParameters cspParams = new CspParameters() ;
cspParams.KeyCo ntainerName = "XML_ENC_RSA_KE Y";

// Create a new RSA key and save it in the container. This key will
encrypt
// a symmetric key, which will then be encryped in the XML document.
RSACryptoServic eProvider rsaKey = new
RSACryptoServic eProvider(cspPa rams);

try
{
// Encrypt the "creditcard " element.
Encrypt(xmlDoc, "creditcard ", "EncryptedEleme nt1", rsaKey,
"rsaKey");
// Save the XML document.
xmlDoc.Save("te st_Encrypted.xm l");

// Display the encrypted XML to the console.
Console.WriteLi ne("Encrypted XML:");
Console.WriteLi ne();
Console.WriteLi ne(xmlDoc.Outer Xml);

}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
finally
{
// Clear the RSA key.
rsaKey.Clear();
}
// Create an XmlDocument object.
xmlDoc = new XmlDocument();

// Load an XML file into the XmlDocument object.
try
{
xmlDoc.Preserve Whitespace = true;
xmlDoc.Load("te st_Encrypted.xm l");
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
cspParams = new CspParameters() ;
cspParams.KeyCo ntainerName = "XML_ENC_RSA_KE Y";

// Get the RSA key from the key container. This key will decrypt
// a symmetric key that was imbedded in the XML document.
rsaKey = new RSACryptoServic eProvider(cspPa rams);

try
{

// Decrypt the elements.
Decrypt(xmlDoc, rsaKey, "rsaKey");
// Display the encrypted XML to the console.
Console.WriteLi ne();
Console.WriteLi ne("Decrypted XML:");
Console.WriteLi ne();
Console.WriteLi ne(xmlDoc.Outer Xml);
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
finally
{
// Clear the RSA key.
rsaKey.Clear();
}

Console.ReadLin e();
}

public static void Encrypt(XmlDocu ment Doc, string ElementToEncryp t,
string EncryptionEleme ntID, RSA Alg, string KeyName)
{
// Check the arguments.
if (Doc == null)
throw new ArgumentNullExc eption("Doc");
if (ElementToEncry pt == null)
throw new ArgumentNullExc eption("Element ToEncrypt");
if (EncryptionElem entID == null)
throw new ArgumentNullExc eption("Encrypt ionElementID");
if (Alg == null)
throw new ArgumentNullExc eption("Alg");
if (KeyName == null)
throw new ArgumentNullExc eption("KeyName ");

////////////////////////////////////////////////
// Find the specified element in the XmlDocument
// object and create a new XmlElemnt object.
////////////////////////////////////////////////
XmlElement elementToEncryp t =
Doc.GetElements ByTagName(Eleme ntToEncrypt)[0] as XmlElement;

// Throw an XmlException if the element was not found.
if (elementToEncry pt == null)
{
throw new XmlException("T he specified element was not found");

}
RijndaelManaged sessionKey = null;

try
{
//////////////////////////////////////////////////
// Create a new instance of the EncryptedXml class
// and use it to encrypt the XmlElement with the
// a new random symmetric key.
//////////////////////////////////////////////////

// Create a 256 bit Rijndael key.
sessionKey = new RijndaelManaged ();
sessionKey.KeyS ize = 256;

EncryptedXml eXml = new EncryptedXml();

byte[] encryptedElemen t = eXml.EncryptDat a(elementToEncr ypt,
sessionKey, false);
////////////////////////////////////////////////
// Construct an EncryptedData object and populate
// it with the desired encryption information.
////////////////////////////////////////////////

EncryptedData edElement = new EncryptedData() ;
edElement.Type = EncryptedXml.Xm lEncElementUrl;
edElement.Id = EncryptionEleme ntID;
// Create an EncryptionMetho d element so that the
// receiver knows which algorithm to use for decryption.

edElement.Encry ptionMethod = new
EncryptionMetho d(EncryptedXml. XmlEncAES256Url );
// Encrypt the session key and add it to an EncryptedKey
element.
EncryptedKey ek = new EncryptedKey();

byte[] encryptedKey = EncryptedXml.En cryptKey(sessio nKey.Key,
Alg, false);

ek.CipherData = new CipherData(encr yptedKey);

ek.EncryptionMe thod = new
EncryptionMetho d(EncryptedXml. XmlEncRSA15Url) ;

// Create a new DataReference element
// for the KeyInfo element. This optional
// element specifies which EncryptedData
// uses this key. An XML document can have
// multiple EncryptedData elements that use
// different keys.
DataReference dRef = new DataReference() ;

// Specify the EncryptedData URI.
dRef.Uri = "#" + EncryptionEleme ntID;

// Add the DataReference to the EncryptedKey.
ek.AddReference (dRef);
// Add the encrypted key to the
// EncryptedData object.

edElement.KeyIn fo.AddClause(ne w KeyInfoEncrypte dKey(ek));
// Set the KeyInfo element to specify the
// name of the RSA key.

// Create a new KeyInfo element.
edElement.KeyIn fo = new KeyInfo();

// Create a new KeyInfoName element.
KeyInfoName kin = new KeyInfoName();

// Specify a name for the key.
kin.Value = KeyName;

// Add the KeyInfoName element to the
// EncryptedKey object.
ek.KeyInfo.AddC lause(kin);
// Add the encrypted element data to the
// EncryptedData object.
edElement.Ciphe rData.CipherVal ue = encryptedElemen t;
////////////////////////////////////////////////////
// Replace the element from the original XmlDocument
// object with the EncryptedData element.
////////////////////////////////////////////////////
EncryptedXml.Re placeElement(el ementToEncrypt, edElement, false);
}
catch (Exception e)
{
// re-throw the exception.
throw e;
}
finally
{
if (sessionKey != null)
{
sessionKey.Clea r();
}

}

}
public static void Decrypt(XmlDocu ment Doc, RSA Alg, string KeyName)
{
// Check the arguments.
if (Doc == null)
throw new ArgumentNullExc eption("Doc");
if (Alg == null)
throw new ArgumentNullExc eption("Alg");
if (KeyName == null)
throw new ArgumentNullExc eption("KeyName ");
// Create a new EncryptedXml object.
EncryptedXml exml = new EncryptedXml(Do c);

// Add a key-name mapping.
// This method can only decrypt documents
// that present the specified key name.
exml.AddKeyName Mapping(KeyName , Alg);

// Decrypt the element.
exml.DecryptDoc ument();

}

}
Jun 27 '08 #1
1 6408
Any idea?
"Elliot" <el************ @hotmail.co.ukw rote in message
news:EF******** *************** ***********@mic rosoft.com...
When decrypt the xml, output "Unable to retrieve the decryption key."
Can anyone help me solve the problem?

I got the code from http://msdn.microsoft.com/en-us/library/ms229746.aspx
using System;
using System.Xml;
using System.Security .Cryptography;
using System.Security .Cryptography.X ml;

class Program
{
static void Main(string[] args)
{
// Create an XmlDocument object.
XmlDocument xmlDoc = new XmlDocument();

// Load an XML file into the XmlDocument object.
try
{
xmlDoc.Preserve Whitespace = true;
xmlDoc.Load("te st.xml");
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}

// Create a new CspParameters object to specify
// a key container.
CspParameters cspParams = new CspParameters() ;
cspParams.KeyCo ntainerName = "XML_ENC_RSA_KE Y";

// Create a new RSA key and save it in the container. This key
will encrypt
// a symmetric key, which will then be encryped in the XML
document.
RSACryptoServic eProvider rsaKey = new
RSACryptoServic eProvider(cspPa rams);

try
{
// Encrypt the "creditcard " element.
Encrypt(xmlDoc, "creditcard ", "EncryptedEleme nt1", rsaKey,
"rsaKey");
// Save the XML document.
xmlDoc.Save("te st_Encrypted.xm l");

// Display the encrypted XML to the console.
Console.WriteLi ne("Encrypted XML:");
Console.WriteLi ne();
Console.WriteLi ne(xmlDoc.Outer Xml);

}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
finally
{
// Clear the RSA key.
rsaKey.Clear();
}
// Create an XmlDocument object.
xmlDoc = new XmlDocument();

// Load an XML file into the XmlDocument object.
try
{
xmlDoc.Preserve Whitespace = true;
xmlDoc.Load("te st_Encrypted.xm l");
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
cspParams = new CspParameters() ;
cspParams.KeyCo ntainerName = "XML_ENC_RSA_KE Y";

// Get the RSA key from the key container. This key will decrypt
// a symmetric key that was imbedded in the XML document.
rsaKey = new RSACryptoServic eProvider(cspPa rams);

try
{

// Decrypt the elements.
Decrypt(xmlDoc, rsaKey, "rsaKey");
// Display the encrypted XML to the console.
Console.WriteLi ne();
Console.WriteLi ne("Decrypted XML:");
Console.WriteLi ne();
Console.WriteLi ne(xmlDoc.Outer Xml);
}
catch (Exception e)
{
Console.WriteLi ne(e.Message);
}
finally
{
// Clear the RSA key.
rsaKey.Clear();
}

Console.ReadLin e();
}

public static void Encrypt(XmlDocu ment Doc, string ElementToEncryp t,
string EncryptionEleme ntID, RSA Alg, string KeyName)
{
// Check the arguments.
if (Doc == null)
throw new ArgumentNullExc eption("Doc");
if (ElementToEncry pt == null)
throw new ArgumentNullExc eption("Element ToEncrypt");
if (EncryptionElem entID == null)
throw new ArgumentNullExc eption("Encrypt ionElementID");
if (Alg == null)
throw new ArgumentNullExc eption("Alg");
if (KeyName == null)
throw new ArgumentNullExc eption("KeyName ");

////////////////////////////////////////////////
// Find the specified element in the XmlDocument
// object and create a new XmlElemnt object.
////////////////////////////////////////////////
XmlElement elementToEncryp t =
Doc.GetElements ByTagName(Eleme ntToEncrypt)[0] as XmlElement;

// Throw an XmlException if the element was not found.
if (elementToEncry pt == null)
{
throw new XmlException("T he specified element was not found");

}
RijndaelManaged sessionKey = null;

try
{
//////////////////////////////////////////////////
// Create a new instance of the EncryptedXml class
// and use it to encrypt the XmlElement with the
// a new random symmetric key.
//////////////////////////////////////////////////

// Create a 256 bit Rijndael key.
sessionKey = new RijndaelManaged ();
sessionKey.KeyS ize = 256;

EncryptedXml eXml = new EncryptedXml();

byte[] encryptedElemen t = eXml.EncryptDat a(elementToEncr ypt,
sessionKey, false);
////////////////////////////////////////////////
// Construct an EncryptedData object and populate
// it with the desired encryption information.
////////////////////////////////////////////////

EncryptedData edElement = new EncryptedData() ;
edElement.Type = EncryptedXml.Xm lEncElementUrl;
edElement.Id = EncryptionEleme ntID;
// Create an EncryptionMetho d element so that the
// receiver knows which algorithm to use for decryption.

edElement.Encry ptionMethod = new
EncryptionMetho d(EncryptedXml. XmlEncAES256Url );
// Encrypt the session key and add it to an EncryptedKey
element.
EncryptedKey ek = new EncryptedKey();

byte[] encryptedKey = EncryptedXml.En cryptKey(sessio nKey.Key,
Alg, false);

ek.CipherData = new CipherData(encr yptedKey);

ek.EncryptionMe thod = new
EncryptionMetho d(EncryptedXml. XmlEncRSA15Url) ;

// Create a new DataReference element
// for the KeyInfo element. This optional
// element specifies which EncryptedData
// uses this key. An XML document can have
// multiple EncryptedData elements that use
// different keys.
DataReference dRef = new DataReference() ;

// Specify the EncryptedData URI.
dRef.Uri = "#" + EncryptionEleme ntID;

// Add the DataReference to the EncryptedKey.
ek.AddReference (dRef);
// Add the encrypted key to the
// EncryptedData object.

edElement.KeyIn fo.AddClause(ne w KeyInfoEncrypte dKey(ek));
// Set the KeyInfo element to specify the
// name of the RSA key.

// Create a new KeyInfo element.
edElement.KeyIn fo = new KeyInfo();

// Create a new KeyInfoName element.
KeyInfoName kin = new KeyInfoName();

// Specify a name for the key.
kin.Value = KeyName;

// Add the KeyInfoName element to the
// EncryptedKey object.
ek.KeyInfo.AddC lause(kin);
// Add the encrypted element data to the
// EncryptedData object.
edElement.Ciphe rData.CipherVal ue = encryptedElemen t;
////////////////////////////////////////////////////
// Replace the element from the original XmlDocument
// object with the EncryptedData element.
////////////////////////////////////////////////////
EncryptedXml.Re placeElement(el ementToEncrypt, edElement,
false);
}
catch (Exception e)
{
// re-throw the exception.
throw e;
}
finally
{
if (sessionKey != null)
{
sessionKey.Clea r();
}

}

}
public static void Decrypt(XmlDocu ment Doc, RSA Alg, string KeyName)
{
// Check the arguments.
if (Doc == null)
throw new ArgumentNullExc eption("Doc");
if (Alg == null)
throw new ArgumentNullExc eption("Alg");
if (KeyName == null)
throw new ArgumentNullExc eption("KeyName ");
// Create a new EncryptedXml object.
EncryptedXml exml = new EncryptedXml(Do c);

// Add a key-name mapping.
// This method can only decrypt documents
// that present the specified key name.
exml.AddKeyName Mapping(KeyName , Alg);

// Decrypt the element.
exml.DecryptDoc ument();

}

}

Jun 27 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
6871
by: M Wells | last post by:
Hi All, I'm trying to implement encryption on certain data fields in my MySQL database and I'm experiencing ongoing problems. I seem to be able to encrypt the data without issues, but can't figure out how to decrypt the data. My field in my test table, in which I'm storing the encrypted data, is a TEXT type field.
2
1553
by: Brian Genisio | last post by:
Hi all, So, IE has a code obfuscation method that is specific to IE. I have read that it has been easily decrypted. Has the decryption for this method been published anywhere? Is it legal to do so, assuming the authors of the code give my permission to read the code? Before anyone flames me, I promise my motives are legitimate. I am developing the DOM and JS interface for a browser that needs to act like IE.
10
7680
by: Alessandro Bottoni | last post by:
I know you will shake you head sadly but... I really have to perform such a suicidal task (even if for a short time and just for internal use). I have to send by email (over the open internet) a XML file containing _system commands_ (yes: the kind of stuff like "rm -dfr /") to a server and have a Python program sitting on this server, fetching and parsing the e-mail message and executing the commands (maybe with _root privileges_). Of...
5
8983
by: Joe | last post by:
I'm trying to figure out how to remove the characters padded to the end of my string without setting the Padding = PaddingMode.None. My original string passed in is 'passwordTest' and the resulting decrypted string is 'passwordTestAAAAAAAAAA==' I would like to use for both strings and files. private static string DoEncryption(byte data) {
2
4311
by: Abhishek Bhatt | last post by:
We are using MSAccess forms as a front end of our application. The business logics are written is VB 6.3 that comes with MSAccess. We have to use Triple DES in our application for encryption and decryption. The password for connecting to some other system would be provided to us in an encrypted form and key would be provided. We have to decrypt this password in our application. But I don't have any idea of how can we do that. Can anyone give...
4
5690
by: Fritjolf | last post by:
Hi. I've got a strange problem... I've made a simple program to test encryption/decryption. I use Rijndael encryption and here are the most important properties. RijndaelManaged cipher = new RijndaelManaged(); cipher.KeySize = 256; cipher.BlockSize = 256;
3
4387
by: Sin Jeong-hun | last post by:
It seems like the Protect() uses the Windows accout information to encrypt data. If I know the user name and the password, can I decrypt it on another PC? If it is not, how about the exported key? On Windows Vista, if file encryption is used, Windows suggests to back up the key. If I import the key on another PC, then can I decrypt a data protected by the Protect() method? Or it is impossible by any means?
6
2861
by: priyajohal | last post by:
#include<fstream.h> #include<process.h> #include<stdlib.h> #include<conio.h> #include<string.h> #include<dos.h> #include<ctype.h> #include<stdio.h> void setup() void help();
12
2570
by: techani | last post by:
hi , I have a problem in the following program (at the first link ) , which is : I send a simple encrypted message in AES , the encrypting and sending operations is done ok with no any problems , but when receiving and decrypting , the message decryption operation gives an exceptions , Although the decryption operation is done absolutely very well ( the second link improves that ) , some body tells me what is the problem Exactly please...
0
8457
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8365
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8788
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8563
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8646
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7390
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2776
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1778
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.