c# - 使用安全 key C# 进行 DES 编码

标签 c# .net encryption des

我知道这可能是一个常见问题,但我无法在任何地方找到答案。所以我有字节数组键和字节数组值,我需要生成新的 8 字节数组,该数组已在 C# 中用 DES 加密

最佳答案

这是您的示例代码。记住用随机数据填充 trailig 零,记住写入的字节和 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();
            }
        }
    }
}

关于c# - 使用安全 key C# 进行 DES 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4723322/

相关文章:

java - 如何将 java (Android) 加密参数转换为 iOS 加密?

c# - IISExpress 是单线程的吗?

javascript - 从浏览器到桌面应用程序的信号

c# - 线程池在 .NET REST 服务实现中的使用

c# - 使用 NetComm dll 发送屏幕截图到主机

encryption - 如何禁用 openssl 引擎?

c - 使用替换密码的加密不会生成有效的 ASCII 输出

c# - 有没有更简洁的方法来检查对象是否为假?

.net - 从两个(不同的)Excel 文件 .NET 中选择

.net - 从 iPhone 上传图像/音频到服务器无法发送大图像