简体   繁体   English

Swift 中结构数组的 SHA1 hash

[英]SHA1 hash of an array of structs in Swift

I need to produce an SHA1 hash of an array of custom structs in Swift.我需要在 Swift 中生成自定义结构数组的 SHA1 hash。 The app receives the array from an external source at periodic intervals.应用程序定期从外部源接收数组。 The objective is to be able to tell if the data changed after last update, without holding a full copy of the data.目标是能够判断数据在上次更新后是否发生了变化,而无需保存数据的完整副本。

How can I do this?我怎样才能做到这一点?

struct Person {
    let firstName: String
    let lastName: String
}

let people = [
    Person(firstName: "John", lastName: "Appleseed"),
    Person(firstName: "Mike", lastName: "Doe")
]

// Produce an SHA1 digest of `people` here?

One way to do this could be using JSON with sorted keys:一种方法是使用 JSON 和排序键:

struct Person: Encodable {
    let firstName: String
    let lastName: String
}

let people = [
    Person(firstName: "John", lastName: "Appleseed"),
    Person(firstName: "Mike", lastName: "Doe")
]

let encoder = JSONEncoder()
encoder.outputFormatting = .sortedKeys
let data = try! encoder.encode(people)

var digest = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes { ptr in
    CC_SHA1(ptr.baseAddress, CC_LONG(data.count), &digest)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM