本文介绍了ios/swift 中的椭圆曲线 Diffie Hellman的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

iOS 是否公开 API 用于生成密钥和使用 ECDH 导出密钥?

Does iOS expose API for key generation, and secret key derivation using ECDH?

据我所知,Apple 正在内部使用它(特别是 x25519),但我认为它没有通过通用加密或其他方式公开为公共 API.

From what I see, apple are using it (and specifically x25519) internally but I don't see it exposed as public API by common crypto or otherwise.

谢谢,

Z

推荐答案

在 Playground 中使用 Xcode 8.3.3 完成,使用 EC 为 Alice、Bob 生成一个私钥/公钥,然后使用 Alice 的私钥计算 Alice 的共享密钥和Bob 的公开,并使用 Bob 的私有和 Alice 的公开为 Bob 共享秘密,并最终断言它们是平等的.

Done in playground with Xcode 8.3.3, generates a private/public key using EC for Alice, Bob, then calculating the shared secret for Alice using Alice's private and Bob's public, and share secret for Bob using Bob's private and Alice's public and finally asserting that they're equal.

import Security
import UIKit

let attributes: [String: Any] =
    [kSecAttrKeySizeInBits as String:      256,
     kSecAttrKeyType as String: kSecAttrKeyTypeEC,
     kSecPrivateKeyAttrs as String:
        [kSecAttrIsPermanent as String:    false]
]

var error: Unmanaged<CFError>?
if #available(iOS 10.0, *) {
    // generate a key for alice
    guard let privateKey1 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
        throw error!.takeRetainedValue() as Error
    }
    let publicKey1 = SecKeyCopyPublicKey(privateKey1)

    // generate a key for bob
    guard let privateKey2 = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
        throw error!.takeRetainedValue() as Error
    }
    let publicKey2 = SecKeyCopyPublicKey(privateKey2)

    let dict: [String: Any] = [:]

    // alice is calculating the shared secret
    guard let shared1 = SecKeyCopyKeyExchangeResult(privateKey1, SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256, publicKey2!, dict as     CFDictionary, &error) else {
        throw error!.takeRetainedValue() as Error
    }

    // bob is calculating the shared secret
    guard let shared2 = SecKeyCopyKeyExchangeResult(privateKey2, SecKeyAlgorithm.ecdhKeyExchangeStandardX963SHA256, publicKey1!, dict as CFDictionary, &error) else {
        throw error!.takeRetainedValue() as Error
    }

    print(shared1==shared2)


} else {
    // Fallback on earlier versions
    print("unsupported")
}

感谢@Mats 让我朝着正确的方向前进..3

Thanks @Mats for sending me in the right direction..3

这篇关于ios/swift 中的椭圆曲线 Diffie Hellman的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-09 12:46