This repository has been archived by the owner on May 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Sum.swift
108 lines (84 loc) · 2.61 KB
/
Sum.swift
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
//
// Sum.swift
// SwiftMultihash
//
// Created by Matteo Sartori on 30/05/15.
// Licensed under MIT See LICENCE for details
//
import Foundation
import CommonCrypto
enum MultihashSumError : Error {
case invalidMultihash(Int)
case notImplemented
case noDefaultLength(Int)
}
// English language error descriptions
extension MultihashSumError {
var description: String {
get {
switch self {
case .invalidMultihash(let code):
return "Invalid multihash code \(code)"
case .notImplemented:
return "Function not implemented. Complain to lib maintainer."
case .noDefaultLength(let code):
return "No default length for code \(code)"
}
}
}
}
//func sumError(code: Int, msg: String) -> NSError {
// return NSError(domain: ErrDomain, code: code, userInfo: [NSLocalizedDescriptionKey : msg])
//}
public func sum(_ data: [UInt8], _ code: Int, _ length: Int) throws -> Multihash {
if validCode(code) == false {
throw MultihashSumError.invalidMultihash(code)
}
var sumData: [UInt8]
switch code {
case SHA1:
sumData = sumSHA1(data)
case SHA2_256:
sumData = sumSHA256(data)
case SHA2_512:
sumData = sumSHA512(data)
default:
throw MultihashSumError.notImplemented
}
var len: Int = length
if length < 0 {
guard let l = DefaultLengths[code] else {
throw MultihashSumError.noDefaultLength(code)
}
len = l
}
let bytes: [UInt8] = Array(sumData[0..<len])
return Multihash(try SwiftMultihash.encodeBuf(bytes,code: code))
}
func sumSHA1(_ data: [UInt8]) -> [UInt8] {
let len = Int(CC_SHA1_DIGEST_LENGTH)
var digest = [UInt8](repeating: 0, count: len)
CC_SHA1(data, CC_LONG(data.count), &digest)
return Array(digest[0..<len])
}
func sumSHA256(_ data: [UInt8]) -> [UInt8] {
let len = Int(CC_SHA256_DIGEST_LENGTH)
var digest = [UInt8](repeating: 0, count: len)
CC_SHA256(data, CC_LONG(data.count), &digest)
return Array(digest[0..<len])
}
func sumSHA512(_ data: [UInt8]) -> [UInt8] {
let len = Int(CC_SHA512_DIGEST_LENGTH)
var digest = [UInt8](repeating: 0, count: len)
CC_SHA512(data, CC_LONG(data.count), &digest)
return Array(digest[0..<len])
}
// No SHA3 Swift lib yet?
//func sumSHA3(data: [UInt8]) -> [UInt8] {
// let dat = NSData(bytes: data, length: data.count)
//
// if let bytes = dat. no sha3 ?.arrayOfBytes() {
// return Array(bytes[0..<20])
// }
// return []
//}