Skip to content

Commit 858aaa6

Browse files
committed
fix base64url and add percent convenience
1 parent bd16c70 commit 858aaa6

File tree

4 files changed

+53
-4
lines changed

4 files changed

+53
-4
lines changed

Sources/Bits/Base64Encoder.swift

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,22 @@ public final class Base64Encoder {
2626
return nil
2727
}
2828
}
29-
29+
30+
let decodeMap: Base64Encoder.ByteMap = { byte in
31+
switch byte {
32+
case Byte.hyphen:
33+
return 62
34+
case Byte.underscore:
35+
return 63
36+
default:
37+
return nil
38+
}
39+
}
40+
3041
return Base64Encoder(
3142
padding: nil,
32-
encodeMap: encodeMap
43+
encodeMap: encodeMap,
44+
decodeMap: decodeMap
3345
)
3446
}
3547

Sources/Bits/Bytes+Base64.swift

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
import Foundation
2-
31
extension Sequence where Iterator.Element == Byte {
42
public var base64Encoded: Bytes {
53
let bytes = Array(self)

Sources/Bits/Bytes+Percent.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import Foundation
2+
3+
extension Sequence where Iterator.Element == Byte {
4+
public var percentDecoded: Bytes {
5+
return makeString()
6+
.removingPercentEncoding?
7+
.makeBytes() ?? []
8+
}
9+
10+
public var percentEncodedForURLQuery: Bytes {
11+
return makeString()
12+
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)?
13+
.makeBytes() ?? []
14+
}
15+
16+
public var percentEncodedForURLPath: Bytes {
17+
return makeString()
18+
.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)?
19+
.makeBytes() ?? []
20+
}
21+
22+
public var percentEncodedForURLHost: Bytes {
23+
return makeString()
24+
.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)?
25+
.makeBytes() ?? []
26+
}
27+
28+
public var percentEncodedForURLFragment: Bytes {
29+
return makeString()
30+
.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)?
31+
.makeBytes() ?? []
32+
}
33+
}

Tests/BitsTests/ByteTests.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,4 +153,10 @@ class ByteTests: XCTestCase {
153153
"aa"
154154
)
155155
}
156+
157+
public func testBase64URLDecodeJWT() {
158+
let jwt = "Aw_Ma0impeGEaCQn6AramTZ6hXeW0bJm_3dKbiXtJDOBhs1Zm6IgX-uJhuzW0SY2evWL4D2ZX5I90ISAzEdabw".makeBytes()
159+
let decoded = jwt.base64URLDecoded
160+
XCTAssertEqual(decoded.count, 64)
161+
}
156162
}

0 commit comments

Comments
 (0)