提问者:小点点

iOS SecKeyCopyKeyExchangeResult share dInfo参数


我试图使用SecKeyCopyKeyExchangeResult函数从我的本地私钥和接收到的服务器公钥中获取共享秘密。共享密钥生成成功,我能够使用AES加密解密输入消息不久前,服务器开发人员决定将KDF添加到密钥生成流程中。我开始调查如何在iOS方面做到这一点,并发现有一个特殊的参数静态让share dInfo: SecKeyKeyExchangeParameter要说留档很差,什么也别说…我只发现了标题中的描述

@常量kSecKeyKeyExchangeParameterSharedInfo包含CFDataRef以及KDF的附加共享信息(密钥派生函数)。

如果有人用过这个,请帮忙。服务器使用这个参数在scala上生成KDF

private def concatWithKdf(secretKey: SecretKey) = {
    val bytes = new Array[Byte](SECRET_KEY_LENGTH)
    val digest = new SHA256Digest();
    val kdf1BytesGenerator = new KDF1BytesGenerator(digest)
    kdf1BytesGenerator.init(new KDFParameters(secretKey.getEncoded, null))
    kdf1BytesGenerator.generateBytes(bytes, 0, bytes.length)
    new SecretKeySpec(bytes, secretKey.getAlgorithm)
}

代码在iOS一边

var keyExchangeError: Unmanaged<CFError>?
let dict = [SecKeyKeyExchangeParameter.requestedSize.rawValue : 32,
        SecKeyKeyExchangeParameter.sharedInfo.rawValue : ???]
    let secret = SecKeyCopyKeyExchangeResult(privateOwn,
            SecKeyAlgorithm.ecdhKeyExchangeStandard,
            publicTheir,
            dict as CFDictionary,
            &keyExchangeError)

共1个答案

匿名用户

你是完全正确的,我的朋友,围绕安全框架的留档是糟糕透顶的。

事实上,CryptoKit是Apple试图以libNa风格对这里的事物进行现代化改造,为精心选择的原语提供简单的接口,例如椭圆曲线Diffie-Hellman在安全曲线上。

所以我同情,并建议在iOS/macOS上需要加密时,通常只使用libNa

无论如何,为了希望回答你的问题,我在SecKit库中发现了一个与你在Scala中使用的内容相匹配的内容,在Diffie-Hellman进程之后,你正在服务器端通过SHA256运行密钥材料,所以iOS需要匹配这个HBKDF。

 @constant kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA256
    Compute shared secret using ECDH cofactor algorithm, suitable only for kSecAttrKeyTypeECSECPrimeRandom keys
    and apply ANSI X9.63 KDF with SHA256 as hashing function.  Requires kSecKeyKeyExchangeParameterRequestedSize and allows
    kSecKeyKeyExchangeParameterSharedInfo parameters to be used.

所以我认为你只需要改变这一点:

var keyExchangeError: Unmanaged<CFError>?
let dict = [SecKeyKeyExchangeParameter.requestedSize.rawValue : 32,
        SecKeyKeyExchangeParameter.sharedInfo.rawValue : ???]
    let secret = SecKeyCopyKeyExchangeResult(privateOwn,
            SecKeyAlgorithm.ecdhKeyExchangeStandard,
            publicTheir,
            dict as CFDictionary,
            &keyExchangeError)

对此:

var keyExchangeError: Unmanaged<CFError>?
let dict = [SecKeyKeyExchangeParameter.requestedSize.rawValue : 32,
        SecKeyKeyExchangeParameter.sharedInfo.rawValue : ???]
    let secret = SecKeyCopyKeyExchangeResult(privateOwn,
            SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256,
            publicTheir,
            dict as CFDictionary,
            &keyExchangeError)

我还没有测试过上面的内容,因为我在Linux机器atm上,但希望它能有所帮助,它应该会将基于SHA256的KDF添加到ECDH进程中。但是是的,API真是一团糟。我就是无法使用它。