Skip to content

Commit b99669e

Browse files
committed
Clean up Base64 encoding
# Conflicts: # Sources/HttpParser.swift # XCode/Sources/String+BASE64.swift
1 parent 88996c0 commit b99669e

File tree

2 files changed

+3
-35
lines changed

2 files changed

+3
-35
lines changed

XCode/Sources/String+BASE64.swift

Lines changed: 2 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -9,37 +9,7 @@ import Foundation
99

1010
extension String {
1111

12-
private static let CODES = [UInt8]("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".utf8)
13-
14-
public static func toBase64(_ data: [UInt8]) -> String? {
15-
16-
// Based on: https://en.wikipedia.org/wiki/Base64#Sample_Implementation_in_Java
17-
18-
var result = [UInt8]()
19-
var tmp: UInt8
20-
for index in stride(from: 0, to: data.count, by: 3) {
21-
let byte = data[index]
22-
tmp = (byte & 0xFC) >> 2
23-
result.append(CODES[Int(tmp)])
24-
tmp = (byte & 0x03) << 4
25-
if index + 1 < data.count {
26-
tmp |= (data[index + 1] & 0xF0) >> 4
27-
result.append(CODES[Int(tmp)])
28-
tmp = (data[index + 1] & 0x0F) << 2
29-
if index + 2 < data.count {
30-
tmp |= (data[index + 2] & 0xC0) >> 6
31-
result.append(CODES[Int(tmp)])
32-
tmp = data[index + 2] & 0x3F
33-
result.append(CODES[Int(tmp)])
34-
} else {
35-
result.append(CODES[Int(tmp)])
36-
result.append(contentsOf: [UInt8]("=".utf8))
37-
}
38-
} else {
39-
result.append(CODES[Int(tmp)])
40-
result.append(contentsOf: [UInt8]("==".utf8))
41-
}
42-
}
43-
return String(bytes: result, encoding: .utf8)
12+
public static func toBase64(_ data: [UInt8]) -> String {
13+
return Data(data).base64EncodedString()
4414
}
4515
}

XCode/Sources/WebSockets.swift

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,9 +139,7 @@ public func websocket(
139139

140140
disconnected?(session)
141141
}
142-
guard let secWebSocketAccept = String.toBase64((secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").sha1()) else {
143-
return HttpResponse.internalServerError
144-
}
142+
let secWebSocketAccept = String.toBase64((secWebSocketKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").sha1())
145143
let headers = ["Upgrade": "WebSocket", "Connection": "Upgrade", "Sec-WebSocket-Accept": secWebSocketAccept]
146144
return HttpResponse.switchProtocols(headers, protocolSessionClosure)
147145
}

0 commit comments

Comments
 (0)