The exception "The key does not exist" is excluded. What am I doing wrong?

I have a test below that isolates the problem I encountered using System.Security.Cryptograph.RSACryptoServiceProvider. The problem is that r.Decrypt throws a "Key does not exist" exception. If I use privateKeyXml for encryption and decryption (instead of using publicKeyXml when decrypting), then it works as expected. Of course, I do not want to share the private key, I need to be able to decrypt using the public key. Does anyone see what I'm doing wrong here?

[Fact] public void BasicEncryptDecrypt() { var cspParameters = new CspParameters() { Flags = CspProviderFlags.CreateEphemeralKey | CspProviderFlags.NoPrompt }; string privateKeyXml = null; string publicKeyXml = null; using(var r = new RSACryptoServiceProvider(2048, cspParameters)){ r.PersistKeyInCsp = false; privateKeyXml = r.ToXmlString(true); publicKeyXml = r.ToXmlString(false); } byte[] encrypted = null; string decrypted = null; using (var r = new RSACryptoServiceProvider(2048, cspParameters)) { r.FromXmlString(privateKeyXml); encrypted = r.Encrypt(Encoding.UTF8.GetBytes("foobar"), false); } using (var r = new RSACryptoServiceProvider(2048, cspParameters)) { r.FromXmlString(publicKeyXml); decrypted = Encoding.UTF8.GetString(r.Decrypt(encrypted, false)); } Assert.Equal("foobar", decrypted); } 
+6
source share
1 answer

Use "private key encryption / public key decryption". I am working on a project where there is a specific context in which we must do this. I know there is a lot of discussion about this, but I will continue to explain how to do this. I think there are many questions that explain when we should use "sign / verification" or "public key encryption / decryption of the secret key" or not.

First of all, I got the same solution as you, but it didnโ€™t work, I checked many CspParameters options. I think this should work, but it is not!

So my final solution was to use the BouncyCastle libraries:

 RsaPrivateCrtKeyParameters privateKeyParameters = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(Convert.FromBase64String(prvKey)); AsymmetricKeyParameter publicKeyInfoParameters = PublicKeyFactory.CreateKey(Convert.FromBase64String(pubKey)); byte[] clearData = Encoding.UTF8.GetBytes("..."); string algorithm = "RSA/ECB/PKCS1Padding"; var cipherOne = Org.BouncyCastle.Security.CipherUtilities.GetCipher(algorithm); cipherOne.Init(true, privateKeyParameters); byte[] signedData = cipherOne.DoFinal(clearData); var clientTwo = CipherUtilities.GetCipher(algorithm); clientTwo.Init(false, publicKeyInfoParameters); var clearDataTwo = clientTwo.DoFinal(signedData); Assert.IsTrue(Convert.ToBase64String(clearData) == Convert.ToBase64String(clearDataTwo)); 
+1
source

Source: https://habr.com/ru/post/956742/


All Articles