1

I am trying to encrypt a string and save it in the keychain. This is what i have done

   //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)

In the last line, I get this error "Cannot convert of type [UInt8] to data".
I basically want to convert messageEncrypted to String so that I can save it in the keychain.
I am using this Keychain Lib - https://github.com/jrendel/SwiftKeychainWrapper
This requires that I enter the data as a String.
Any help will be appreciated. I understand that saving encrypted data in the keychain might not be the way to go but it's a client requirement.

Thanks in advance

1 Answer 1

1

It seems that all is needed is to convert your messageEncrypted from [UInt8] to Data instance, and fortunatelly there is a fitting initializer :

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.