RSA Encryption - string to byte[] to string to byte[] to string

Here is my goal:

1. Take a string

2. Encrypt it 

3. Pass it as a parameter in the QueryString

4. Decrypt it

 The value starts as a string, then is converted to a byte[] and then encrypted.  The resulting byte[] is converted to a string and send as a parameter.  The recieving page decrypts the string (creates a byte[], decrypts to a new byte[], and the value is finally parsed for its values)

 I am using http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritycryptographyrsacryptoserviceproviderclasstopic.asp with a small modification to allow the Encoding to be changed.

 
The sample works fine, until I send the encrypted byte[] to a string and then back a new byte[] (simulating the recieving page's process).  Once the calls

string s1 = Encoding.Unicode.GetString(encryptedData);
byte[] dataToEncrypt2 = Encoding.Unicode.GetBytes(s1);



are added to the middle of the process the call to Decrypt throws a "Bad Data" exception. I have tried UNICODE and ASCII encoding and neither have worked.  Any help on debugging this would be great, or if there is a better way.

 

try
        {
            //Create a UnicodeEncoder to convert between byte array and string.
            UnicodeEncoding ByteConverter = new UnicodeEncoding();

            //Create byte arrays to hold original, encrypted, and decrypted data.
            byte[] dataToEncrypt = Encoding.Unicode.GetBytes("Data to Encrypt");
            byte[] encryptedData;
            byte[] decryptedData;

            //Create a new instance of RSACryptoServiceProvider to generate
            //public and private key data.
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

            //Pass the data to ENCRYPT, the public key information
            //(using RSACryptoServiceProvider.ExportParameters(false),
            //and a boolean flag specifying no OAEP padding.
            encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);


            string s1 = Encoding.Unicode.GetString(encryptedData);

            byte[] dataToEncrypt2 = Encoding.Unicode.GetBytes(s1);

            //Pass the data to DECRYPT, the private key information
            //(using RSACryptoServiceProvider.ExportParameters(true),
            //and a boolean flag specifying no OAEP padding.
            decryptedData = RSADecrypt(dataToEncrypt2, RSA.ExportParameters(true), false);

            //Display the decrypted plaintext to the console.
            string s = ByteConverter.GetString(decryptedData);
        }
        catch (ArgumentNullException)
        {
            //Catch this exception in case the encryption did
            //not succeed.
            Console.WriteLine("Encryption failed.");

        }

 RSAEncrypt and RSADecrypt can be seen on the referenced page.
 



 

0
BurnChrome
10/30/2006 2:44:28 PM
asp.net.security 27051 articles. 1 followers. Follow

2 Replies
2601 Views

Similar Articles

[PageSpeed] 22

You need to make sure you are using the same RsaParameters when decrypting and encrypting. Here is what I used and it worked well: 
class Program
{
	static void Main(string[] args)
	{
		string StringToEncrypt = "Test String";
		byte[] rawstring = System.Text.Encoding.Unicode.GetBytes(StringToEncrypt);
		RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
		byte[] encrypted = Encrypt(rawstring, rsa.ExportParameters(true));
		string EncryptedString = Convert.ToBase64String(encrypted); //For passing to another page

		//Decrypt
		byte[] todecrypt = Convert.FromBase64String(EncryptedString);
		byte[] decrypted = Decrypt(todecrypt, rsa.ExportParameters(true));
		string decryptedstring = System.Text.Encoding.Unicode.GetString(decrypted);
		Console.WriteLine(decryptedstring);
		Console.ReadKey(true);
	}

	public static byte[] Encrypt(byte[] data, RSAParameters parameters)
	{
		RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
		provider.ImportParameters(parameters);
		return provider.Encrypt(data, false);
	}

	public static byte[] Decrypt(byte[] data, RSAParameters parameters)
	{
		RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
		provider.ImportParameters(parameters);
		return provider.Decrypt(data, false);
	}
}
 
Cheers,
       Kevin Jones


0
vcsjones
10/30/2006 10:58:11 PM

I know this is old... just came across this...

You mentioned using the ecrypted string in the querystring... Make sure you are UrlEncoding/UrlDecoding correctly or characters like '+' or '=' may be replaced and you may get the Bad Data exception.

0
bluevoodoo1
12/16/2008 9:28:03 PM
Reply:

Similar Artilces:

byte[] and byte[][] in datawindow
I am getting a byte[] from the Jaguar component which I apply to the jDataWindowControl in PowerJ using setFullState(byte[]). How do I send any changes to this datawindow to the Jaguar component. The getFullState(byte[][]) requires a 2dimensional byte array. Replied to your post in the PowerJ DataWindow group, which seem like the most appropriate place for the question. Please try to avoid double-posting. Mark Maslow GDI <shalabhgoel@hotmail.com> wrote in message news:QNHQWJ$R$GA.164@forums.sybase.com... > I am getting a byte[] from the Jaguar component whi...

