简体   繁体   English

从base64字符串获取IV和秘密密钥

[英]Get IV and secret key from base64 string

I am working with crypto swift library But I have to write below logic in swift as I am very new in kotlin to understand the syntax. 我正在使用crypto swift库工作,但是我必须在swift中编写以下逻辑,因为我在Kotlin中非常陌生,以了解语法。

Any leads would be greatly appreciated 任何线索将不胜感激

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())
  }
}

After spending 2 days finally I am able to convert this code in Swift Hope this helps others 花费了两天后,我终于能够在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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM