视频上看到的例子,对着视频打了一遍代码,测试失败,上网搜索后改了一下测试成功,不知道为什么跟视频上打的一样的代码视频上测试的正确而我的测试出错的,先不管了,先记下来,以备后用!
测试代码:
测试效果:
/// <summary>字符串加解密 /// /// </summary> public class Encrypt { private SymmetricAlgorithm mCSP; private const string CIV = "oo*/^fsA"; //密钥, 只能是8位 private const string CKEY = "f123$dew"; //初始化向量, 只能是8位 public Encrypt() { mCSP = new DESCryptoServiceProvider(); } /// <summary>加密字符串 /// /// </summary> /// <param name="Value"></param> /// <returns></returns> public string EncryptString(string Value) { ICryptoTransform ct; MemoryStream ms; CryptoStream cs; byte[] byt; // 这里视频上用的是Convert.FromBase64String(CKEY/CIV),但是我用的话总是出现错误,什么大小不对 ct = mCSP.CreateEncryptor(Encoding.ASCII.GetBytes(CKEY), Encoding.ASCII.GetBytes(CIV)); byt = Encoding.UTF8.GetBytes(Value); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return Convert.ToBase64String(ms.ToArray()); } /// <summary>解密字符串 /// /// </summary> /// <param name="Value"></param> /// <returns></returns> public string DecryptString(string Value) { ICryptoTransform ct; MemoryStream ms; CryptoStream cs; byte[] byt; ct = mCSP.CreateDecryptor(Encoding.ASCII.GetBytes(CKEY), Encoding.ASCII.GetBytes(CIV)); byt = Convert.FromBase64String(Value); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return Encoding.UTF8.GetString(ms.ToArray()); } }
测试代码:
static void Main(string[] args) { Console.Write("请输入要加密的字符串:"); string str = Console.ReadLine(); Console.WriteLine("加密后:" + new Encrypt().EncryptString(str)); Console.ReadLine(); Console.Write("请输入要解密的字符串:"); string str2 = Console.ReadLine(); Console.WriteLine("解密后:" + new Encrypt().DecryptString(str2)); Console.ReadLine(); }
测试效果: