0

I got a digital certificate from a certified body, with it I got a usb sticker with a private key. In VisualStudio I make Console application, i want to test the encryption and decryption with that certificate. For this I used already well known code:

private static string EncryptRSA(string input)
        {
            string outputMessage = String.Empty;
            X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");
            using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PublicKey.Key)
            {
                byte[] byteData = Encoding.UTF8.GetBytes(input);
                byte[] byteEncrypted = csp.Encrypt(byteData, false);
                outputMessage = Convert.ToBase64String(byteEncrypted);
            }

            return izlaznaPoruka;
        }

        public static string DecryptRsa(string enkriptovan)
        {
            string text = string.Empty;
            X509Certificate2 cert = GetCertificateFromStore("I find sertificate by Serial number");

            using (RSACryptoServiceProvider csp = (RSACryptoServiceProvider) cert.PrivateKey)
            {
                byte[] byteEncrypted = Convert.FromBase64String(enkriptovan);
                byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);
                text = Encoding.UTF8.GetString(byteDecrypted);
            }

            return text;
        }

Everything goes as it should until this moment, in the method DecryptRsa:

byte[] byteDecrypted = csp.Decrypt(byteEncrypted, false);

At this point, my authentication client requires a password - I enter the correct password, and the following exception pops up for me: An unhandled exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll An internal error occurred.

Can any one help me?

I've researched a lot of solutions, but most private keys are exported to a .pfx file and use a three-parameter X509Certificate2 constructor when like this

X509Certificate2 cert = new X509Certificate2("myhost.pfx", "pass",
    X509KeyStorageFlags.MachineKeySet); 

Then change the permission of the folder ProgramData\Microsoft\Crypto\RSA\MachineKeys I manually changed the folder rights..

Bain-27
  • 49
  • 1
  • 6

1 Answers1

1

If the error in stack trace is 'keyset does not exist.', then you may need permission in private key from 'Manage Private Keys'

  1. Create a Microsoft Management Console (MMC) with the Certificates snap-in that targets the Local Machine certificate store.
  2. Expand the MMC and select Manage Private Keys
  3. On the Security tab, Add the pool identity or the IIS user account with Read access.

Please check this

Mai Hegazy
  • 11
  • 3