文章

对字节进行hash编码

灵感来至:https://help.aliyun.com/document_detail/176429.html?spm=a2c4g.131156.0.i1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import CommonCrypto
import CryptoKit

let username = "rambo"
// 一个byte=8bit,也就是UInt8
// 三个字节的随机数
var tokenData = (0..<3).map { _ in
    UInt8(arc4random_uniform(UInt32(UInt8.max)))
}
// tokenData就是三个字节的数组 [UInt8]。例如:[0xA1, 0x11, 0x82]
let randomString = tokenData.map { String(format: "%02X", $0) }.joined()
print(randomString)// 将字节按16进制转化为字符串进行输出 A11182

let userData = username.data(using: .utf8)!
//  将 Data 转换为 byte 数组
let userByte = userData.map { $0 }
tokenData = tokenData + userByte
// X x 表示大写还是小写
let origin = tokenData.map { String(format: "%02X", $0) }.joined()
print(origin)

// 将字节数组转换为 Data
let data = Data(tokenData)

/**** iOS 13之后可以使用SHA256进行hash *****/
// 使用 SHA-256 计算哈希值
let hashResult = SHA256.hash(data: data)
/**************/

/*****iOS 12可以使用下面的********/
// 创建足够的空间来存放 SHA-256 哈希值(它固定为 32 个字节)
var hashResult = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
// 使用 CommonCrypto 进行 SHA-256 计算
data.withUnsafeBytes { body in
    _ = CC_SHA256(body.baseAddress!, CC_LONG(data.count), &hashResult)
}
/***************/

// 将哈希值转换为 Data
let hashData = Data(hashResult)
// 若要将哈希值转换为十六进制字符串以方便查看
let hexString = hashData.map { String(format: "%02hhX", $0) }.joined()
print(hexString)
// 输出32位的token
print(hexString[0..<32])




func hexToByteArray(inHex: String) -> [UInt8] {
    var inHex_ = inHex
    if inHex.count % 2 == 1 {
        inHex_ = "0" + inHex
    }
    let length = inHex_.count / 2
    var byteArray = [UInt8](repeating: 0, count: length)

    for i in stride(from: 0, to: length, by: 1) {
        if let decimal = self.hexToDecimal(hex: inHex_[(i*2) ... (i*2 + 1)]) {
            byteArray[i] = UInt8(decimal)
        } else {
            // 如果十六进制字符串中有非有效字符,这里需要处理错误
            fatalError("Invalid hexadecimal value in the string")
        }
    }

    return byteArray
}

func hexToDecimal(hex: String) -> Int? {
    return Int(hex, radix: 16)
}

extension String {
    subscript(bounds: CountableClosedRange<Int>) -> String {
        let start = index(startIndex, offsetBy: bounds.lowerBound)
        let end = index(startIndex, offsetBy: bounds.upperBound)
        return String(self[start ... end])
    }

    subscript(bounds: CountableRange<Int>) -> String {
        let start = index(startIndex, offsetBy: bounds.lowerBound)
        let end = index(startIndex, offsetBy: bounds.upperBound)
        return String(self[start..<end])
    }
}
本文由作者按照 CC BY 4.0 进行授权