综合

img wskyo

MD5加密解密

发表于2004/10/21 9:31:00  2247人阅读

using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;

class Class1
{
 static void Main()
 {
  Console.WriteLine("Encrypt String...");
  txtKey = "tkGGRmBErvc=";//设置加密Key
  btnKeyGen();
  Console.WriteLine("Encrypt Key :{0}",txtKey);
  txtIV = "Kl7ZgtM1dvQ=";//设置加密IV
  btnIVGen();
  Console.WriteLine("Encrypt IV :{0}",txtIV);
  Console.WriteLine();

  string txtEncrypted = EncryptString("测试");
  Console.WriteLine("Encrypt String : {0}",txtEncrypted);

  string txtOriginal = DecryptString(txtEncrypted);
  Console.WriteLine("Decrypt String : {0}",txtOriginal);
 }

 private static SymmetricAlgorithm mCSP;
 private static string txtKey;
 private static string txtIV;

 private static void btnKeyGen()
 {
  mCSP = SetEnc();

  byte[] byt2 = Convert.FromBase64String(txtKey);

  mCSP.Key = byt2;
 }

 private static void btnIVGen()
 {
  byte[] byt2 = Convert.FromBase64String(txtIV);

  mCSP.IV = byt2;
 }

 private static string EncryptString(string Value)
 {
  ICryptoTransform ct;
  MemoryStream ms;
  CryptoStream cs;
  byte[] byt;

  ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);

  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());
 }

 private static string DecryptString(string Value)
 {
  ICryptoTransform ct;
  MemoryStream ms;
  CryptoStream cs;
  byte[] byt;

  ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);

  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());
 }

 private static SymmetricAlgorithm SetEnc()
 {
  return new DESCryptoServiceProvider();
 }
}

阅读全文
0 0

相关文章推荐

img
取 消
img