Skip to content

Commit

Permalink
Close #48 Allow base64 strings with missing equal signs at the end
Browse files Browse the repository at this point in the history
  • Loading branch information
kaphacius committed Mar 9, 2024
1 parent 0ee0a7b commit 8f6060f
Showing 1 changed file with 35 additions and 6 deletions.
41 changes: 35 additions & 6 deletions JustTags/Utils/InputParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ struct InputParser {
}

static func parse(input: String) throws -> [BERTLV] {
var parsedData: Data? = nil
var parsedData: [UInt8]? = nil

let hexStringBytes = input
.replacingOccurrences(of: " ", with: "")
Expand All @@ -26,11 +26,10 @@ struct InputParser {
let compactedHexStringBytes = hexStringBytes.compactMap { $0 }

if hexStringBytes.count == compactedHexStringBytes.count {
parsedData = Data(compactedHexStringBytes)
} else if let base64Bytes = Data(
base64Encoded: input, options: .ignoreUnknownCharacters
) {
parsedData = Data(base64Bytes)
// Attempt parsing a hex string
parsedData = compactedHexStringBytes
} else if let base64Bytes = parseBase64(input: input) {
parsedData = base64Bytes
}

guard let parsedData = parsedData else {
Expand All @@ -40,4 +39,34 @@ struct InputParser {
return try BERTLV.parse(bytes: [UInt8](parsedData))
}

static private func parseBase64(input: String) -> [UInt8]? {
// Attempt parsing a base64 string
if let base64Bytes = Data(
base64Encoded: input, options: .ignoreUnknownCharacters
) {
return [UInt8](base64Bytes)
}

// Attempt parsing a base64 string with missing padding
// Base64 data is encoded with groups of 4 characters
let groupSize = 4

// Check if the last group might be missing padding
let lastGroupSize = input.count % groupSize

// Only 2 and 3 characters in the last group are allowed
guard lastGroupSize == 2 || lastGroupSize == 3 else { return nil }

let paddedInput = input.appending(String(repeating: "=", count: groupSize - lastGroupSize))

if let base64Bytes = Data(
base64Encoded: paddedInput, options: .ignoreUnknownCharacters
) {
// Attempt parsing a base64 string
return [UInt8](base64Bytes)
}

return nil
}

}

0 comments on commit 8f6060f

Please sign in to comment.