ios - 我可以从 Swift 中的 SecKeyRef 对象获取模数或指数吗?

标签 ios swift encryption cryptography public-key-encryption

在 Swift 中,我创建了一个 SecKeyRef通过调用对象 SecTrustCopyPublicKey在一些原始 X509 证书数据上。这就是这个 SecKeyRef 对象的样子。

Optional(<SecKeyRef algorithm id: 1,
key type: RSAPublicKey,
version: 3, block size: 2048 bits,
exponent: {hex: 10001, decimal: 65537},
modulus: <omitted a bunch of hex data>,
addr: 0xsomeaddresshere>)

基本上,这个SecKeyRef 对象保存了一大堆关于 公钥的信息,但似乎没有办法实际转换这个SecKeyRef 转换成字符串、NSData 或其他任何东西(这是我的目标,只是为了获得一个 base64 公钥)。

但是,我有一个函数,我可以给出一个模数和一个指数,它只会计算公钥是什么。我通过传递从上面的 SecKeyRef 记录的数据对其进行了测试。

但不知何故,我无法从 SecKeyRef 对象访问这些属性(我只能在控制台中看到整个对象;例如,我无法执行 SecKeyRef.modulus 或任何类似的东西)

我的问题:如何访问 SecKeyRef.modulus,或者将此 SecKeyRef 转换为 NSData 或类似的东西? 谢谢

编辑

(更多信息)

我正在动态创建我的SecKeyRef,通过这个函数我有:

func bytesToPublicKey(certData: NSData) -> SecKeyRef? {
    guard let certRef = SecCertificateCreateWithData(nil, certData) else { return nil }
    var secTrust: SecTrustRef?
    let secTrustStatus = SecTrustCreateWithCertificates(certRef, nil, &secTrust)
    if secTrustStatus != errSecSuccess { return nil }
    var resultType: SecTrustResultType = UInt32(0) // result will be ignored.
    let evaluateStatus = SecTrustEvaluate(secTrust!, &resultType)
    if evaluateStatus != errSecSuccess { return nil }
    let publicKeyRef = SecTrustCopyPublicKey(secTrust!)

    return publicKeyRef
}

它所做的是从证书中获取原始字节流(可以从使用 PKI 的硬件中广播),然后将其转换为 SecKeyRef

编辑2

(截至 2015 年 1 月 7 日对现有答案的评论)

这不起作用:

let mirror = Mirror(reflecting: mySecKeyObject)

for case let (label?, value) in mirror.children {
    print (label, value)
}

这会在控制台中产生以下输出:

Some <Raw SecKeyRef object>

不确定字符串“Some”是什么意思。

此外,mirror.descendant("exponent")(或“modulus”)导致 nil,即使在控制台中打印原始对象时,我可以清楚地看到这些属性存在,并且它们实际上已被填充。

此外,如果可能的话,我想避免必须保存到钥匙串(keychain),读取为 NSData,然后从钥匙串(keychain)中删除。如赏金描述中所述,如果这是唯一可能的方法,请引用权威引用。感谢您迄今为止提供的所有答案。

最佳答案

确实可以使用既不使用 key 链也不使用 私有(private) API 来提取模数和指数。

有 ( public but undocumented ) 函数 SecKeyCopyAttributes提取 CFDictionary来自SecKey . 属性键的一个有用来源是 SecItemConstants.c

检查这本词典的内容,我们找到一个条目 "v_Data" : <binary> .它的内容是DER-encoded ASN对于

SEQUENCE {
    modulus           INTEGER, 
    publicExponent    INTEGER
}

请注意,如果整数是正数并且有一个前导 1 位(以免将它们与二补负数混淆),则整数将用零字节填充,因此您可能会发现比预期多一个字节.如果发生这种情况,请将其切掉。

您可以为此格式实现解析器,或者在知道 key 大小的情况下对提取进行硬编码。对于 2048 位 key (和 3 字节指数),格式为:

30|82010(a|0)        # Sequence of length 0x010(a|0)
    02|82010(1|0)    # Integer  of length 0x010(1|0)
        (00)?<modulus>
    02|03            # Integer  of length 0x03
        <exponent>

总共 10 + 1? + 256 + 3 = 269 或 270 字节。

import Foundation
extension String: Error {}

func parsePublicSecKey(publicKey: SecKey) -> (mod: Data, exp: Data) {
    let pubAttributes = SecKeyCopyAttributes(publicKey) as! [String: Any]

    // Check that this is really an RSA key
    guard    Int(pubAttributes[kSecAttrKeyType as String] as! String)
          == Int(kSecAttrKeyTypeRSA as String) else {
        throw "Tried to parse non-RSA key as RSA key"
    }

    // Check that this is really a public key
    guard    Int(pubAttributes[kSecAttrKeyClass as String] as! String) 
          == Int(kSecAttrKeyClassPublic as String) 
    else {
        throw "Tried to parse non-public key as public key"
    }

    let keySize = pubAttributes[kSecAttrKeySizeInBits as String] as! Int

    // Extract values
    let pubData  = pubAttributes[kSecValueData as String] as! Data
    var modulus  = pubData.subdata(in: 8..<(pubData.count - 5))
    let exponent = pubData.subdata(in: (pubData.count - 3)..<pubData.count) 

    if modulus.count > keySize / 8 { // --> 257 bytes
        modulus.removeFirst(1)
    }

    return (mod: modulus, exp: exponent)
}

(我最终编写了一个完整的 ASN 解析器,所以这段代码没有经过测试,请注意!)


请注意,您可以用非常相似的方式提取私钥 的详细信息。使用 DER 术语,这是 v_Data 的格式:

PrivateKey ::= SEQUENCE {
    version           INTEGER,
    modulus           INTEGER,  -- n
    publicExponent    INTEGER,  -- e
    privateExponent   INTEGER,  -- d
    prime1            INTEGER,  -- p
    prime2            INTEGER,  -- q
    exponent1         INTEGER,  -- d mod (p-1) (dmp1)
    exponent2         INTEGER,  -- d mod (q-1) (dmq1)
    coefficient       INTEGER,  -- (inverse of q) mod p (coeff)
    otherPrimeInfos   OtherPrimeInfos OPTIONAL
 }

手动解析这个可能是不明智的,因为任何整数都可能已被填充。


注意事项:如果 key 是在 macOS 上生成的,则公钥的格式会有所不同;上面给出的结构是这样包装的:

SEQUENCE {
    id              OBJECTID,
    PublicKey       BITSTRING
}

位串是上述形式的 DER 编码 ASN。

关于ios - 我可以从 Swift 中的 SecKeyRef 对象获取模数或指数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34408825/

相关文章:

swift - 如何生成泛型的 nil

javascript - 如何加密 JavaScript 代码以使其不可解密?

java - 如何用新加密的数据更新部分加密的数据?

ios - 如何让 AVCaptureSession 和 AVPlayer 尊重 AVAudioSessionCategoryAmbient?

ios - 在导航 Controller 类的类别中添加左右栏按钮项

ios - 图片IO : PNG invalid PNG file: iDOT doesn't point to valid IDAT chunk

ios - 在 Swift 4 中升级后未调用 textFieldShouldReturn

ios - 找不到 Firebase 的 PhoneAuthProvider 类

ios - 固定标签在该位置且宽度相等

带有salt的MySQL encrypt()在密码后接受随机字符