2017-05-09 56 views
1

我想加密一個字符串並將其保存在鑰匙串中。這是我做了什麼在鑰匙串中保存加密的字符串

//Generate RSA private and public keys 
    let parameters: [String: AnyObject] = [ 
     kSecAttrKeyType as String: kSecAttrKeyTypeRSA, 
     kSecAttrKeySizeInBits as String: 1024 as AnyObject 
    ] 
    SecKeyGeneratePair(parameters as CFDictionary, &publicKey, &privateKey) 

    let blockSize = SecKeyGetBlockSize(publicKey!) 
    var messageEncrypted = [UInt8](repeating: 0, count: blockSize) 
    var messageEncryptedSize = blockSize 

    status = SecKeyEncrypt(publicKey!, SecPadding.PKCS1, data, data.characters.count, &messageEncrypted, &messageEncryptedSize) 

    let encryptedString = String(data: messageEncrypted, encoding: .utf8) 

在最後一行中,我得到這個錯誤「不能類型的轉換[UINT8]到數據」。
我基本上想要將messageEncrypted轉換爲字符串,以便我可以將它保存在鑰匙串中。
我正在使用此Keychain Lib - https://github.com/jrendel/SwiftKeychainWrapper
這就要求我輸入數據作爲字符串。
任何幫助將不勝感激。我知道在鑰匙串中保存加密的數據可能不是要走的路,但這是客戶的要求。

在此先感謝

回答

1

似乎所有需要的是你的messageEncrypted[UInt8]轉換爲Data實例,fortunatelly有一個fitting initializer

let encryptedData = Data(bytes: messageEncrypted) 
let encryptedString = String(data: encryptedData, encoding: .utf8)