【发布时间】:2020-08-03 12:33:15
【问题描述】:
我想使用 Apples CryptoKit 将加密数据从运行 kotlin 应用程序的服务器发送到 iOS 应用程序。
我在初始化AES.GCM.SealedBox 和解密数据时遇到问题。一般来说,我不明白 Sealboxstag 的用途。
所以首先是 Kotlin 方面:
fun ByteArray.aesEncrypt(key: ByteArray, iv: ByteArray? = null): ByteArray {
return aes(this, Cipher.ENCRYPT_MODE, key, iv)
}
private fun aes(self: ByteArray, mode: Int, key: ByteArray, iv: ByteArray?): ByteArray{
val skey = SecretKeySpec(key, "AES")
val cipher = Cipher.getInstance("AES/GCM/PKCS5Padding")
println("MODE: ${cipher.algorithm}")
iv?.let {
cipher.init(mode, skey, GCMParameterSpec(128, iv))
}?: run{
cipher.init(mode, skey)
}
val cipherText = ByteArray(cipher.getOutputSize(self.size))
var ctLength = cipher.update(self, 0, self.size, cipherText, 0)
ctLength += cipher.doFinal(cipherText, ctLength)
return cipherText
}
iOS:
static private let privateKey = SymmetricKey(size: SymmetricKeySize.bits128)
static private let nonce = AES.GCM.Nonce()
static func decrypt(_ data: Data) -> Data {
print("Encrypted data \(data.bytes)")
print("Private key: \(privateKey.data.bytes)")
print("Nonce: \(Array(nonce))")
let boxToDecrypt = try! AES.GCM.SealedBox(combined: data)
let plainData = try! AES.GCM.open(boxToDecrypt, using: privateKey)
return plainData
}
当然,双方都有相同的密钥和 iv/nonce。我遇到的错误消息是:
CryptoKit.CryptoKitError.incorrectParameterSize
排队:
let boxToDecrypt = try! AES.GCM.SealedBox(combined: data)
编辑我: 额外的有效载荷信息:
服务器(Kotlin):
Not encrypted: 0,0,0,0,0,0,0,1
Key: 169,152,60,154,77,50,10,63,60,166,48,129,1,68,219,250
IV: 134,191,34,26,111,146,17,54,31,212,74,14
Encrypted: 158,154,213,95,227,42,155,199,169,183,166,67,139,154,198,172,229,82,34,30,40,188,41,73
客户端(iOS):
Encrypted data [158, 154, 213, 95, 227, 42, 155, 199, 169, 183, 166, 67, 139, 154, 198, 172, 229, 82, 34, 30, 40, 188, 41, 73]
Nonce: [134, 191, 34, 26, 111, 146, 17, 54, 31, 212, 74, 14]
Private key: [169, 152, 60, 154, 77, 50, 10, 63, 60, 166, 48, 129, 1, 68, 219, 250]
【问题讨论】:
-
为什么不直接通过 TLS 传输数据?它易于使用且安全。
-
我希望至少可以指出 what 参数导致了这种情况以及代码的哪一行。
-
@MaartenBodewes 嘿,我用一些有效载荷信息更新了我的帖子。
-
在 Java / Kotlin 中,标签会自动添加到密文的末尾。默认为 128 位或 16 字节。可能是斯威夫特密封盒使用了不同的顺序。然而,当我发布一个关于此的问题时,fanbois 投票将其遗忘,所以我只能发布此评论。 Apple 加密文档似乎需要处于已弃用的水平。
-
@MaartenBodewes Mhhh 好的 - 但谢谢 :)
标签: swift kotlin encryption aes apple-cryptokit