C# 3DES解密,32位密钥的问题

曦钺 2017-08-07 04:10:24
这样的,3DES密钥:D02DAC6052868AA54537842CDD3B9BEA
加密后的数据为:271AC12BAED4E1190296E7B92D8E5C85
解密后的数据为:08123456780000000000000000000000

我查了一些资料解析会报:不正确的数据。\r\n

public static string Decrypt3Des(string aStrString, string aStrKey, CipherMode mode = CipherMode.ECB, string iv = "12345678")
{
try
{
var des = new TripleDESCryptoServiceProvider
{
Key = Convert.FromBase64String(aStrKey),
Mode = mode,
Padding = PaddingMode.PKCS7
};
if (mode == CipherMode.CBC)
{
des.IV = Encoding.UTF8.GetBytes(iv);
}
var desDecrypt = des.CreateDecryptor();
var result = "";
byte[] buffer = Encoding.UTF8.GetBytes(aStrString);
var bytResult = desDecrypt.TransformFinalBlock(buffer, 0, buffer.Length);
result = Encoding.UTF8.GetString(bytResult);
return result;
}
catch (Exception e)
{
return string.Empty;
}
}

这是网上大神的代码,改了一下 Key = Convert.FromBase64String(aStrKey), 这地方原本是 Encoding.UTF8.GetBytes
不改会保长度的错。

这段代码看起来也有的地方不懂,
var bytResult = desDecrypt.TransformFinalBlock(buffer, 0, buffer.Length);
到这的地方buffer 只有24位了,原本的长度是32未的,是被截掉了嘛,


求大神帮忙解惑,或者给能出结果的代码让我瞻仰一下。
...全文
1008 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
长度不一样,肯定解不出来
曦钺 2017-08-08
  • 打赏
  • 举报
回复
自己顶一下,求助各位大神
曦钺 2017-08-07
  • 打赏
  • 举报
回复
引用 2 楼 starfd 的回复:
ECB是没有IV的,CBC才有,另外几种加密方式不熟悉
这个我知道的,用ECB的模式,就是密钥长度有问题,到后面报;不正确的数据。\r\n的错
曦钺 2017-08-07
  • 打赏
  • 举报
回复
引用 1 楼 starfd 的回复:
        static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            return returnBytes;
        }
key和data用16进制转成byte,结果加密出来结果比你长多了,但前面部分一样
var key = strToToHexByte("D02DAC6052868AA54537842CDD3B9BEA");
var data = strToToHexByte("08123456780000000000000000000000");
//用的CipherMode.ECB, PaddingMode.PKCS7
那倒过来解密呢,你的方法能正常解出加密前的数据吗
  • 打赏
  • 举报
回复
ECB是没有IV的,CBC才有,另外几种加密方式不熟悉
  • 打赏
  • 举报
回复
        static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}

key和data用16进制转成byte,结果加密出来结果比你长多了,但前面部分一样
var key = strToToHexByte("D02DAC6052868AA54537842CDD3B9BEA");
var data = strToToHexByte("08123456780000000000000000000000");
//用的CipherMode.ECB, PaddingMode.PKCS7

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