ERROR
Anyone have any idea what this is about...Target Site:Byte[] GetDecodedData(Byte[], Byte[], Int32, Int32, Int32 ByRef)Exception Messages:Unable to validate data.Source Error:System.WebServer Error:System.Web.HttpException: Unable to validate data. at System.Web.Configuration.MachineKey.GetDecodedData(Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Int32& dataLength) at System.Web.UI.LosFormatter.Deserialize(String input)I can post my code, it is a tad long.Thanks. Hi, I'm getting the same error without any clue. Did you manage to solve it?   Thanks,  Yehuda....

want to compare byte[] with byte[]
i have stored encrypted form of password using md5 algorith 1)now if the user wants to delete his account i will take the password from the user and compare with the password present in db public string Get_Password(string strUsrloginid,byte[] strUsrPassword) { while(dtardrPassword.Read())   { strPass=dtardrPassword.GetValue(0).ToString();   } if(strPass==strUsrPassword) { strRtval="Yes"; } else { strRtval="No"; } return strRtval; }   now my question is how to get the value from the db in byte[] form and compare with the password which is given by the use...

Ambiguity between Byte and System::Byte
I have just added zlib.h and zconf.h to a complex application that was compiling fine before and got the following error. [BCC32 Error] Cxcalc.hpp(468): E2015 Ambiguity between 'Byte' and 'System::Byte' I understand, I think :), what it is saying but wondered whether there is a suggested strategy for dealing with it. Cheers <Paul Sanderson> wrote in message news:403158@forums.embarcadero.com... > I have just added zlib.h and zconf.h to a complex application > that was compiling fine before and got the following error. Do you have the same problem i...

Error comparing Byte() to Byte()?
Hi People, This has really thrown me. I'm creating a LOGIN SCREEN in ASP.NET 2.0 using VS2005.... I have a SQL COMMAND ("SELECT * FROM USERS WHERE USERNAME=@USERNAME AND PASSWORD=@PASSWORD") with the following parameter: Code: parPASSWORD = New SqlParameter("@Password", SqlDbType.Binary, 16)parPASSWORD is an MD5 ENCRYPTED PASSWORD that gets returned from an ENCRYPT FUNCTION as Byte() datatype. I can LOG IN fine; the password validates against the encrypted version stored in the database. In my DataTable from the above "SELECT.." statement, I have (amongst others) the PASSWORD field and a TEM...

byte
byte is used to store values from 0 to 256. what it means by this ////////////////////////////////////////byte[] hashedBytes; UTF8Encoding encoder = new UTF8Encoding(); hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(strPassword)); ///////////////////////////////////// here in the above cod what GetBytes(strPassword)); means strPassword is string but byte is integer.Mark As Answer If my reply helped you. Hi,  Encoder.GetBytes() method will encode a set of characters into a sequence of bytes. More info   HTH  K B ShajudeenAreYaar.comDubai, United Arab Emir...

byte
from my project to project library fucntion when i pass the byte information   i get the following message cannot convert from byte to byte  Mark As Answer If my reply helped you. Or does it say byte to byte()?  That would mean that you can't convert a single instance of byte to an array of byte values.---------------------------------------MCP - Web Based Client Development .NET 2.0 What is calling code and what is the code that is being called?Don't forget to click "Mark as Answer" on the post that helped you.This credits that member, earns you a po...

