将私有base64编码的密钥转换为SecKey

时间:2019-02-28 05:41:50

标签: ios swift encryption base64

我确实使用OpenSSL这样生成了私钥:

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 563 -nodes -subj "//C=LT\ST=Vilnius\L=Vilnius\O=Briedis\OU=Org\CN=www.example.com"

key.pem文件包含base64格式的私有密钥。删除了BEGIN和END标记。以及新行。应用这些更改后,私钥如下所示:

let privteKeyString = “MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCxFZF3YHfkbvNbC5kuXo4QxtHVRBKe35lOUVFPIRPxc87QUJHwb0b62aG84AHRhx6fawX66Sby/U31U0HBXh0QY3IRGqSm3xOZBjrJvAk2vd8T5y4fCYFuEk3exTm7FNVeucf0W3ibPyW/zWTbMek1XMSbii130LUKBhMFg1Jmf/M2YwSRmPO4gZ3uzK+hvE02QtvEI8/ruiO1GfRsqsYNPd67Cayley8DvYXzQKCS6+LJUW1lTQObgY0xHLpmlLmXjLj9pAvXPVp0jqbVml2TcKCeC/7cyaf0jxEfkajlYGORpw/0/zcYk2mde/UzzEzvKsOXAnZo1XTj+BdOMVuaeKdxjtEOoFBGVabSmBl0NRTg2JEZKTHJ6gywiua1jemnKAnwrwsc3DOFIKDpGS9EBiFgbg86c/2/76EcQ4pYtiZgwYABahPpC+JAEpw99PGK9jZcSsFpTO81ZNIwoy/deH/frZ0G1hQCnB85T3DDELC8aJMM9R+NUJcLnq9NHywE15Sm2xzepkY1sWo0XmcSn/e3lBqOLAIIw+bygsM9Xksxhs6FLb0BOWMh/C3urKnG/jdPLp0ROKD6t9/5iVgCPDftHEEVxPrKcVqOSBoFPRhKvl8SP6OdyS4ken8xzKNCN7bs1ZvhpvhtpFysgAOHZF9y9GcafltZEFVECfBd0wIDAQABAoICAQCJle9ip/Ie6tFrMLTAYTjR8hfAMlahV6r+PZIF//ZFyCuskJ0DCQJGDmdqn0TqbaguRnHsA9B+RK6YaCqTubKtNAbBIUlCWdoZL8znR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/QKO24lyRtEqYQZtCFs+AEeZNFkay9npYY/nNplQV/K/b9E4WYUtNWHukjwll8ftwsiDJqj2JV5GYmfLbUgJbuxJ6eGNXcgrW3Vs8ye9mVHiL8QSpYpQS3ys0Kiv3zjvkobCO4bQVfIQGxIj5mnWL/is=“

从base64转换为SecKey:

let privateKeyData = Data(privteKeyString.utf8)
var error: Unmanaged<CFError>?
 let secKey = SecKeyCreateWithData(privateKeyData as! NSData, [
 kSecAttrKeyType: kSecAttrKeyTypeRSA,
 kSecAttrKeySizeInBits: 4096,
 kSecAttrKeyClass: kSecAttrKeyClassPrivate,
 ] as NSDictionary, &error)

执行后出现-50错误。

将base64私钥转换为SecKey的方式是什么?

1 个答案:

答案 0 :(得分:1)

通常,所有RSAPrivateKey都不是普通的RSAPrivateKey,而是PrivateKeyInfo(请参阅RFC 5208的第5节)。 IOS不支持PrivateKeyInfo密钥结构。在这种情况下,需要转换为RSAPrivateKey。从PrivateKeyInfo创建iOS SecKey的步骤:

  1. 使用OpenSSL将private key.pem转换为DER格式。

    openssl rsa -in key.pem -outform der -out key.der
    
  2. 将key.der文件拖放到Xcode项目中。

  3. 加载并打印出私钥作为普通RSAPrivateKey:

    let keyUrl = Bundle.main.url(forResource: "key", withExtension: "der")
    let keyDerData = try? Data(contentsOf: keyUrl!)
    print(keyDerData?.base64EncodedString())
    
  4. 将原始RSAPrivateKey原始数据转换为SecKey。

       var error: Unmanaged<CFError>?
     let secKey = SecKeyCreateWithData(keyDerData as! NSData, [
     kSecAttrKeyType: kSecAttrKeyTypeRSA,
     kSecAttrKeySizeInBits: 4096,
     kSecAttrKeyClass: kSecAttrKeyClassPrivate,
     ] as NSDictionary, &error)