iOS/Swift中的椭圆曲线Diffie Hellman [英] Elliptic Curve Diffie Hellman in ios/swift

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

问题描述

iOS是否公开用于密钥生成和使用ECDH进行秘密密钥派生的API?

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

据我所知,苹果内部使用它(特别是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

推荐答案

使用Xcode 8.3.3在操场上完成,使用EC为Alice,Bob生成私钥/公钥,然后使用Alice的private和鲍勃(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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