我知道这可能是一个常见问题,但我无法在任何地方找到答案。所以我有字节数组键和字节数组值,我需要生成新的8字节数组,该数组已在C#中用DES加密
答案 0 :(得分:4)
这是您的示例代码。记得用随机数据填充尾随零,记住写入的字节和DES参数:Key,IV。
祝福;)
using System.Security.Cryptography;
using System.IO;
namespace hash
{
public static class Program
{
static void Main(string[] args)
{
byte[] data = new byte[10000];
DES des = DES.Create();
int bytesWritten = 0;
data = Encode(data, des, out bytesWritten);
}
private static byte[] Encode(byte[] data, DES des, out int bytesWritten)
{
using (var input = new MemoryStream(data))
using (var output = new MemoryStream())
using (var csp = new DESCryptoServiceProvider())
using (var encStream = new CryptoStream(output, csp.CreateEncryptor(des.Key, des.IV), CryptoStreamMode.Write))
{
int length = 0;
byte[] buffer = new byte[256];
bytesWritten = 0;
while ((length = input.Read(buffer, 0, 256)) > 0)
{
if (length < 256)
{
byte[] pad = new byte[256];
using (var rng = RNGCryptoServiceProvider.Create())
{
rng.GetBytes(pad);
for (int i = 0; i < 256 - length; i++)
{
buffer[length + i] = pad[i];
}
}
encStream.Write(buffer, 0, length);
bytesWritten += length;
break;
}
encStream.Write(buffer, 0, 256);
bytesWritten += length;
}
return output.ToArray();
}
}
}
}
答案 1 :(得分:1)
这就是我要找的东西:D:D ......谢谢你:D
private static byte[] Encrypt(byte[] value, byte[] key)
{
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider
{
Mode = CipherMode.ECB,
Padding = PaddingMode.None
};
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);
cryptoStream.Write(value, 0, value.Length);
cryptoStream.Close();
return memoryStream.ToArray();
}