-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShortkeyGenerator.swift
34 lines (30 loc) · 1.13 KB
/
ShortkeyGenerator.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
import Foundation
class ShortkeyGenerator {
enum Error: Swift.Error {
case randomBase64BytesGenerationFailed
}
func generateRandomBase64Bytes() throws -> String {
var encodedString = Data(count: 8)
let result = encodedString.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, 8, $0.baseAddress!)
}
if result == errSecSuccess {
return replaceUnwantedBytesChars(encodedString.base64EncodedString())
}
throw Error.randomBase64BytesGenerationFailed
}
func replaceUnwantedBytesChars(_ encodedString: String) -> String {
var pureEncodedString = encodedString.replacingOccurrences(of: "/", with: "_")
pureEncodedString = pureEncodedString.replacingOccurrences(of: "+", with: "-")
pureEncodedString = String(pureEncodedString.dropLast()) // Last character with base64 is '=' sign
return pureEncodedString
}
func generate() throws -> String {
do {
let shortkey = try generateRandomBase64Bytes()
return shortkey
} catch {
throw error
}
}
}