我正在尝试做一个练习,其中包括使用给定的共享 key 解密给定的加密 session key 。我已经解密了 session key 并在屏幕上打印了字节数组。 (当我运行该程序时,会打印出相同的结果)。
然后为了检查我的工作,我尝试再次加密解密的 session key (显然使用相同的共享 key )但结果始终不同,什么时候应该还给我原始的加密 session key 。
我不明白是我的错....
谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace Crypto
{
public class Program
{
static void Main(string[] args)
{
//Shared Master Key
byte[] mkByteArray = { 0x12, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x23 };
//Encrypted Session Key
byte[] eskByteArray = { 0x4a, 0x4d, 0xe6, 0x87, 0x82, 0x47, 0xd3, 0x7b };
PrintByteArray(eskByteArray);
DES des = new DESCryptoServiceProvider();
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.None;
des.Key = mkByteArray;
ICryptoTransform ct1 = des.CreateDecryptor();
byte[] resultArray1 = ct1.TransformFinalBlock(eskByteArray, 0, eskByteArray.Length);
des.Clear();
PrintByteArray(resultArray1);
ICryptoTransform ct2 = des.CreateEncryptor();
byte[] resultArray2 = ct2.TransformFinalBlock(resultArray1, 0, resultArray1.Length);
des.Clear();
PrintByteArray(resultArray2);
}
//-----Method to print the byte array on screen-----
public static void PrintByteArray(byte[] bytes)
{
var sb = new StringBuilder("new byte[] { ");
foreach (var b in bytes)
{
sb.Append(b + ", ");
}
sb.Append("}");
Console.WriteLine(sb.ToString());
}
}
}
请您参考如下方法:
我发现了你的问题,但现在我正在检查它发生的确切原因。
你在加密和解密之间调用des.Clear();,如果你不这样做,输入和输出是一样的。
来自 Msdn :
When called, the Clear method overwrites all sensitive data within the object with zeros
因此,您的 DES 对象中的主 key 被设置为零,这就是您的输出不同的原因。
