用C#加密/解密阿拉伯字符串
本文关键字:阿拉伯 字符串 解密 加密 | 更新日期: 2023-09-27 18:28:51
如何使用这些方法在C#中加密/解密阿拉伯字符串????当我试图解密任何阿拉伯字符串时,它的返回"???"问号。。如何通过此代码使用编码UTF8??请帮忙。。提前感谢
public static string Encrypt(string pDataToEncrypt)
{
ASCIIEncoding textConverter = new ASCIIEncoding();
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] toEncrypt;
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
toEncrypt = textConverter.GetBytes(pDataToEncrypt);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
return Convert.ToBase64String(msEncrypt.GetBuffer(), 0, (int)msEncrypt.Length);
}
public static string Decrypt(string pDataToDecrypt)
{
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] fromEncrypt;
//Encoding asciiEncoding = Encoding.ASCII;
fromEncrypt = Convert.FromBase64String(pDataToDecrypt);
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);
MemoryStream msDecrypt = new MemoryStream(fromEncrypt, 0, fromEncrypt.Length);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
StreamReader sr = new StreamReader(csDecrypt);
return sr.ReadToEnd();
}
使用UTF-8,您的代码应该是这样的:
public static string Encrypt(string pDataToEncrypt)
{
RijndaelManaged myRijndael = new RijndaelManaged();
ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor,CryptoStreamMode.Write);
byte[] toEncrypt = Encoding.UTF8.GetBytes(pDataToEncrypt);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
return Convert.ToBase64String(msEncrypt.GetBuffer(), 0, (int)msEncrypt.Length);
}
public static string Decrypt(string pDataToDecrypt)
{
RijndaelManaged myRijndael = new RijndaelManaged();
byte[] fromEncrypt = Convert.FromBase64String(pDataToDecrypt);
ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);
MemoryStream msDecrypt = new MemoryStream(fromEncrypt, 0, fromEncrypt.Length);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[fromEncrypt.Length];
int decryptedByteCount = csDecrypt.Read(plainTextBytes, 0, plainTextBytes.Length);
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}