得益于bouncycaSTLe的库,我需要为iOS(快速)重新实现针对Android应用(kotlin)执行的加密操作。
Kotlin代码为:

val mac = "9D3391051A4E774B".hexStringToByteArray()
val macKey = "89D7B23D500D492FA01DC53B44864AB8".hexStringToByteArray()
val cipheredData = "E77A914D5C94A04B6D8E10BA7A56A015AC2C40167F867A97B6349F29F3100D6D".hexStringToByteArray()

var macBlock = CBCBlockCipherMac(AESEngine(), ISO7816d4Padding())
macBlock.init(KeyParameter(macKey))
macBlock.update(cipheredData, 0, cipheredData.size)
var output = ByteArray(8)
macBlock.doFinal(output, 0)

if(output.toHex() == mac.toHex()) {
    print("equals !!")
} else {
    print("not equals : ${output.toHex()}")
}

此代码有效,从输出中找到的mac与原始的“mac”属性相同。

我尝试通过以下代码使用swift库CryptoSwift:
let mac = Data(hex: "9D3391051A4E774B")
let macKey = Data(hex: "89D7B23D500D492FA01DC53B44864AB8")
let cipheredData = Data(hex: "E77A914D5C94A04B6D8E10BA7A56A015AC2C40167F867A97B6349F29F3100D6D")

do {
    var output = try CBCMAC(key: macKey.bytes).authenticate(cipheredData.bytes)
    checkOutput(mac: mac, output: output)
} catch {
    debugPrint("Exception \(error)")
}

但这是行不通的。 CryptoSwift的CBCMAC类背后的算法与充气城堡的CBCBlockCipherMac的想法不同。

我也尝试过使用Apple的CommonCrypto库,但没有CBCMAC身份验证,只有HMAC。我没有找到任何针对iOS平台轻松进行CBC-MAC身份验证的方法。

最佳答案

我找到了一个解决方案,在CryptoSwift类中开发了真正的CBC-MAC加密:

public func authenticate(_ cipheredBytes: Array<UInt8>, padding: Padding, blockSize: Int) throws -> Array<UInt8> {
    var inBytes = cipheredBytes
    bitPadding(to: &inBytes, blockSize: blockSize)
    let blocks = inBytes.chunked(into: blockSize)

    var lastBlockEncryptionResult : [UInt8] = CBCMAC.Zero
    try blocks.forEach { (block) in
        let aes = try AES(key: Array(key), blockMode: CBC(iv: lastBlockEncryptionResult), padding: padding)
        lastBlockEncryptionResult = try aes.encrypt(block)
    }

    return lastBlockEncryptionResult
}

使用我的初始参数调用此命令可得出答案:

9d3391051a4e774b7572fb9bca51dc51

因此,前8位是好的位。

08-04 10:04