6

我正在针对 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 中的替换是CValueRefdocs),所以我使用cValue简写来获取正确类型的 ref(应该是size_t,又名。ULong)。

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

val numBytesEncrypted = cValue<ULongVar>()
// or
val numBytesEncrypted = cValue<ULongVarOf<size_t>>()

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

numBytesEncrypted.getPointer(MemScope()).pointed.value // <- this always returns 0.

我测试了算法的其余部分,它运行良好(加密值是预期的值,解密也有效),但在不知道加密/解密数据的长度的情况下,我无法正确实例化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)
    }
}

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

@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)}")
    }
}

先感谢您!

4

1 回答 1

1

改变

val numBytesEncrypted = cValue<ULongVarOf<size_t>>()

val numBytes = cValue<ULongVar>().ptr

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

 NSData.dataWithBytesNoCopy(
                buff,
                numBytes.pointed.value
            ).toByteArray()

在描述的方法签名中,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)!!)
    }
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
于 2021-08-04T10:45:21.283 回答