iOS CryptoKit AES-GCM 是否可以使用少于 12 字节的随机数?

iOS CryptoKit AES-GCM is it possible to use a nonce with fewer than 12 bytes?

我正在尝试与使用 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 字节的随机数会导致它抛出错误。我尝试用备用的 0'ed 8 字节填充随机数:

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

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

我找到了适合我的解决方案。

我使用了优秀的 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))