Binu Vijayan
Binu Vijayan

Reputation: 803

RSACryptoServiceProvider.Decrypt() throws "bad data" in console application while the same code works in WCF application

string keyName = "c94a1e1f-177c-460a-8a34-bf1a3da300a2";
        string valueToDecrypt = "GvI5sh1P3a30iX6vkfolier/rHFEDpfVhXngxp12AoUXgfCxkvICugNcvZ9yZLIrTJcsS3clyp8iA7ByRkxYvb1oYOzGznFYkKfWE/4mtarUdlyrLYX8ubYMEGeDfUIhisXGTkRe9ewr7QoNt4wJ8Avu+mRjTonPwzDGTE3f2CQ=";

    string retVal = String.Empty;
    RSACryptoServiceProvider rsa = null;
    try
    {
        if (!String.IsNullOrEmpty(keyName))
        {
            byte[] bDecryptedValue = Convert.FromBase64String(valueToDecrypt);
           // Array.Reverse(bDecryptedValue);

            //byte[] bDecryptedValue = Encoding.UTF8.GetBytes(valueToDecrypt);        

            CspParameters cp = new CspParameters() { KeyContainerName = keyName, Flags = CspProviderFlags.UseExistingKey};              

            rsa = new RSACryptoServiceProvider(cp);
            Console.WriteLine("RSE Object created");
            byte[] byteNumber = rsa.Decrypt(bDecryptedValue, false);
            retVal = ASCIIEncoding.ASCII.GetString(byteNumber);
        }
    }

When i used this code in a WCF application it worked properly. But when i Used the same code on a Console application. Bad data exception is throwing from the line:

byte[] byteNumber = rsa.Decrypt(bDecryptedValue, false);

I tried after reversing the byte array before decrypting and that also didn't work. I also tried creating a Crypto key security access rule since in IIS the application pool was running under "NetworkService" identity.

CryptoKeySecurity cks = new CryptoKeySecurity();
var si = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null);
var sec = new System.Security.AccessControl.CryptoKeyAccessRule(si, CryptoKeyRights.GenericAll, AccessControlType.Allow);
cks.AddAccessRule(sec);
cp.CryptoKeySecurity = cks;

Any idea what would be the reason?

The Code used in WCF Service is

public string Decrypt(string keyName, string valueToDecrypt)
        {
            string retVal = String.Empty;
            RSACryptoServiceProvider rsa = null;
            try
            {
                if (!String.IsNullOrEmpty(keyName))
                {
                    byte[] bDecryptedValue = Convert.FromBase64String(valueToDecrypt);
                    CspParameters cp = new CspParameters() { KeyContainerName = keyName, Flags = CspProviderFlags.UseExistingKey };

                    Console.WriteLine("Reached initialization");

                    rsa = new RSACryptoServiceProvider(cp);
                    byte[] byteNumber = rsa.Decrypt(bDecryptedValue, false);
                    retVal = ASCIIEncoding.ASCII.GetString(byteNumber);
                }
            }

            catch (Exception ex)
            {
                retVal = ex.Message;
            }
            finally
            {
                if (rsa != null)
                {
                    rsa.Dispose();
                }
            }

            return retVal;
        }

The function used for encryption is

 string Encrypt(string valueToEncrypt)
        {
            string retVal = String.Empty;
            RSACryptoServiceProvider rsa = null;
            try
            {
                Key currentKey = GetActiveCryptoKey();
          // while running the Kay name is "c94a1e1f-177c-460a-8a34-bf1a3da300a2"
                if ((currentKey != null) && (!String.IsNullOrEmpty(currentKey.KeyName)))
                {
                    byte[] bDecryptedValue = ASCIIEncoding.ASCII.GetBytes(valueToEncrypt);
                    CspParameters cp = new CspParameters() { KeyContainerName = currentKey.KeyName, Flags = CspProviderFlags.UseExistingKey};
                    rsa = new RSACryptoServiceProvider(cp);
                    byte[] byteNumber = rsa.Encrypt(bDecryptedValue, false);
                    retVal = Convert.ToBase64String(byteNumber);
                }
            }
            catch (FaultException fex)
            {
                throw new FaultException<ServiceFault>(new ServiceFault(fex), fex.Message);
            }
            catch (Exception ex)
            {

                LogException(ex);

            }
            finally
            {
                if (rsa != null)
                {
                    rsa.Dispose();
                }
            }

            return retVal;
        }

Upvotes: 0

Views: 814

Answers (0)

Related Questions