Problems with RSACryptoServiceProvider in a Windows Service

From: dr_hook (dphook_at_hotmail.com)
Date: 01/27/05


Date: 27 Jan 2005 03:19:37 -0800

I have created an encryption class whose main encryption method
encrypts small amounts of bytes (< 64) using .Net's RSA methods.

This had all been working fine until I tried using the class within a
"Windows Service" application. The application fails on a Decrypt with
a "bad key" error in the "Windows Service" but runs fine (with same key
& encrypted data) in a normal windows application.

The main sections of code from within my class are the following:-

I generate my Public / Private keys in a function like this:-

// Create RSA Crypto object
RSACryptoServiceProvider rsaCSP = new RSACryptoServiceProvider();

// get public & private key xml
sPublicKeyXml = rsaCSP.ToXmlString(false);
sPrivateKeyXml = rsaCSP.ToXmlString(true);

I encrypt like this:-

// encrypt symmetric key
// Create CSPParameters required object
CspParameters cspParam = new CspParameters();
cspParam.Flags = CspProviderFlags.UseDefaultKeyContainer;

// encrypt byte[] using asymmetric method RSA
RSACryptoServiceProvider rsaCSP = new
RSACryptoServiceProvider(cspParam);
// load the private key
rsaCSP.FromXmlString(sPrivateKeyXml);
// encrypt using private key
byte[] byteEncrypted = rsaCSP.Encrypt(byteToEncrypt, false);

And I decrypt like this:-

// Create CSPParameters required object
CspParameters cspParam = new CspParameters();
cspParam.Flags = CspProviderFlags.UseDefaultKeyContainer;

// decrypt byte[] using method RSA
RSACryptoServiceProvider rsaCSP = new
RSACryptoServiceProvider(cspParam);
// load the public key
rsaCSP.FromXmlString(sPublicKeyXml);

// decrypt using public key
byte[] byteDecrypt = rsaCSP.Decrypt(byteEncrypted, false);

I have tried running the Windows Service as Administrator but got the
same "bad key" error.

The stack trace here is
"System.Security.Cryptography.RSACryptoServiceProvider._DecryptPKWin2KEnh(IntPtr
hPubKey, Byte[] rgbKey, Boolean fOAEP)"

I also tried changing the CspProviderFlags property to to
"UseMachineKeyStore" and the code doesn't work at all, even in the
normal windows application.
Any help would be hugely appreciated!

Thanks,

D