发布网友 发布时间:2022-04-24 16:57
共1个回答
热心网友 时间:2022-05-15 03:07
3DES加密过程为:C=Ek3(Dk2(Ek1(P)))
3DES解密过程为:P=Dk1(EK2(Dk3(C)))
具体的加/解密过程如图所示。
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();
}
}
K1、K2、K3决定了算法的安全性,若三个密钥互不相同,本质上就相当于用一个长为168位的密钥进行加密。多年来,它在对付强力攻击时是比较安全的。若数据对安全性要求不那么高,K1可以等于K3。在这种情况下,密钥的有效长度为112位。