【发布时间】:2019-05-08 06:35:09
【问题描述】:
我想加密字节数组。所以首先我在this site 尝试一下。
- 键 = 00000000000000000000000000000000
- IV = 00000000000000000000000000000000
- 输入数据 = 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;
}
}
}
【问题讨论】:
-
为什么要将输入的字节数组转换成字符串?
-
@Magnus 我在这里找到了例子docs.microsoft.com/en-us/dotnet/api/…
-
对我来说它给了 A2E4E50D343BEA0A222B643A48E37644
-
@Magnus 我更改为字节数组的功能。这解决了返回长度数据的长度问题。但它仍然与示例不同。
-
@eocron 感谢您的关注。每次都有不同的结果吗?
标签: c# encryption cryptography aes