When I am trying to decrypt the encrypted string using C#, I am getting an error as below
Here is the HTML Razor anchor link code clicking on which, I am trying to decrypt it
<li>
<a class="ajax" href="/NexSignsPlugin/TemplateConfiguration?key=@crypto.EncryptStringAES(mTemplateConn.LicenseKey)&TemplateGUID=@mTemplateConn.TemplateGUID">
<i class="zmdi zmdi-edit"></i> Edit Template</a>
</li>
C# code of controller:
public ActionResult TemplateConfiguration(string key, Guid TemplateGUID, bool pv = false)
{
string licenseKey = utility.security.crypto.DecryptStringAES(key);
Areas.NexSigns2.ViewModels.TemplateConfigurationViewModel vm = new ViewModels.TemplateConfigurationViewModel();
vm.mTemplateLicenseKey = DBentity.TemplateLicenseKeyConnections.Where(x => x.LicenseKey == licenseKey && x.TemplateGUID == TemplateGUID).First();
vm.TemplateController = new AttributeController(vm.mTemplateLicenseKey.AttributeXML);
if (pv == true)
return PartialView(vm);
else
return View(vm);
}
C# class which decrypts the string:
public static string DecryptStringAES(string cipherText)
{
// Declare the string used to hold
// the decrypted text.
string plaintext = null;
try
{
// generate the key from the shared secret and the salt
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);
// Create the streams used for decryption.
//getting error here
byte[] bytes = Convert.FromBase64String(cipherText);
//code removed for clarity
}
}
So what's the error and how can I resolve it? any help is appreciated
You simply need to encode your url, base64 encoding uses some characters which must be encoded if they're part of a querystring (namely
+
and /
). If the string isn't correctly encoded then you won't be able to decode it successfully at the other end, hence the errors.
You need to use the HttpUtility.UrlEncode
method directly to encode the string which you are passing to controller, to get the properly encoded string, so your code will be as below
<li>
<a class="ajax" ajax-target="#content" href="/NexSigns2/NexSignsPlugin/TemplateConfiguration?key=@HttpUtility.UrlEncode(crypto.EncryptStringAES(mTemplateConn.LicenseKey))&TemplateGUID=@mTemplateConn.TemplateGUID">
<i class="zmdi zmdi-edit"></i> Edit Template</a>
</li>
that's it.
You need to simply Encode your URL
So to encode url you can use HttpUtility.UrlEncode
so here is the sample C# code for it.
string cryptostring = EncryptStringAES(MySecretString);
string URL = HelperFunction.ToAbsoluteUrl("~/URL?QString=" + HttpUtility.UrlEncode(cryptostring));
This should help
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly