asp.net c#中的加密和解密 [英] Encryption And Decryption in asp.net c#
本文介绍了asp.net c#中的加密和解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我正在使用这段代码来加密和解密密码,但是在解密部分中出现错误base-64 char数组或字符串的无效长度就行了byte [] cipherBytes = Convert.FromBase64String(cipherText);。
hello i am using this code to Encrypt and Decrypt password but giving error in decrypt Portion "invalid length for a base-64 char array or string" on line "byte[] cipherBytes = Convert.FromBase64String(cipherText);".
private string Encrypt(string clearText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
clearText = Convert.ToBase64String(ms.ToArray());
}
}
return clearText;
}
private string Decrypt(string cipherText)
{
string EncryptionKey = "MAKV2SPBNI99212";
byte[] cipherBytes = Convert.FromBase64String(cipherText);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
cipherText = Encoding.Unicode.GetString(ms.ToArray());
}
}
return cipherText;
}
请帮助...........
please help...........
推荐答案
请参阅解决方案的链接:
http://stackoverflow.com/questions/16858718/encryption-failing-with-error-invalid-length -for-a-base-64-char-array-or-string [ ^ ]
Refer the link for the solution:
http://stackoverflow.com/questions/16858718/encryption-failing-with-error-invalid-length-for-a-base-64-char-array-or-string[^]
string strKey = "12345@password.com";
try
{
string strEncrypt = Encrypt(strKey); //Encrypt1(HttpUtility.UrlEncode(strKey));
string strDecrypt = Decrypt(strEncrypt);//Decrypt1(HttpUtility.UrlDecode(strEncrypt));
if (strEncrypt == strDecrypt)
{
Response.Write("String Matched");
}
else
{
Response.Write("String Not Matched");
}
}
catch(Exception e1)
{
}
结果集::
Result Set::
strKey = "12345@password.com";
strEncrypt="Encrypted String";
strDecrypt="12345@password.com";
If facing Problem With the StringKey code..then try this.
Encrypt(HttpUtility.UrlEncode(strKey));
Decrypt(HttpUtility.UrlDecode(strEncrypt));
这篇关于asp.net c#中的加密和解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文