-
Notifications
You must be signed in to change notification settings - Fork 490
Expand file tree
/
Copy pathCommonUtils.swift
More file actions
57 lines (47 loc) · 1.78 KB
/
CommonUtils.swift
File metadata and controls
57 lines (47 loc) · 1.78 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
import CommonCrypto
import Foundation
import Security
public class CommonUtils {
static let emailRegex = ".+@([a-zA-Z0-9\\-]+\\.)+[a-zA-Z0-9]{2,63}"
public static func isValidEmail(_ email: String) -> Bool {
let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailPredicate.evaluate(with: email)
}
public static func randomNonce(length: Int = 32) -> String {
let characterSet = "0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._"
var result = ""
var remainingLength = length
while remainingLength > 0 {
var randoms = [UInt8](repeating: 0, count: 16)
let errorCode = SecRandomCopyBytes(kSecRandomDefault, randoms.count, &randoms)
if errorCode != errSecSuccess {
fatalError("Unable to generate nonce: OSStatus \(errorCode)")
}
for random in randoms {
if remainingLength == 0 {
break
}
if random < characterSet.count {
let index = characterSet.index(characterSet.startIndex, offsetBy: Int(random))
result.append(characterSet[index])
remainingLength -= 1
}
}
}
return result
}
public static func sha256Hash(of input: String) -> String {
guard let data = input.data(using: .utf8) else { return "" }
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA256($0.baseAddress, CC_LONG(data.count), &hash)
}
return hash.map { String(format: "%02x", $0) }.joined()
}
public static func getQueryParamValue(from urlString: String, paramName: String) -> String? {
guard let urlComponents = URLComponents(string: urlString) else {
return nil
}
return urlComponents.queryItems?.first(where: { $0.name == paramName })?.value
}
}