如何在ios中生成如下所示的公钥/私钥对,swift

时间:2017-08-28 07:45:40

标签: ios swift rsa pem der

这就是我生成公钥/私钥对的方法

var statusCode: OSStatus
var publicKey: SecKey?
var privateKey: SecKey?

let publicKeyAttribute: [NSObject : NSObject] = [kSecAttrIsPermanent: true as NSObject, kSecAttrApplicationTag: "publictag".data(using: String.Encoding.utf8)! as NSObject]

let privateKeyAtrribute: [NSObject: NSObject] = [kSecAttrIsPermanent: true as NSObject, kSecAttrApplicationTag: "privatetag".data(using: String.Encoding.utf8)! as NSObject]

var keyPairAttr = [NSObject: Any]()
keyPairAttr[kSecAttrType] = kSecAttrKeyTypeRSA
keyPairAttr[kSecAttrKeySizeInBits] = 2048
keyPairAttr[kSecReturnData] = true
keyPairAttr[kSecPublicKeyAttrs] = publicKeyAttribute
keyPairAttr[kSecPrivateKeyAttrs] = privateKeyAtrribute


statusCode = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)

这会产生如下所示的密钥对,

公钥:

Optional(<SecKeyRef algorithm id: 1, key type: RSAPublicKey, version: 4, block size: 2048 bits, exponent: {hex: 10001, decimal: 65537}, modulus: 9A6AC9860B66ED5276A1C90C54DB341957A5DA52A040617C2A826E36B7D4F656132C231F0EF5B5BF073DDA2A60A581E02D27DD776845FE7A79C6A84DDE9620D193EC0B20B08E25D01FC28FB5E2FAEB4F945E9FB8A2153E571DEF5CC187A0F511A372E4616691BD30485D62D50B57E589F0AB998036A6EBFDA45B9765A2A4A95C96EADAB8E0D7F24044D99C7AD5C07F2AED929465B96F8D8435E8953DA2E6E39974D35DFED44296C650C40997961398C05E55027B909C4B1D9C6D58F6A7231B5BAC6B0B8631184649F1EB1F78623758F3BC7B98FEC0665F11BF36D75B468185F26B4ABE96855E0C9BEF6120D505000CF0A2A1661BC16EC9857D48C104AC37CD21, addr: 0x60800002e580>)

私钥:

Optional(<SecKeyRef algorithm id: 1, key type: RSAPrivateKey, version: 4, block size: 2048 bits, addr: 0x60800002e5c0>)
  

这些是.pem.der

但我需要它,如下所示

公钥:

    -----BEGIN RSA PUBLIC KEY-----
    MIIBCgKCAQEA0bipoOhkkvPxcsyOzcqsIUeVe0+iwe8W7N4EbHZMgujRERu1TPpy
    UcCO0uuKmm1TU09Kl40rRvDbtgB1YcGV3FPnNp3sOyFVsdyZ5bzxZtyyLrSWtj/n
    bLnGwaG9xJSwd2R/pTQLzOLV5KldwD2eUb3Z4Z4e9Z8II7eWgGaCLLqbrtEAa05N
    EqARckxrzJ1S3j+59h4AQovF72KI90/kRPryT2OGDiVlJ6CTjn2ZnTYcx65X6Rwf
    AeJKHZAGhw96j9tXyS+dJcXy4IBUTi3PXw0aEfhHQr/JsSHuMp/8mrhVJEokXb1C
    gKDZgJXujpGhCBdztHBAJxLBQMlODg7srwIDAQAB
    -----END RSA PUBLIC KEY-----


