我正在研究固件更新方案,该方案需要对固件映像进行端到端加密.目标设备是蓝牙低功耗芯片,硬件支持Blueooth Spec,AES-CCM中指定的加密技术.我们希望利用此硬件来最小化代码大小和速度,因此我们需要以构建硬件的格式加密固件映像.
因此,我正在尝试使用.NET的AesManaged class,以便我可以重现Bluetooth Spec(p 1547)中给出的数据样本,但我没有得到相同的输出.这是示例数据:
Payload byte length: 08
K: 89678967 89678967 45234523 45234523
Payload counter: 0000bc614e
Zero-length ACL-U Continuation: 0
Direction: 0
Initialization vector: 66778899 aabbccdd
LT_ADDR: 1
Packet Type: 3
LLID: 2
Payload: 68696a6b 6c6d6e6fB0: 494e61bc 0000ddcc bbaa9988 77660008
B1: 00190200 00000000 00000000 00000000
B2: 68696a6b 6c6d6e6f 00000000 00000000Y0: 95ddc3d4 2c9a70f1 61a28ee2 c08271ab
Y1: 418635ff 54615443 8aceca41 fe274779
Y2: 08d78b32 9d78ed33 b285fc42 e178d781T: 08d78b32
CTR0: 014e61bc 0000ddcc bbaa9988 77660000
CTR1: 014e61bc 0000ddcc bbaa9988 77660001S0: b90f2b23 f63717d3 38e0559d 1e7e785e
S1: d8c7e3e1 02050abb 025d0895 17cbe5fbMIC: b1d8a011
Encrypted payload: b0ae898a 6e6864d4
现在,我很高兴只是在没有身份验证的情况下使加密工作.我注意到MIC和加密有效载荷分别与S0和S1进行了T和Payload XOR,因此我的目标只是生成S0.我的理解是,我应该能够通过ECB使用密钥K来执行CTR0数组:
//I've tried a few endian-ness permutations of K, none work
byte[] sampleKey = { 0x23, 0x45, 0x23, 0x45, 0x23, 0x45, 0x23, 0x45,
0x67, 0x89, 0x67, 0x89, 0x67, 0x89, 0x67, 0x89};
byte[] sampleCtr0 = { 01, 0x4e, 0x61, 0xbc, 00, 00, 0xdd, 0xcc,
0xbb, 0xaa, 0x99, 0x88, 0x77, 0x66, 00, 00 };
byte[] encrypted;
using (AesManaged aesAlg = new AesManaged())
{
aesAlg.Mode = CipherMode.ECB; //CTR implemented as ECB w/ manually-incrementing counter
// Create an encrytor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(sampleKey, zeros); //zeros is a byte array of 16 0's
// 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(sampleCtr0);
}
encrypted = msEncrypt.ToArray();
}
}
}
我希望看到加密的S0,但我没有.怎么了?
最佳答案 事实证明使用StreamWriter是个问题.删除它并用csEncrypt.Write()替换它,我得到了我的预期输出.
我仍然不理解我的修复,所以我即将编辑这个问题,但看到问题可能与加密无关,我认为这将作为一个单独的问题更好地解决.或者,如果有人可以解释修复,我会更改已接受的答案.