如何使用 swift 将 SecKey 编码为 base64 字符串

How to encode SecKey to base64 string using swift

我想将密钥编码为 base64 字符串。但我真的不明白该怎么做。我试图找到一些信息,但我一无所获。这就是为什么我在这里寻求帮助。如果有任何帮助,我将不胜感激。 现在我有这个:

var error: Unmanaged<CFError>? = nil
    var statusCode: OSStatus = 0
    var publicKey: SecKey?
    var privateKey: SecKey?

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

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

    var keyPairAttr = [NSObject: Any]()

和 func keysGeneration() {

    rsaKeyGenerator.keyPairAttr[kSecAttrType] = kSecAttrKeyTypeRSA
    rsaKeyGenerator.keyPairAttr[kSecAttrKeySizeInBits] = 2048
    rsaKeyGenerator.keyPairAttr[kSecReturnData] = true
    rsaKeyGenerator.keyPairAttr[kSecPublicKeyAttrs] = rsaKeyGenerator.publicKeyAttribute
    rsaKeyGenerator.keyPairAttr[kSecPrivateKeyAttrs] = rsaKeyGenerator.privateKeyAtrribute


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

    if #available(iOS 10.0, *) {
        let publicKey = SecKeyCopyExternalRepresentation(rsaKeyGenerator.publicKey!, &rsaKeyGenerator.error)
        let privateKey = SecKeyCopyExternalRepresentation(rsaKeyGenerator.privateKey!, &rsaKeyGenerator.error)
//            print("MY PUBLIC KEY = \(publicKey)")
//            print("MY PRIVATE KEY = \(privateKey)")

    }

要将字符串转换为其 base64 表示形式,您需要经过 Data

let s = "string to encode as base64"
let d = s.data(using: .utf8)
let b64 = base64EncodedString()