convert RSA Array of Byte Arrays( modulus & Exponent) Key Material into java.security.Public
Does any one know how to convert RSA modulus & exponent ( return from a token as a pubspec[][] into a java.security.Public object. this is my best guess but it has a hole in the middle. pubKeySpec[][] = ....from JNI PKCS11 API call RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(pubSpec[0]), new BigInteger(pubSpec[1])); WHat goes here? X509EncodedKeySpec pukeySPK = new X509EncodedKeySpec( ? ); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); java.security.PublicKey publicKey = keyFactory.generatePublic(pukeySPK...

Multi-Byte on a Single-Byte database
Hi iAnywhere, We have Japanese data stored on a iso1 dataserver. The data is stored "as-is" and no translation was done during storing the data. We are able to read that data in a Putty session with no tranlsation done by dbisqlc(i.e no CharSet param used in sesion connection). Putty has an tranlation option in which I pick the display FONT as UTF-8 that displays Japanese characters correctly. However, I can't seem to get this to work in any of the other Sybase supplied client application. Interctive SQL des not have UTF8 or Unicode font option to display these ...

byte[] buffer = new byte[bufferLength];
What is the VB.NET equivalent of this: byte[] buffer = new byte[bufferLength];   buffer = Byte(bufferlength) is what I tried but it says Byte does not have a constructor Not sure if this is the same, but you can use: ReDim buffer(bufferLength) You can do it a few ways, but note that a the size parameter in VB.NET is not actually the size, rather it is the upper bound (Size - 1), whereas in C# it is the size. // C# byte[] buffer = new byte[bufferLength]; ' VB.NET Dim buffer() As Byte = New Byte(bufferLength - 1) { } ' -OR- Dim buffer(bufferLength - 1) As BytePicky...

How to convert object to Byte[] (Byte array)
Hello how are all here? I need to convert an object into byte[] (byte array). The line of code is below: byte[] DocImage = new byte[] DocImage = returnData["DocImage"] (which returns an object) Now How can I convert object to byte[]? There does not exist any built-in conversion from object to byte[] like Convert.ToInt32, Convert.ToString etc Thanks byte[] DocImage = new byte[] DocImage = (byte[] )returnData["DocImage"] Regards,Anas Ghanem.Note:Please Don't hesitate to click "Report Abuse" link if you noticed something wrong on the forums (like dup...

Copying RawByteString byte by byte in Delphi XE
I just ran into a problem with XE that I never thought of before... copying a RawByteString to another byte by byte does not work on some Windows versions. The example below runs fine on an English Windows, but on a Windows with a Chinese locale (for example Traditional Hong Kong), it fails: procedure TForm1.Button1Click(Sender: TObject); var S1, S2, UTF8BOM: RawByteString; i: integer; begin UTF8BOM := #$EF#$BB#$BF; S1 := UTF8BOM + '<html>TEST</html>'; S2 := ''; for i := 1 to length(S1) do S2 := S2 + S1[i]; //Does NOT wo...

BYTE*
I am calling an API [CryptGetHashParam] that has a BYTE* argument. In the declaration, I've tried ref string, ref char[ ], and ref blob but none of them seems to return anything useful. I'm expecting a 16-byte hash from the MD5 algorithm, which I want to convert to readable hex [e.g. 0cc175b9c0f1b6a831c399e269772661]. Anybody got any fresh ideas? Found it - I declared the variable in the call as blob{16} "Jerry Siegel" <jerry@data-sci.com.nospam> wrote in message news:%23ogcq2ZQDHA.331@forums-2-dub... > I am calling an API [CryptGetHashParam] that h...

BYTES
Este es un mensaje multipartes en formato MIME. --------------218CCA14B939909D2E6E9A75 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit How many bytes is a integer, a char, a date and a long? --------------218CCA14B939909D2E6E9A75 Content-Type: text/x-vcard; charset=us-ascii; name="vcard.vcf" Content-Transfer-Encoding: 7bit Content-Description: Tarjeta de Marta Hern�ndez Ram�rez Content-Disposition: attachment; filename="vcard.vcf" begin: vcard fn: Marta Hern�ndez Ram�rez n: Hern�ndez Ram�rez;Mart...

[byte]()
In the security classe, it has the following code: Public Shared Function Encrypt(ByVal cleanString As String) As String Dim clearBytes As [Byte]() clearBytes = New UnicodeEncoding().GetBytes(cleanString) Dim hashedBytes As [Byte]() = CType(CryptoConfig.CreateFromName("MD5"), HashAlgorithm).ComputeHash(clearBytes) Dim hashedText As String = BitConverter.ToString(hashedBytes) Return hashedText End Function Just wondering when should we use the type [Byte](). Anywhere can I learn more ...

Web resources about - RSA Encryption - string to byte[] to string to byte[] to string - asp.net.security

Encryption - Wikipedia, the free encyclopedia
For technical reasons, an encryption scheme usually uses a pseudo-random encryption key generated by an algorithm. It is in principle possible ...

REPORT: Facebook’s Outdated Web Encryption Technology May Have Enabled Prism
Facebook still uses encryption keys with 1,024-bit lengths, while the industry standard used by Internet companies — including Apple, Microsoft, ...

Search Twitter - encryption
Sign in Sign up Search Refresh Tech Investor News @ TechInvestNews 2m Secusmart puts its BlackBerry encryption chip to work on the desktop (Netflash) ...

Hide Text - Text encryption and secret messages on the App Store on iTunes
Get Hide Text - Text encryption and secret messages on the App Store. See screenshots and ratings, and read customer reviews.

Paris attacks fuel encryption debate
Assaults prompt renewed government push for Silicon Valley to open up systems.

ProtonMail: banning encryption won't stop terrorism
... similar atrocities happening in future. As well as calls for an increase in online surveillance , politicians have also suggested that encryption ...

Apple, Google, Facebook and Microsoft warn weaker encryption makes the bad guys stronger
... stance on encrypted Internet-connected products and services. But government officials aren’t the only ones to voice concerns about encryption. ...

ISIS Is Using Everything From Encryption To PlayStations To Avoid Being Spied On
But the larger problem, according to intelligence officials, is what happens when ISIS stops using technology at all.

Feinstein: The Achilles heel in the internet is encryption - Videos - CBS News
Senate Intelligence Committee member Sen. Dianne Feinstein, D-California, says that the biggest obstacle the intelligence community faces is ...

On encryption, Clinton tells Silicon Valley to be a team player
Democratic presidential candidate tells tech companies they need to help track down terrorists but stops short of calling for weaker encryption. ...

Resources last updated: 11/27/2015 4:02:01 PM