Q:

Store & Load [Uint8] to & from Keychain (Swift)

I need to store an uint8 array [UInt8] to the keychain. This seems to works. Then I need to load and use this previously stored data but the result of the print doesn't fit with the array expect. I need to restore exactly the same content stored.
import UIKit

class Keychain: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let privKeyUInt8: [UInt8] = [0x04,0x09,0x44,0x11,0xc6,0xbe,0x9f,0x31,0x88,0xa0,0x23,0xe7,0xf1,0x77,0x13,0xef,0xde,0x0a,0x37,0x02,0xfc,0xc6,0x04,0x5b,0x03,0xd7,0x12,0x03,0x26,0x6a,0x4b,0x3d,0x05,0x55,0x5d,0x90,0xe1,0xa4,0xcf,0xd1,0x78,0xf7,0x95,0xda,0xa3,0x9c,0x18,0x2c,0x37,0x4f,0x1b,0xfa,0x28,0x2e,0x64,0x7a,0x22,0x7f,0x47,0x9a,0x98,0x1a,0x2c,0x9b,0x2d,0x28,0x96,0xe0,0x66,0x07,0x33,0x06,0x10,0x5a,0x95,0x85,0x9c,0xc3,0xfd,0x43,0xf4,0x81,0x95,0xf4,0xe5,0x6d,0xb2,0x52,0x32,0x2a,0x87,0x6d,0xc1,0x52,0x89,0xd3,0x05]

        let privKeyData = Data(bytes: privKeyUInt8, count: privKeyUInt8.count)

        let status = self.save(key: "PrivKey", data: privKeyData)
        print("status: ", status)

        if let receivedData = self.load(key: "PrivKey") {
            let result = receivedData.to(type: Int.self)
            print("result: ", result)
        }
    }

    func save(key: String, data: Data) -> OSStatus {
        let query = [
            kSecClass as String       : kSecClassGenericPassword as String,
            kSecAttrAccount as String : key,
            kSecValueData as String   : data ] as [String : Any]

        SecItemDelete(query as CFDictionary)

        return SecItemAdd(query as CFDictionary, nil)
    }

    func load(key: String) -> Data? {
        let query = [
            kSecClass as String       : kSecClassGenericPassword,
            kSecAttrAccount as String : key,
            kSecReturnData as String  : kCFBooleanTrue!,
            kSecMatchLimit as String  : kSecMatchLimitOne ] as [String : Any]

        var dataTypeRef: AnyObject? = nil

        let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)

        if status == noErr {
            return dataTypeRef as! Data?
        } else {
            return nil
        }
    }

}

extension Data {

    init<T>(from value: T) {
        var value = value
        self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
    }

    func to<T>(type: T.Type) -> T {
        return self.withUnsafeBytes { $0.load(as: T.self) }
    }
}

I get : result:  3575786387057936644 Any idea? Thanks!

A:

You're overcomplicating things. Your issue lies here:
let result = receivedData.to(type: Int.self)
You were storing an [UInt8] type that you're now converting to an Int type.
You can get your array back by doing:
let result = [UInt8](receivedData)

