Skip to content

Commit

Permalink
Clean up Base64 encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
Mazyod committed Apr 16, 2019
1 parent 8a474d4 commit d82f504
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 36 deletions.
2 changes: 1 addition & 1 deletion Sources/HttpParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public class HttpParser {
}
return request
}

private func readBody(_ socket: Socket, size: Int) throws -> [UInt8] {
return try socket.read(length: size)
}
Expand Down
34 changes: 2 additions & 32 deletions Sources/String+BASE64.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,38 +9,8 @@ import Foundation


extension String {

private static let CODES = [UInt8]("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".utf8)

public static func toBase64(_ data: [UInt8]) -> String? {

// Based on: https://en.wikipedia.org/wiki/Base64#Sample_Implementation_in_Java

var result = [UInt8]()
var tmp: UInt8
for index in stride(from: 0, to: data.count, by: 3) {
let byte = data[index]
tmp = (byte & 0xFC) >> 2;
result.append(CODES[Int(tmp)])
tmp = (byte & 0x03) << 4;
if index + 1 < data.count {
tmp |= (data[index + 1] & 0xF0) >> 4;
result.append(CODES[Int(tmp)]);
tmp = (data[index + 1] & 0x0F) << 2;
if (index + 2 < data.count) {
tmp |= (data[index + 2] & 0xC0) >> 6;
result.append(CODES[Int(tmp)]);
tmp = data[index + 2] & 0x3F;
result.append(CODES[Int(tmp)]);
} else {
result.append(CODES[Int(tmp)]);
result.append(contentsOf: [UInt8]("=".utf8));
}
} else {
result.append(CODES[Int(tmp)]);
result.append(contentsOf: [UInt8]("==".utf8));
}
}
return String(bytes: result, encoding: .utf8)
public static func toBase64(_ data: [UInt8]) -> String {
return Data(bytes: data).base64EncodedString()
}
}
4 changes: 1 addition & 3 deletions Sources/WebSockets.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,7 @@ public func websocket(

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

0 comments on commit d82f504

Please sign in to comment.