Kotlin Native (iOS),使用 CValuesRef 和 CCCrypt

MrA*_*sco 6 ios commoncrypto kotlin kotlin-native

我正在针对 iOS 的 Kotlin 多平台项目中研究 AES256 加密算法。

我检查了一些在纯 Kotlin 中实现这一点的现有库(例如krypto),但它们都不符合我对其余代码的要求(它们已经在 J​​VM 和 JS 中实现,因此无法更改) .

来自 iOS 背景,我决定使用CommonCrypto. 我从这里改编并移植了代码,但我坚持如何ULong通过引用传递CCCrypt函数并稍后检索其值。

我非常仔细地阅读了关于C InteropObjective-C Interop的 Kotlin 文档,但我找不到任何可以解释如何处理我的案例的示例。

特别是,我的问题是numBytesEncrypted变量(见下面的代码)。我需要通过引用CCCrypt函数来传递它,然后读取它的值以NSData使用正确的长度实例化结果。在 Objective-C/Swift 中,我会&在调用函数时为变量加上前缀。

但是,Kotlin 不支持&运算符。如果我从文档中理解正确,那么 Native 中的替换是CValueRef( docs ),所以我使用cValue速记来获取正确类型的引用(应该是size_t,又名。ULong)。

我试图以CValueRef两种方式实例化,就类型检查而言,这两种方式似乎都有效:

val numBytesEncrypted = cValue<ULongVar>()
// or
val numBytesEncrypted = cValue<ULongVarOf<size_t>>()
Run Code Online (Sandbox Code Playgroud)

然后我使用这段代码来获取函数执行后的值:

numBytesEncrypted.getPointer(MemScope()).pointed.value // <- this always returns 0.
Run Code Online (Sandbox Code Playgroud)

我测试了算法的其余部分,它完美地工作(加密值是预期的值,解密也有效),但是在不知道加密/解密数据的长度的情况下,我无法正确实例化NSData(以及结果ByteArray)。

这是完整的函数代码,包括我编写的扩展(基于此处找到的代码)以转换NSDataByteArray

private fun process(operation: CCOperation, key: ByteArray, initVector: ByteArray, data: ByteArray): ByteArray = memScoped {
    bzero(key.refTo(0), key.size.convert())

    val dataLength = data.size

    val buffSize = (dataLength + kCCBlockSizeAES128.toInt()).convert<size_t>()
    val buff = platform.posix.malloc(buffSize)

    val numBytesEncrypted = cValue<ULongVarOf<size_t>>() // <- or the other way above

    val status = CCCrypt(
        operation,
        kCCAlgorithmAES128,
        kCCOptionPKCS7Padding,
        key.refTo(0), kCCKeySizeAES256.convert(),
        initVector.refTo(0),
        data.refTo(0), data.size.convert(),
        buff, buffSize,
        numBytesEncrypted
    )

    if (status == kCCSuccess) {
        return NSData.dataWithBytesNoCopy(
                buff, 
                numBytesEncrypted.getPointer(MemScope()).pointed.value // <- this always returns the original value of the variable or 0.
        )
        .toByteArray()
    }

    free(buff)
    return byteArrayOfUnsigned(0)
}

fun NSData.toByteArray(): ByteArray = ByteArray(this@toByteArray.length.toInt()).apply {
    usePinned {
        memcpy(it.addressOf(0), this@toByteArray.bytes, this@toByteArray.length)
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,这是我用来验证代码的单元测试:

@Test
fun testAes256() {
    val initVector = ByteArray(16) { _ -> 0x00 }
    val key = ByteArray(32) { _ -> 0x00 }
    val data = ByteArray(1) { _ -> 0x01 }

    val expectedEncrypted = byteArrayOfUnsigned(0xFE, 0x2D, 0xE0, 0xEE, 0xF3, 0x2A, 0x05, 0x10, 0xDC, 0x31, 0x2E, 0xD7, 0x7D, 0x12, 0x93, 0xEB)

    val encrypted = process(kCCEncrypt, key, initVector, data)
    val decrypted = process(kCCDecrypt, key, initVector, encrypted)

    assertArraysEquals(expectedEncrypted, encrypted)
    assertArraysEquals(data, decrypted)
}

private fun assertArraysEquals(expected: ByteArray, actual: ByteArray) {
    if (expected.size != actual.size) asserter.fail("size is different. Expected: ${expected.size}, actual: ${actual.size}")
    (expected.indices).forEach { pos ->
        if (expected[pos] != actual[pos]) asserter.fail("entry at pos $pos different \n expected: ${debug(expected)} \n actual  : ${debug(actual)}")
    }
}
Run Code Online (Sandbox Code Playgroud)

先感谢您!

小智 0

改变

val numBytesEncrypted = cValue<ULongVarOf<size_t>>()
Run Code Online (Sandbox Code Playgroud)

val numBytes = cValue<ULongVar>().ptr
Run Code Online (Sandbox Code Playgroud)

你可以在你的代码中使用它

 NSData.dataWithBytesNoCopy(
                buff,
                numBytes.pointed.value
            ).toByteArray()
Run Code Online (Sandbox Code Playgroud)

在方法签名中描述的 dataOutMoved 是 kotlinx.cinterop.CValuesRef 类型。

我发现getPointer总是分配内存。

public abstract class CValues<T : CVariable> : CValuesRef<T>() {

    public override fun getPointer(scope: AutofreeScope): CPointer<T> {
        return place(interpretCPointer(scope.alloc(size, align).rawPtr)!!)
    }
Run Code Online (Sandbox Code Playgroud)
val numBytes = cValue<ULongVar>()
println("${numBytes.ptr.rawValue} ${numBytes.ptr.rawValue} ${numBytes.ptr.rawValue}")
0x7fa4a593bc18 0x7fa4a593ae28 0x7fa4a593b5d8


val numBytes = cValue<ULongVar>().ptr
println("${numBytes.rawValue} ${numBytes.rawValue} ${numBytes.rawValue}")
0x7fd5a287bfd8 0x7fd5a287bfd8 0x7fd5a287bfd8
Run Code Online (Sandbox Code Playgroud)