C#AES加密字节数组

时间:2018-12-06 14:24:14

标签: c# encryption cryptography aes

我想加密字节数组。所以首先我在this site中尝试。

  • = 00000000000000000000000000000000000000
  • IV = 00000000000000000000000000000000000000
  • 输入数据 = 1EA0353A7D2947D8BBC6AD6FB52FCA84
  • 类型 = CBC

它计算得出

  • 加密的输出 = C5537C8EFFFCC7E152C27831AFD383BA

然后,我使用 System.Security.Cryptography 库进行计算。但这给了我不同的结果。在这种情况下,您能帮我吗?

代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using System.IO;
using System.Security.Cryptography;

namespace DesfireCalculation
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        byte key_no = 0x00;
        byte[] key = new byte[16] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
        byte[] IV = new byte[16] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        byte[] rndB = new byte[16] { 0x1E,0xA0,0x35,0x3A,0x7D,0x29,0x47,0xD8,0xBB,0xC6,0xAD,0x6F,0xB5,0x2F,0xCA,0x84 };

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                byte[] res=EncryptStringToBytes_Aes(BitConverter.ToString(rndB), key, IV);
                string res_txt = BitConverter.ToString(res);
                Console.WriteLine(res_txt);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: {0}", ex.Message);
            }
        }

        static byte[] EncryptStringToBytes_Aes(byte[] Data, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;
                aesAlg.Mode = CipherMode.CBC;
                aesAlg.BlockSize = 128;
                aesAlg.FeedbackSize = 128;
                aesAlg.KeySize = 128;

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                             swEncrypt.Write(Data);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return encrypted;    
        }
    }
}

2 个答案:

答案 0 :(得分:7)

该网站正在说明:

Input Data (It will be padded with zeroes if necessary.)

填充在密码学中真的很重要。

因此请确保您正在使用: aes.Padding = PaddingMode.Zeros;

在这种情况下,如果没有它,您将获得更长的填充字节结果。

编辑:对于实际情况,您可能应该保留默认值:PKCS#7。 @WimCoenen有一个很好的理由。检查评论。

您的代码的另一个问题是:您要先设置Key和IV,然后再设置其大小。

这是错误

        aesAlg.Key = Key;
        aesAlg.IV = IV;
        aesAlg.Mode = CipherMode.CBC;
        aesAlg.BlockSize = 128;
        aesAlg.FeedbackSize = 128;
        aesAlg.KeySize = 128;

这是正确的订单:

        aesAlg.Mode = CipherMode.CBC;
        aesAlg.KeySize = 128;
        aesAlg.BlockSize = 128;
        aesAlg.FeedbackSize = 128;
        aesAlg.Padding = PaddingMode.Zeros;
        aesAlg.Key = key;
        aesAlg.IV = iv;

代码的另一个问题是您正在使用 StreamWriter 写入加密流:

using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
    //Write all data to the stream.
    swEncrypt.Write(Data);
}

StreamWriter 可能会弄乱一切。它专门用于编写特殊编码的文本。

在下面的代码中查看适用于您的情况的我的实现。

public class AesCryptographyService 
{
    public byte[] Encrypt(byte[] data, byte[] key, byte[] iv)
    {
        using (var aes = Aes.Create())
        {
            aes.KeySize = 128;
            aes.BlockSize = 128;
            aes.Padding = PaddingMode.Zeros;

            aes.Key = key;
            aes.IV = iv;

            using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
            {
                return PerformCryptography(data, encryptor);
            }
        }
    }

    public byte[] Decrypt(byte[] data, byte[] key, byte[] iv)
    {
        using (var aes = Aes.Create())
        {
            aes.KeySize = 128;
            aes.BlockSize = 128;
            aes.Padding = PaddingMode.Zeros;

            aes.Key = key;
            aes.IV = iv;

            using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
            {
                return PerformCryptography(data, decryptor);
            }
        }
    }

    private byte[] PerformCryptography(byte[] data, ICryptoTransform cryptoTransform)
    {
        using (var ms = new MemoryStream())
        using (var cryptoStream = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
        {
            cryptoStream.Write(data, 0, data.Length);
            cryptoStream.FlushFinalBlock();

            return ms.ToArray();
        }
    }
}

var key = new byte[16] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
var iv = new byte[16] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
var input = new byte[16] { 0x1E,0xA0,0x35,0x3A,0x7D,0x29,0x47,0xD8,0xBB,0xC6,0xAD,0x6F,0xB5,0x2F,0xCA,0x84 };

var crypto = new AesCryptographyService();

var encrypted = crypto.Encrypt(input, key, iv);
var str = BitConverter.ToString(encrypted).Replace("-", "");
Console.WriteLine(str);

它将输出结果:

C5537C8EFFFCC7E152C27831AFD383BA

与您所引用的网站上的相同:

image

编辑:

我更改了您的功能,因此它将输出正确的结果:

static byte[] EncryptStringToBytes_Aes(byte[] data, byte[] key, byte[] iv)
{
    // Check arguments.
    if (key == null || key.Length <= 0)
        throw new ArgumentNullException("key");
    if (iv == null || iv.Length <= 0)
        throw new ArgumentNullException("iv");
    byte[] encrypted;

    // Create an Aes object
    // with the specified key and IV.
    using (Aes aesAlg = Aes.Create())
    {
        aesAlg.Mode = CipherMode.CBC;
        aesAlg.KeySize = 128;
        aesAlg.BlockSize = 128;
        aesAlg.FeedbackSize = 128;
        aesAlg.Padding = PaddingMode.Zeros;
        aesAlg.Key = key;
        aesAlg.IV = iv;

        // Create an encryptor to perform the stream transform.
        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

        // Create the streams used for encryption.
        using (MemoryStream msEncrypt = new MemoryStream())
        {
            using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
            {
                csEncrypt.Write(data, 0, data.Length);
                csEncrypt.FlushFinalBlock();

                encrypted = msEncrypt.ToArray();
            }
        }
    }

    // Return the encrypted bytes from the memory stream.
    return encrypted;    
}

答案 1 :(得分:0)

输入数据不同,因此结果也不同。 在网站上,您的纯文本为“ C5537C8EFFFCC7E152C27831AFD383BA”,代码中为 'B969FDFE56FD91FC9DE6F6F213B8FD1E'