您好我想使用.cer文件的公钥加密Json Payload。请建议怎么做?
let path = Bundle.main.path(forResource: "Keys123_1", ofType: "cer")
//get the data asociated to this file
let urlStt = URL(fileURLWithPath: path!)
if let base64String = try? Data(contentsOf: urlStt).base64EncodedString() {
print(base64String)
let data2 = Data.init(base64Encoded: base64String)
let keyDict:[NSObject:NSObject] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPublic,
kSecAttrKeySizeInBits: NSNumber(value: 2048),
kSecReturnPersistentRef: true as NSObject
]
var error:Unmanaged<CFError>? = nil
guard let key = SecKeyCreateWithData(data2 as! CFData, keyDict as CFDictionary, &error) else {
print(error)
return
}
我收到此错误:
Optional(Swift.Unmanaged<__ObjC.CFError>(_value: Error Domain=NSOSStatusErrorDomain Code=-50 "RSA public key creation from data failed" UserInfo={NSDescription=RSA public key creation from data failed}))
答案 0 :(得分:1)
尝试此代码并使用公钥进行加密,并通过服务器端的私钥解密来验证数据。我遵循了link。
可能适合你。
func getPublicKey() -> SecKey? {
let certificateData = try! Data(contentsOf: Bundle.main.url(forResource: "public", withExtension: "cer")!)
let certificate = SecCertificateCreateWithData(nil, certificateData as CFData)
var trust: SecTrust?
let policy = SecPolicyCreateBasicX509()
let status = SecTrustCreateWithCertificates(certificate!, policy, &trust)
if status == errSecSuccess {
let publicKey = SecTrustCopyPublicKey(trust!)!
return publicKey
}
return nil
}