2017-05-09 102 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)