3des算法源码

2023-01-31 01:01:05 des 算法 源码
using System;
using System.Text;
using System.io;
using System.Security.Cryptography;

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

  string txtEncrypted = EncryptString("1111");
  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();
}
}


3DES(即Triple DES)是DES向AES过渡的加密算法(1999年,NIST将3-DES指定为过渡的加密标准),是DES的一个更安全的变形。它以DES为基本模块,通过组合分组方法设计出分组加密算法,其具体实现如下:设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的密钥,P代表明文,C代表密表,这样,

3DES加密过程为:C=Ek3(Dk2(Ek1(P)))

3DES解密过程为:P=Dk1((EK2(Dk3(C)))

具体的加/解密过程如图2所示。K1、K2、K3决定了算法的安全性,若三个密钥互不相同,本质上就相当于用一个长为168位的密钥进行加密。多年来,它在对付强力***时是比较安全的。若数据对安全性要求不那么高,K1可以等于K3。在这种情况下,密钥的有效长度为112位。

相关文章