问题
I have a string that I want to decrypt at runtime in my C# WPF Application.
I thought I could use the following code:
using System.Text;
using System.Web;
using System.Web.Security;
[Test]
public void Encrypt()
{
var text = "This is my string";
var stream = Encoding.UTF8.GetBytes(text);
var encodedValue = MachineKey.Protect(stream);
var result = HttpServerUtility.UrlTokenEncode(encodedValue);
}
[Test]
public void Decrypt()
{
var text = "ZG1CrjMgyq5O1krnBxoYM5rXH071xVxFnhC3xTTBiJ05Uy4msSe0jonP-ayFuChh_M6EaEhMif_j7i8yUSQ4Pkc63moEbvq34hMZGfYkazo1";
var stream = HttpServerUtility.UrlTokenDecode(text);
var decodedValue = MachineKey.Unprotect(stream);
var result = Encoding.UTF8.GetString(decodedValue);
}
However I get a
CryptographicException: Error occurred during a cryptographic operation
error when running the Unprotect command in my WPF app. Any ideas?
-- If the above code is only meant to work in a web app (ie. not in WPF), why does it work when called in a Unit Test?
回答1:
Try these solution, hope it would work:
1.Have you defined "machineKey" entry for encrypt/decrypt in your web.config? If not then define it.
2.Just clear all of browser's cookies and cache data.
3.If you are using forms auth. you can signout when you catch the exception and allow your users to login and create a valid cookie(add it in your global.asax)
catch (CryptographicException cex)
{
FormsAuthentication.SignOut();
}
回答2:
I understand now that this pattern wouldn't work for me anyway.. Seeing as I'm using a client application, anyone could inspect the code in my assembly and decrypt the string.
I'm going to do the following instead:
- Use a separate console app and private key to encrypt my string.
- Create an Azure function that has the private key and can decrypt strings.
- Call the Azure function via SSL from my client WPF app to decrypt the string.
来源:https://stackoverflow.com/questions/50712196/cryptographicexception-error-occurred-during-a-cryptographic-operation