在C#.NET 3DES密钥大小物质 [英] 3DES Key Size Matter in C#.Net

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

问题描述

下面code是工作的罚款在C#.NET

 字节[]键= Encoding.ASCII.GetByte(012345678901234567890123); // 24characters
字节[] =明文Encoding.ASCII.GetBytes(lasaa);
TripleDes的DES = TripleDES.Create();
des.Key =键;
des.Mode = CipherMode.CBC;
ICryptoTransform的IC = des.CreateEncryptor();
字节[] = ENC ic.TransformFinalBlock(明文,0,plainText.Length);
MessageBox.Show(UTF8Encoding.UTF8.GetString(ENC));

我的上述关于问题......


  1. 如何指定密钥长度?如果我使用 des.KeySize = 128 192 256 它给


  

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



  1. 如果我通过增加更多的(例如:40个字符)更改字符长度的密钥。它给误差


  

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


我想知道为什么是这样呢?


解决方案

一个3DES密钥长度为128或192位。需要注意的是,内部的,算法将仅使用112(分别为168)位掉那些128(分别为192)的比特;然而,密钥本身,烯coded进入字节,储存和交换,必须具有长度为16或24个字节。试图设置不具有这两种长度的一个关键触发一个错误,当您尝试使用40字节的密钥,你观察到。

您不应该尝试设置密钥大小:你已经决定,当你设置的关键。当您设置 TripleDES.Key 属性,则 TripleDes的类看到你给它一个24字节的密钥,因此,将密钥长度属性设置本身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天全站免登陆