0

我正在尝试与使用 AES-GCM 和 4 字节随机数(UInt32)的现有设备进行交互。这是一个简单的增量计数器,每次操作发生时都会增加:

var cryptoCounter: UInt32 = 0

然后我尝试对其进行加密并检索如下值:

let key = SymmetricKey(data: sharedKey) // This is a 32-byte key.
let nonceData = withUnsafeBytes(of: cryptoCounter.bigEndian, Array.init) // Convert UInt32 to 4-byte data.
let nonce = try! AES.GCM.Nonce(data: Data(nonceData)) // This throws an invalid parameter size exception.
let encrypted = try! AES.GCM.seal(serialized, using: key, nonce: nonce)

但是,AES.GCM.Nonce少于 12 字节的情况下不起作用,因此 4 字节的 nonce 会导致它抛出错误。我试过用一个备用的 0'ed 8 字节填充随机数:

let nonceData = [0, 0, 0, 0, 0, 0, 0, 0] + withUnsafeBytes(of: cryptoCounter.bigEndian, Array.init)

但是设备拒绝了加密值,所以我认为这是不正确的。如果有人对实现这个 Swift 的最佳方式有任何建议,那就太棒了!谢谢你。

4

1 回答 1

0

我想出了一个对我有用的解决方案。

我使用了出色的CryptoSwift库(撰写本文时在 GitHub 上有 7.8k 星):

let gcm = GCM(iv: withUnsafeBytes(of: cryptoCounter.bigEndian, Array.init), mode: .detached)
let aes = try! AES(key: [UInt8](sharedKey), blockMode: gcm, padding: .noPadding)
let encrypted = try! aes.encrypt([UInt8](serialized))
于 2020-06-10T18:41:17.177 回答