473,732 Members | 1,991 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Error:"Key not valid for use in specified state" for "RSACryptoServi ceProvider.Encr ypt()"

I modified the RSACSPSample from MSDN to try out a simple commutative
encryption model using RSA encryption but when i run the progrem the first
encryption command works but during the second encryption command (line :
encryptedData2 = RSAE...) i get a "Key not valid for use in specified
state." exception error even though i provide a valid second key to encrypt
it. How can i overcome this error and get double encryption to work ?

The Code I use :
############### ############### ############### ############### ############### ############### ##

using System;
using System.Security .Cryptography;
using System.Text;

class RSATest
{

static void Main()
{
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 = ByteConverter.G etBytes("Data to
Encrypt");
byte[] encryptedData;
byte[] encryptedData2;
byte[] decryptedData;

//Create a new instances of RSACryptoServic eProvider
RSACryptoServic eProvider RSA = new RSACryptoServic eProvider();
RSACryptoServic eProvider RSA2 = new RSACryptoServic eProvider();
//Pass the data to ENCRYPT, the public key information
encryptedData = RSAEncrypt(data ToEncrypt,
RSA.ExportParam eters(false), false);
encryptedData2 = RSAEncrypt(encr yptedData,
RSA2.ExportPara meters(false), false);

//Pass the data to DECRYPT using private key information

decryptedData = RSADecrypt(encr yptedData2,
RSA.ExportParam eters(true), false);

decryptedData = RSADecrypt(decr yptedData,
RSA2.ExportPara meters(true), false);

//Display the decrypted plaintext to the console.
Console.WriteLi ne("Decrypted plaintext: {0}",
ByteConverter.G etString(decryp tedData));
}
catch (Exception ex)
{
//Catch this exception in case the encryption did
//not succeed.
Console.WriteLi ne(ex.Message);

}
}

static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters
RSAKeyInfo, bool DoOAEPPadding)
{
try
{
//Create a new instance of RSACryptoServic eProvider.
RSACryptoServic eProvider RSA = new RSACryptoServic eProvider();

//Import the RSA Key information.
RSA.ImportParam eters(RSAKeyInf o);

//Encrypt the passed byte array and specify OAEP padding.
return RSA.Encrypt(Dat aToEncrypt, DoOAEPPadding);
}
//Catch and display a CryptographicEx ception
//to the console.
catch (CryptographicE xception e)
{
Console.WriteLi ne(e.Message);

return null;
}

}

static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters
RSAKeyInfo, bool DoOAEPPadding)
{
try
{
//Create a new instance of RSACryptoServic eProvider.
RSACryptoServic eProvider RSA = new RSACryptoServic eProvider();

//Import the RSA Key information. This needs
RSA.ImportParam eters(RSAKeyInf o);

//Decrypt the passed byte array and specify OAEP padding.

return RSA.Decrypt(Dat aToDecrypt, DoOAEPPadding);
}
//Catch and display a CryptographicEx ception

catch (CryptographicE xception e)
{
Console.WriteLi ne(e.ToString() );

return null;
}

}
}

Dec 2 '06 #1
0 5680

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

Similar topics

2
2417
by: qe_Cui | last post by:
Hello everyone: I am using vb.net 2003, sqlserver2000 database, and windows 2000 professional OS. In the program, I encrypt the login user's userid and passed with RSACryptoServiceProvider. It is work fine in my compute, but when i set up it on the client computer(which have assembled IE6.0 SP1, ..net framework 1.1 and MDAC 2.7. and the
7
17879
by: Dica | last post by:
i've used the sample code from msdn to create an encyption/decryption assembly as found here: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnnetsec/html/SecNetHT10.asp i'm able to encrypt and then decrypt data okay as in the following code: // encrypt the data // Encryptor enc = new Encryptor(EncryptionAlgorithm.TripleDes); byte key = Encoding.ASCII.GetBytes("0123456789012345");
6
4497
by: karim | last post by:
I have an asp.net page that stopped running properly giving the error below. The app uses a SQL Server 2000 on another server. Enterprise Manager and Query analyzer on the web server can connect to that sql server just fine and run queries. I rebooted the web server and made aspnet member of the admin group. I don't know why the error mentions open connections if I can open several query anaylzer windows using the same sql server...
3
8833
by: Brian Foree | last post by:
I am developing an ASP.NET application that uses Access 2000 as its backend, and have just started getting the following error on 2 ASP.NET pages that had been working until late last week (and I don't think I made any changes to either page other than changing the user control that creates the header). Server Error in '/myApp' Application. ---------------------------------------------------------------------------- ----
0
1135
by: qe_Cui | last post by:
Hello everyone: I am using vb.net 2003, sqlserver2000 database, and windows 2000 professional OS. In the program, I encrypt the login user's userid(is "sa") and passed(is "sa") with RSACryptoServiceProvider. It is work fine in my compute,but when i set up it on the client computer(which have assembled IE6.0 SP1, .net framework 1.1 and MDAC
2
30534
by: GRB | last post by:
A client wants me to decrypt a cookie. They encrypted the data in java using TripleDES. The key provided is a 168 bit 44 character key, DESede alogorithm. Ive tried to decrypt in vb.net and get the above error. Below is the class I use and the code I use to call it. Not sure wher I'm going wrong here. The TripleDES service provider only uses a 192 bit 24 character length key. Any help would be greatly appreciated.
4
6229
by: floppyzedolfin | last post by:
Hello! I'm actually encoding an encryption / decryption program. The encryption programes takes a file path in parameter, and encrypts the contents of the file and stores that into another file. I'm using AES for it is quick, and RSA to encrypt AES, to transmit AES keys (it'll run on two separate computers). Please notice that - this is my first C# code :)
3
2349
by: Mahesh | last post by:
#include <stdio.h> #include <string.h> #include <malloc.h> int main(void) { int key = 120; char *s = "String to Encrypt using XOR"; char *ss = s; char echar; char dchar;
1
2499
by: SM | last post by:
Hi, I need your help, the following code is not working, ret = sr.ReadToEnd() throws the message error : Length of the data to decrypt is invalid. Any idea ? thank you public string Decrypting(string Source, string Key) { string ret = ""; try
0
8944
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
8773
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
9306
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
9234
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
9180
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...
1
6733
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6030
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4548
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2177
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.