我正在使用crypto swift库,但是我必须迅速编写以下逻辑,因为我在kotlin中非常陌生,以了解语法。
任何线索都将不胜感激
fun decryptAES(data: ByteArray, secretKey: ByteArray): ByteArray {
try {
val byteBuffer = ByteBuffer.wrap(data)
val ivLength = byteBuffer.int
if (ivLength < 12 || ivLength >= 16) {
throw IllegalArgumentException("invalid iv length")
}
val iv = ByteArray(ivLength)
byteBuffer.get(iv)
val cipherText = ByteArray(byteBuffer.remaining())
byteBuffer.get(cipherText)
val encryptCipher = Cipher.getInstance("AES/GCM/PKCS5Padding")
encryptCipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(secretKey, "AES"), GCMParameterSpec(128, iv))
return encryptCipher.doFinal(cipherText)
} finally {
Arrays.fill(secretKey, 0.toByte())
}
}
答案 0 :(得分:0)
花了两天终于可以在Swift Hope中转换此代码,对其他人有帮助
func decryptCode(_ cipher:String, _ key:String)-> String{
var keyBytes: [UInt8] = []
var codeBytes: [UInt8] = []
var code = ""
if let keyData = NSData(base64Encoded:key, options: .ignoreUnknownCharacters) {
keyBytes = [UInt8](keyData as Data)
}
if let codeData = NSData(base64Encoded: cipher, options: .ignoreUnknownCharacters) {
codeBytes = [UInt8](codeData as Data)
}
// First 4 bytes define the IV length
// next 12 to 16 bytes are reserve for IV
//and remaining bytes are actual cipher text
debugPrint(codeBytes)
let sizeOfIV = 4
let ivUInt8Array = Array([UInt8](codeBytes)[0 ..< sizeOfIV])
let ivLength:Int = Int(ivUInt8Array.reduce(0, +))
if ivLength < 12 || ivLength >= 16{
return code
}
let codeBytescount = [UInt8](codeBytes).count
let remainingBytes = Array([UInt8](codeBytes)[sizeOfIV ..< codeBytescount])
let remainingBytescount = [UInt8](remainingBytes).count
let iv = Array([UInt8](remainingBytes)[0 ..< ivLength])
let cipher = Array([UInt8](remainingBytes)[ivLength ..< remainingBytescount])
do{
let gcm = GCM(iv: iv, mode: .combined)
let aes = try AES(key: keyBytes, blockMode: gcm, padding: .pkcs5)
IFLOG("aes created")
let decrypted = try aes.decrypt(cipher)
IFLOG("decrypted completed")
if let decryptedString = String(bytes: decrypted, encoding: .utf8) {
code = decryptedString
}
debugPrint(code)
}catch let error as AES.Error {
debugPrint(error.localizedDescription)
return code
} catch {
return code
}
return code
}