我必须使用两个密钥加密十六进制字符串。我的代码看起来像这样:
public byte[] TripleDes(byte[] inputBuffer, byte[] key)
{
byte[] result;
using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
using (MemoryStream stream = new MemoryStream())
using (CryptoStream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(), CryptoStreamMode.Write))
{
des.Key = key;
// des.KeySize = 128; <- wrong, overrides the values of the key
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.None;
cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
cryptoStream.FlushFinalBlock();
result = stream.ToArray();
}
return result;
}
设置的密钥是16个字节,由两部分组成:第一部分=要加密的密钥,第二部分=要解密的密钥。 inputBuffer是8个字节。当我像这样进行加密时,我的结果是16个字节而不是8个字节。我做错了什么?
答案 0 :(得分:0)
检查stream.Length
。
使用此函数将流更改为字节数组
public static byte[] ReadFully(Stream input)
{
if (input is MemoryStream)
{
return ((MemoryStream)input).ToArray();
}
else
{
return ReadFully(input);
}
}
答案 1 :(得分:0)
代码是正确的但订单没有。 &#34; TripleDESCryptoServiceProvider&#34;的配置实例发生在&#34; CreateEncryptor()&#34;方法是实例化的。所以正确的代码是:
public byte[] TripleDes(byte[] inputBuffer, byte[] key)
{
using (TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider())
{
des.Key = key;
des.Mode = CipherMode.ECB;
des.Padding = PaddingMode.None;
byte[] result;
using (MemoryStream stream = new MemoryStream())
using (CryptoStream cryptoStream = new CryptoStream(stream, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cryptoStream.Write(inputBuffer, 0, inputBuffer.Length);
cryptoStream.Flush();
//cryptoStream.FlushFinalBlock();
result = stream.ToArray();
}
return result;
}
}
&#34; Flush()&#34;和&#34; FlushFinalBlock()&#34;方法返回相同的结果,除了&#34; FlushFinalBlock&#34;有8个字节的额外数据,我不需要,我也不知道它是什么。