and private key should be like : 

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAsfxMagVKY5++61Kot0esyhEOesqyQlZNvWbqMBcOoaOAb3pk
LvwaGJ2YtD12u4yDEKcY5rpX7B/2t8GBHf+74NG47zAutf4Gf6qgQRUmIx2b7i4k
WBt3KIifb/Zfs9KVJLhD4007bg1OtXA4kIhhXiuvhajDjDLOEthogF45CkJe+N67
JnH5hVW5CqBxPyRCrWCFbEHcXs5H515JV/Kz1+JVrB2/M03fW751wptO2GdGwsde
ofqQzY+WUzqUihXigIjAVLFRemky3HpwuhzXUJn6A0ZD4tkk1JLstpSSJdBpH+L2
b9QlOitehxFgRsYmto+idpD1XrS9UyUtmpbTuwIDAQABAoIBAQCYvrAJcJ7lnmtn
Ytm96LoF89tcT+Xpfk1bFR43xSHeYAXSJdQiamIu69joHbNuwuib+vsoz5Sy5L+D
9YHMb/MZvoIaa1w6/VUwbQr4r6C6FCgEoP65ymBZnd5OZL6/ASLTj3tbb6VoDe2V
UkiI6TG+cnlAmJOxFsy5aZVNTQ9gmCMS0+AdpTbDsxTPg3y0EKFXeVRyKjq0lO9m
p3G5yHkFjzWWY6s5XHx27gDTt8eXg/un72Qsz1rh5iUnAoxrga0Oco3Yk9DMvMwz
a1I1Lo5fpB6FbTGX3k24heSnLDFEnlBvsBBg0g/n/qgwoZJ81MgG8Q4kAfeScuCI
sYVnHEBpAoGBAOpnrKEkyhk1rXG4Md+z1/odhqx89mV7mF1ttW4IhFcwpJSMohsG
r27Ic87whkpRxz2Mwj3B5WPGne4UkbvniH46n3jEW7ZIUF+ASVWkjMaGJWtOqSLC
I19Snie9WvpREwaCVuvT2l4IeM1WL5gKotBwa3csZgGYH6gcyW5Ipbo/AoGBAMJh
/+WXbohF4+A989q0jYjRRhKwUJAYeK8/AePrx8MnAXnRd09TiqeGn0Xig/RNZ0RE
96/TC1dTIBIHk5aDMy3vQhhYF0KbwcQWmCOnGo1qNTTaWTa3UitFMWf0hO0HuZtp
RyD1YwhHP0W2tiK2GVjCreqIYASCpYKLq5Qq1K+FAoGARk2h8RLfqn/27UyZaMa/
2DxS0BkKrZVMNXlaGQ5k4uGr+wHS/NgcddWZJk/tdwzf/Q3ilDM7YZmIdIemzfy7
a2CZw9bgyuMVeA85733S2xgQ0QZepBYmFcjptnGMf9chJaqh90krDVjtImjfDXLj
MjEFilC+p2vA0uMPZwxS6HECgYAc5dLUQBoHmlRRTwSEvBjagToopxujAHBYpUZT
qwbMpWzbvl89ZM8VLrdY/V7en+89P/+OnRJvjgUTiRrQ4npmVs59rgLvPRamXzGJ
A1u4MFTuoZNnxgMqOaQprzlfv6lBSHpxlOl/HpByfcJAENBd2LtgRZv4r6+JY9hD
M8bgvQKBgCDTSCLj5c1CYyuJMdrz9L5+xLFmrmL48djhK460ZcmcZ/gP808CyXx/
sDneow+JWt7Jb3p5zyUvvq1aDGNSsn4plB2rg7AqtoHcZYyFFZGI/K/b6JZna1yu
FUYOfcanunabxY1wPQxuvR+AEuufBjB0aKg+qkLCCN1HYQtLs+N8
-----END RSA PRIVATE KEY-----

怎么做。希望你的帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法generateKeyPair创建公钥/私钥对,然后使用 SecKeyCopyExternalRepresentation 方法进行外部表示。

<强> Swift3

//tuple type for public/private key pair at class level
typealias KeyPair = (publicKey: SecKey, privateKey: SecKey)

