-1

我需要将一个 uint8 数组 [UInt8] 存储到钥匙串中。这似乎有效。然后我需要加载并使用这个先前存储的数据,但打印的结果不符合预期的数组。我需要恢复存储的完全相同的内容。

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

我明白了:有result: 3575786387057936644什么想法吗?谢谢!

4

2 回答 2

1

你把事情复杂化了。你的问题在这里:

let result = receivedData.to(type: Int.self)

您正在存储一种[UInt8]类型,现在您正在将其转换为一种Int类型。

您可以通过以下方式取回您的阵列:

let result = [UInt8](receivedData)

于 2020-04-23T06:25:17.937 回答
0

只是在做:

if let receivedData = self.load(key: "PrivKey") {
                let array: [UInt8] = Array(receivedData)
                print(array)
            }

做这项工作。;-)

于 2020-04-23T06:25:10.683 回答