Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Foundation/Encoding.swift3// Description: Hex and base64url helpers (WebAuthn uses unpadded base64url everywhere).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public extension Data {10 var hex: String { map { String(format: "%02x", $0) }.joined() }1112 init?(hex: String) {13 var s = Substring(hex)14 if s.hasPrefix("0x") || s.hasPrefix("0X") { s = s.dropFirst(2) }15 guard s.count % 2 == 0 else { return nil }16 var out = Data(capacity: s.count / 2)17 var i = s.startIndex18 while i < s.endIndex {19 let j = s.index(i, offsetBy: 2)20 guard let b = UInt8(s[i..<j], radix: 16) else { return nil }21 out.append(b); i = j22 }23 self = out24 }2526 var base64URL: String {27 base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")28 }2930 /** Strict unpadded-or-padded base64url; rejects characters outside the alphabet. */31 init?(base64URL s: String) {32 guard s.unicodeScalars.allSatisfy({ ($0.value < 128) && (CharacterSet.alphanumerics.contains($0) || $0 == "-" || $0 == "_" || $0 == "=") }) else { return nil }33 var t = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/").replacingOccurrences(of: "=", with: "")34 while t.count % 4 != 0 { t.append("=") }35 guard let d = Data(base64Encoded: t) else { return nil }36 self = d37 }38}39