-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSTEncrypt.swift
More file actions
337 lines (296 loc) · 11.4 KB
/
STEncrypt.swift
File metadata and controls
337 lines (296 loc) · 11.4 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
//
// STEncrypt.swift
// STBaseProject
//
// Created by 寒江孤影 on 2018/12/22.
//
import Security
import Foundation
import CryptoKit
import CommonCrypto
// MARK: - 哈希算法类型
public enum STHashAlgorithm {
case md5
case sha1
case sha256
case sha384
case sha512
}
// MARK: - String 加密扩展
public extension String {
/// 计算字符串的哈希值
/// - Parameter algorithm: 哈希算法
/// - Returns: 哈希值字符串
func st_hash(algorithm: STHashAlgorithm) -> String {
let inputData = Data(self.utf8)
return inputData.st_hash(algorithm: algorithm)
}
/// MD5 哈希
/// - Returns: MD5 哈希字符串
func st_md5() -> String {
return st_hash(algorithm: .md5)
}
/// SHA1 哈希
/// - Returns: SHA1 哈希字符串
func st_sha1() -> String {
return st_hash(algorithm: .sha1)
}
/// SHA256 哈希
/// - Returns: SHA256 哈希字符串
func st_sha256() -> String {
return st_hash(algorithm: .sha256)
}
/// SHA384 哈希
/// - Returns: SHA384 哈希字符串
func st_sha384() -> String {
return st_hash(algorithm: .sha384)
}
/// SHA512 哈希
/// - Returns: SHA512 哈希字符串
func st_sha512() -> String {
return st_hash(algorithm: .sha512)
}
/// 计算 HMAC
/// - Parameters:
/// - key: 密钥字符串
/// - algorithm: 哈希算法
/// - Returns: HMAC 字符串
func st_hmac(key: String, algorithm: STHashAlgorithm) -> String {
let data = Data(self.utf8)
let keyData = Data(key.utf8)
return data.st_hmac(key: keyData, algorithm: algorithm)
}
/// HMAC-SHA256
/// - Parameter key: 密钥字符串
/// - Returns: HMAC-SHA256 字符串
func st_hmacSha256(key: String) -> String {
return st_hmac(key: key, algorithm: .sha256)
}
/// HMAC-SHA512
/// - Parameter key: 密钥字符串
/// - Returns: HMAC-SHA512 字符串
func st_hmacSha512(key: String) -> String {
return st_hmac(key: key, algorithm: .sha512)
}
/// AES-256-GCM 加密
/// - Parameters:
/// - key: 密钥字符串
/// - nonce: 随机数(可选,自动生成)
/// - Returns: 加密结果,包含密文、随机数和认证标签
func st_encryptAES256GCM(key: String, nonce: AES.GCM.Nonce? = nil) throws -> (ciphertext: Data, nonce: AES.GCM.Nonce, tag: Data) {
let keyData = Data(key.utf8)
guard keyData.count == 32 else {
throw STCryptoError.invalidKey
}
return try Data(self.utf8).st_encryptAES256GCM(key: keyData, nonce: nonce)
}
/// AES-256-GCM 解密
/// - Parameters:
/// - ciphertext: 密文数据
/// - key: 密钥字符串
/// - nonce: 随机数
/// - tag: 认证标签
/// - Returns: 解密后的字符串
func st_decryptAES256GCM(ciphertext: Data, key: String, nonce: AES.GCM.Nonce, tag: Data) throws -> String {
let keyData = Data(key.utf8)
guard keyData.count == 32 else {
throw STCryptoError.invalidKey
}
let decryptedData = try keyData.st_decryptAES256GCM(ciphertext: ciphertext, key: keyData, nonce: nonce, tag: tag)
guard let string = String(data: decryptedData, encoding: .utf8) else {
throw STCryptoError.decryptionFailed
}
return string
}
/// PBKDF2 密钥派生
/// - Parameters:
/// - salt: 盐值字符串
/// - iterations: 迭代次数
/// - keyLength: 密钥长度
/// - Returns: 派生的密钥数据
func st_pbkdf2(salt: String, iterations: Int = 10000, keyLength: Int = 32) throws -> Data {
let passwordData = Data(self.utf8)
let saltData = Data(salt.utf8)
return try passwordData.st_pbkdf2(salt: saltData, iterations: iterations, keyLength: keyLength)
}
/// 生成随机字符串
/// - Parameters:
/// - length: 字符串长度
/// - characters: 字符集
/// - Returns: 随机字符串
static func st_randomString(length: Int, characters: String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") -> String {
guard length > 0, !characters.isEmpty else {
return ""
}
return String((0..<length).compactMap { _ in characters.randomElement() })
}
/// 生成随机十六进制字符串
/// - Parameter length: 字符串长度
/// - Returns: 随机十六进制字符串
static func st_randomHexString(length: Int) -> String {
let randomData = STDataUtils.randomData(length: length / 2)
return randomData.hexEncodedString()
}
}
// MARK: - Data 加密扩展
public extension Data {
/// 计算数据的哈希值
/// - Parameter algorithm: 哈希算法
/// - Returns: 哈希值字符串
func st_hash(algorithm: STHashAlgorithm) -> String {
switch algorithm {
case .md5:
let digest = Insecure.MD5.hash(data: self)
return digest.map { String(format: "%02x", $0) }.joined()
case .sha1:
let digest = Insecure.SHA1.hash(data: self)
return digest.map { String(format: "%02x", $0) }.joined()
case .sha256:
let digest = SHA256.hash(data: self)
return digest.map { String(format: "%02x", $0) }.joined()
case .sha384:
let digest = SHA384.hash(data: self)
return digest.map { String(format: "%02x", $0) }.joined()
case .sha512:
let digest = SHA512.hash(data: self)
return digest.map { String(format: "%02x", $0) }.joined()
}
}
/// 计算 HMAC
/// - Parameters:
/// - key: 密钥数据
/// - algorithm: 哈希算法
/// - Returns: HMAC 字符串
func st_hmac(key: Data, algorithm: STHashAlgorithm) -> String {
let symmetricKey = SymmetricKey(data: key)
switch algorithm {
case .sha256:
let hmac = HMAC<SHA256>.authenticationCode(for: self, using: symmetricKey)
return Data(hmac).hexEncodedString()
case .sha384:
let hmac = HMAC<SHA384>.authenticationCode(for: self, using: symmetricKey)
return Data(hmac).hexEncodedString()
case .sha512:
let hmac = HMAC<SHA512>.authenticationCode(for: self, using: symmetricKey)
return Data(hmac).hexEncodedString()
default:
// 对于不支持的算法,使用 SHA256
let hmac = HMAC<SHA256>.authenticationCode(for: self, using: symmetricKey)
return Data(hmac).hexEncodedString()
}
}
/// AES-256-GCM 加密
/// - Parameters:
/// - key: 密钥数据
/// - nonce: 随机数(可选,自动生成)
/// - Returns: 加密结果,包含密文、随机数和认证标签
func st_encryptAES256GCM(key: Data, nonce: AES.GCM.Nonce? = nil) throws -> (ciphertext: Data, nonce: AES.GCM.Nonce, tag: Data) {
guard key.count == 32 else {
throw STCryptoError.invalidKey
}
let symmetricKey = SymmetricKey(data: key)
let usedNonce = nonce ?? AES.GCM.Nonce()
do {
let sealedBox = try AES.GCM.seal(self, using: symmetricKey, nonce: usedNonce)
return (sealedBox.ciphertext, usedNonce, sealedBox.tag)
} catch {
throw STCryptoError.encryptionFailed
}
}
func st_decryptAES256GCM(ciphertext: Data, key: Data, nonce: AES.GCM.Nonce, tag: Data) throws -> Data {
guard key.count == 32 else {
throw STCryptoError.invalidKey
}
let symmetricKey = SymmetricKey(data: key)
do {
let sealedBox = try AES.GCM.SealedBox(nonce: nonce, ciphertext: ciphertext, tag: tag)
return try AES.GCM.open(sealedBox, using: symmetricKey)
} catch {
throw STCryptoError.decryptionFailed
}
}
/// PBKDF2 密钥派生
/// - Parameters:
/// - salt: 盐值数据
/// - iterations: 迭代次数
/// - keyLength: 密钥长度
/// - Returns: 派生的密钥数据
func st_pbkdf2(salt: Data, iterations: Int = 10000, keyLength: Int = 32) throws -> Data {
guard iterations > 0 else {
throw STCryptoError.invalidIterations
}
guard keyLength > 0 else {
throw STCryptoError.invalidKey
}
var derivedKey = Data(count: keyLength)
let result = derivedKey.withUnsafeMutableBytes { derivedKeyBytes in
self.withUnsafeBytes { passwordBytes in
salt.withUnsafeBytes { saltBytes in
CCKeyDerivationPBKDF(
CCPBKDFAlgorithm(kCCPBKDF2),
passwordBytes.bindMemory(to: Int8.self).baseAddress,
self.count,
saltBytes.bindMemory(to: UInt8.self).baseAddress,
salt.count,
CCPseudoRandomAlgorithm(kCCPRFHmacAlgSHA256),
UInt32(iterations),
derivedKeyBytes.bindMemory(to: UInt8.self).baseAddress,
keyLength
)
}
}
}
guard result == kCCSuccess else {
throw STCryptoError.keyGenerationFailed
}
return derivedKey
}
}
// MARK: - 加密工具类
public struct STEncryptionUtils {
/// 生成随机密钥
/// - Parameter length: 密钥长度(字节)
/// - Returns: 随机密钥数据
public static func st_generateRandomKey(length: Int = 32) -> Data {
return STDataUtils.randomData(length: length)
}
/// 生成随机盐值
/// - Parameter length: 盐值长度(字节)
/// - Returns: 随机盐值数据
public static func st_generateRandomSalt(length: Int = 16) -> Data {
return STDataUtils.randomData(length: length)
}
/// 验证密钥强度
/// - Parameter key: 密钥字符串
/// - Returns: 密钥强度评分(0-100)
public static func st_validateKeyStrength(_ key: String) -> Int {
var score = 0
// 长度评分
if key.count >= 8 { score += 20 }
if key.count >= 12 { score += 20 }
if key.count >= 16 { score += 20 }
// 字符类型评分
if key.rangeOfCharacter(from: .lowercaseLetters) != nil { score += 10 }
if key.rangeOfCharacter(from: .uppercaseLetters) != nil { score += 10 }
if key.rangeOfCharacter(from: .decimalDigits) != nil { score += 10 }
if key.rangeOfCharacter(from: .punctuationCharacters) != nil { score += 10 }
return min(score, 100)
}
/// 安全的字符串比较(防止时序攻击)
/// - Parameters:
/// - lhs: 第一个字符串
/// - rhs: 第二个字符串
/// - Returns: 是否相等
public static func st_secureCompare(_ lhs: String, _ rhs: String) -> Bool {
let lhsData = Data(lhs.utf8)
let rhsData = Data(rhs.utf8)
return STDataUtils.constantTimeEquals(lhsData, rhsData)
}
/// 生成安全的随机令牌
/// - Parameter length: 令牌长度
/// - Returns: 随机令牌字符串
public static func st_generateSecureToken(length: Int = 32) -> String {
let randomData = STDataUtils.randomData(length: length)
return randomData.base64URLSafeEncodedString()
}
}