C#.Net 中的 3DES 密钥大小很重要 [英] 3DES Key Size Matter in C#.Net

查看:14
本文介绍了C#.Net 中的 3DES 密钥大小很重要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在 c#.NET 中运行良好

byte[] key = Encoding.ASCII.GetByte("012345678901234567890123");//24个字符byte[] plainText = Encoding.ASCII.GetBytes("lasaa");TripleDES des = TripleDES.Create();des.Key = 键;des.Mode = CipherMode.CBC;ICryptoTransform ic = des.CreateEncryptor();byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);MessageBox.Show(UTF8Encoding.UTF8.GetString(enc));

我对上述问题的疑问是...

  1. 如何指定 KeySize?如果我使用 des.KeySize= 128192256 它给出

<块引用>

指定的密钥不是此算法的有效大小

  1. 如果我通过添加更多字符来更改键中的字符长度(例如:40 个字符).它给出了错误

<块引用>

指定的密钥不是此算法的有效大小

我想知道为什么会这样?

解决方案

3DES 密钥的长度为 128 或 192 位.请注意,在内部,算法将仅使用这 128(分别为 192)位中的 112(分别为 168)位;然而,作为编码成字节、存储和交换的密钥本身必须具有 16 或 24 个字节的长度.尝试设置不具有这两种长度之一的密钥会触发错误,您在尝试使用 40 字节密钥时会观察到该错误.

您不应该尝试设置密钥大小":您在设置密钥时已经决定了.当您设置 TripleDES.Key 属性时,TripleDES 类会看到您给它一个 24 字节的密钥,因此将自己设置 KeySize 属性为 192.

(3DES 加密的输出是二进制的,而不是字符串的 UTF-8 编码.很有可能你的最终 UTF8Encoding.UTF8.GetString(enc) 会抗议.)

Below Code is Working Fine in c#.NET

byte[] key = Encoding.ASCII.GetByte("012345678901234567890123"); //24characters        
byte[] plainText = Encoding.ASCII.GetBytes("lasaa"); 
TripleDES des = TripleDES.Create();
des.Key = key;
des.Mode = CipherMode.CBC;
ICryptoTransform ic = des.CreateEncryptor();
byte[] enc = ic.TransformFinalBlock(plainText, 0, plainText.Length);
MessageBox.Show(UTF8Encoding.UTF8.GetString(enc));

My questions regarding above are...

  1. How can I specify KeySize? if i use des.KeySize= 128 or 192 or 256 it gives

Specified key is not a valid size for this algorithm

  1. If I change character length in key by adding more (ex:40 chars). It gives error

Specified key is not a valid size for this algorithm

I want to know why is this happen?

解决方案

A 3DES key has length 128 or 192 bits. Note that, internally, the algorithm will use only 112 (respectively 168) bits out of those 128 (respectively 192) bits; however, the key itself, as encoded into bytes, stored and exchanged, must have length 16 or 24 bytes. Trying to set a key which does not have one of those two lengths triggers an error, which you observe when you try to use a 40-byte key.

You should not try to set the "key size": you already decide that when you set the key. When you set the TripleDES.Key property, the TripleDES class sees that you give it a 24-byte key, and thus will set itself the KeySize property to 192.

(The output of 3DES encryption is binary, not UTF-8 encoding of a string. Chances are that your final UTF8Encoding.UTF8.GetString(enc) will protest.)

这篇关于C#.Net 中的 3DES 密钥大小很重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