【发布时间】:2017-01-09 00:35:15
【问题描述】:
Alamofire 允许使用证书和公钥进行固定(尽管从包中获取公钥的函数从包中的证书中获取密钥)。
当从证书中提取公钥时,我能够使固定工作,但是当我提供 SHA256 String 作为公钥时固定失败(我收到来自 api 调用的密钥字符串,如果第一次固定失败,它应该用作公钥。)我使用下面的代码将字符串转换为 [SecKey]
//创建服务器信任策略
let serverTrustPolicies: [String: ServerTrustPolicy] = [
destinationURL!: .pinPublicKeys(
publicKeys:savePublicKeys(),
validateCertificateChain:true,
validateHost:true
)]
self.manager = SessionManager(
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
//获取[SecKey]
func savePublicKeys() -> [SecKey]
{
var key:SecKey?
var publicKeys:[SecKey] = []
//Check and use if backup key is received from beacon call
if(KeychainService().checkIfKeyExists(tag: "backupURL"))
{
key = KeychainService().obtainKey(tag: backupURLKey)
publicKeys.append(key!)
}
return publicKeys
}
//插入和检索钥匙串数据的函数
func insertPublicKey(publicTag: String, data: Data) -> SecKey? {
let query: Dictionary<String, AnyObject> = [
String(kSecAttrKeyType): kSecAttrKeyClassPublic,
String(kSecClass): kSecClassKey as CFString,
String(kSecAttrApplicationTag): publicTag as CFString,
String(kSecValueData): data as CFData,
String(kSecReturnPersistentRef): true as CFBoolean]
var persistentRef: AnyObject?
let status = SecItemAdd(query as CFDictionary, &persistentRef)
if status != noErr && status != errSecDuplicateItem {
return nil
}
return obtainKey(tag: publicTag)
}
func obtainKey(tag: String) -> SecKey? {
var keyRef: AnyObject?
let query: Dictionary<String, AnyObject> = [
String(kSecAttrKeyType): kSecAttrKeyClassPublic,
String(kSecReturnRef): kCFBooleanTrue as CFBoolean,
String(kSecClass): kSecClassKey as CFString,
String(kSecAttrApplicationTag): tag as CFString,
String(kSecReturnPersistentRef): true as CFBoolean
]
let status = SecItemCopyMatching(query as CFDictionary, &keyRef)
switch status {
case noErr:
if let ref = keyRef {
return (ref as! SecKey)
}
default:
break
}
return nil
}
我哪里错了?据我所知,我使用的String 是base64encoded 并且适用于Android 部分。
【问题讨论】:
-
我已经添加了一个基本解释,为什么这会很困难,作为这里的答案。虽然我确实希望人们了解散列和安全性,但这可能会演变为关于密码学和数学的辩论。如果版主觉得没问题,可以锁定这个问题。
标签: ios swift3 alamofire keychain