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
//
// Base64URL.swift
// AT-IRC
//
// Base64url helpers used by JWT/DPoP/PKCE encoding.
//
import Foundation
enum Base64URL {
static func encode(_ data: Data) -> String {
data.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
static func decode(_ string: String) -> Data? {
var s = string
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
let remainder = s.count % 4
if remainder > 0 {
s += String(repeating: "=", count: 4 - remainder)
}
return Data(base64Encoded: s)
}
}
extension Data {
/// Random bytes from the system CSPRNG.
static func random(count: Int) -> Data {
var bytes = [UInt8](repeating: 0, count: count)
_ = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)
return Data(bytes)
}
}