// In your code block

    let publicKeyTag: String = "com.org.yourapp.publickey"
    let privateKeyTag: String = "com.org.yourapp.privatekey"
    let keyPair = generateKeyPair(publicKeyTag, privateTag: privateKeyTag, keySize: 2048)
    var pbError:Unmanaged<CFError>?
    var prError:Unmanaged<CFError>?
    guard let pbData = SecKeyCopyExternalRepresentation((keyPair?.publicKey)!, &pbError) as Data? else {
        print("error: ", pbError!.takeRetainedValue() as Error)
        return
    }
    guard let prData = SecKeyCopyExternalRepresentation((keyPair?.privateKey)!, &prError) as Data? else {
        print("private key error: ")
        return
    }
    let strPublicKey = appendPrefixSuffixTo(pbData.base64EncodedString(options: .lineLength64Characters), prefix: "-----BEGIN RSA PUBLIC KEY-----\n", suffix: "\n-----END RSA PUBLIC KEY-----")
    print("public key: \n", strPublicKey)

    let strPrivateKey = appendPrefixSuffixTo(prData.base64EncodedString(options: .lineLength64Characters), prefix: "-----BEGIN RSA PRIVATE KEY-----\n", suffix: "\n-----END RSA PRIVATE KEY-----")
    print("private key: \n", strPrivateKey)

辅助功能:

func appendPrefixSuffixTo(_ string: String, prefix: String, suffix: String) -> String {
    return "\(prefix)\(string)\(suffix)"
}
  

generateKeyPair方法返回public / private KeyPair

func generateKeyPair(_ publicTag: String, privateTag: String, keySize: Int) -> KeyPair? {
    var sanityCheck: OSStatus = noErr
    var publicKey: SecKey?
    var privateKey: SecKey?
    // Container dictionaries
    var privateKeyAttr = [AnyHashable : Any]()
    var publicKeyAttr = [AnyHashable: Any]()
    var keyPairAttr = [AnyHashable : Any]()
    // Set top level dictionary for the keypair
    keyPairAttr[(kSecAttrKeyType ) as AnyHashable] = (kSecAttrKeyTypeRSA as Any)
    keyPairAttr[(kSecAttrKeySizeInBits as AnyHashable)] = Int(keySize)
    // Set private key dictionary
    privateKeyAttr[(kSecAttrIsPermanent as AnyHashable)] = Int(true)
    privateKeyAttr[(kSecAttrApplicationTag as AnyHashable)] = privateTag
    // Set public key dictionary.
    publicKeyAttr[(kSecAttrIsPermanent as AnyHashable)] = Int(true)
    publicKeyAttr[(kSecAttrApplicationTag as AnyHashable)] = publicTag

    keyPairAttr[(kSecPrivateKeyAttrs as AnyHashable)] = privateKeyAttr
    keyPairAttr[(kSecPublicKeyAttrs as AnyHashable)] = publicKeyAttr
    sanityCheck = SecKeyGeneratePair((keyPairAttr as CFDictionary), &publicKey, &privateKey)
    if sanityCheck == noErr && publicKey != nil && privateKey != nil {
        print("RSA key pair generation Successful")
        return KeyPair(publicKey: publicKey!, privateKey: privateKey!)
    }
    return nil
}

输出如下:

public key: 
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAz1zfbybUt5jZX5P6ymy+g04wj3iTYCV8eGbkFyqFNsfN8Lnk6x4x
zstfnpE6asV6NkBecQnT1a9X6AVxA4Mxq4CeysR10TRr8HGczQGKl7R3Nbvvmgw+
jX8LZGxsQTO6qYWhMAtOPFfsMW9iy3AsDE7OIYfya6y/l919ExbgPzJ+0nLdiBmd
bmmzOQ1PaKt3OcxG6qZyBoixRTTOm4UDCLDzYdjz5dS1rbvb7pD15TpkZBkuMRm5
QDv+xhKcz1UFGQP7ssZS++ZoQlF2CZJuLz8R1uUYg4xQnF0r1IBBrlVtKnblgMcA
ZykNweGwrdPaWF3PeZmbvG+/m+Kt7/4BJwIDAQAB
-----END RSA PUBLIC KEY-----