public static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
public static string algorithmName = "des";
public static void GeneratorKey(string FilePath, SymmetricAlgorithm symmetricAlgorithm)
{
symmetricAlgorithm.GenerateKey();
byte[] keys = new byte[symmetricAlgorithm.Key.Length];
keys = symmetricAlgorithm.Key;
using (FileStream fs = new FileStream(FilePath, FileMode.Create))
{
fs.Write(keys, 0, keys.Length);
}
}
public static void Readkey(string filePath, SymmetricAlgorithm symmetricalgorithm)
{
byte[] keys = new byte[symmetricalgorithm.Key.Length];
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
fs.Read(keys, 0, keys.Length);
}
symmetricalgorithm.Key = keys;
}
public static string Encript(string data, string filePath)
{
byte[] data2 = System.Text.Encoding.UTF8.GetBytes(data);
SymmetricAlgorithm symmetrialgorithm = SymmetricAlgorithm.Create(algorithmName);
if (!File.Exists(filePath))
{
GeneratorKey(filePath, symmetrialgorithm);
}
Readkey(filePath, symmetrialgorithm);
symmetrialgorithm.IV = IV;
MemoryStream mem = new MemoryStream();
CryptoStream cs = new CryptoStream(mem, symmetrialgorithm.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(data2, 0, data2.Length);
cs.FlushFinalBlock();
cs.Close();
byte[] mems= mem.ToArray();
string encriptdata = Convert.ToBase64String(mems) ;
return encriptdata;
}
public static string Decript(string data, string filepath)
{
SymmetricAlgorithm symmtrialgorithm = SymmetricAlgorithm.Create(algorithmName);
Readkey(filepath, symmtrialgorithm);
byte[] data2 = System.Text.Encoding.UTF8.GetBytes(data);
symmtrialgorithm.IV = IV;
MemoryStream mem = new MemoryStream();
CryptoStream cs = new CryptoStream(mem, symmtrialgorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(data2,0,data2.Length);
//这里报错了
cs.FlushFinalBlock();
cs.Close();
byte[] mems = mem.ToArray();
string decriptdata = Convert.ToBase64String(mems);
return decriptdata;
}
拿豆来吧。确实你的解码是错误的。如下:
将解密方法改下:
public static string Decript(string data, string filepath) { byte[] data2= Convert.FromBase64String(data); SymmetricAlgorithm symmtrialgorithm = SymmetricAlgorithm.Create(algorithmName); Readkey(filepath, symmtrialgorithm);
//byte[] data2 = System.Text.Encoding.UTF8.GetBytes(data); symmtrialgorithm.IV = IV; MemoryStream mem = new MemoryStream(); CryptoStream cs = new CryptoStream(mem, symmtrialgorithm.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(data2, 0, data2.Length); //这里报错了 cs.FlushFinalBlock(); cs.Close(); byte[] mems = mem.ToArray(); //string decriptdata = Convert.ToBase64String(mems); string decriptdata = System.Text.Encoding.UTF8.GetString(mems); return decriptdata; }
虽然说第二天我就找好了错误,但是还是要感谢你
public static string Encript(string data, string filePath)
public static string Decript(string data, string filepath)
你这个两个方法在字符串处理上不对称。
能详细说说吗
C#加密解密代码网上可以百度到一大堆