SPB Git

Repository Public

Base32.swift 1.8 KB 44 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Crypto/Base32.swift3// Description: RFC 4648 base32 (upper-case alphabet A–Z 2–7) WITHOUT padding, as Stellar strkeys use it. Decoding is strict:4//              no lower case, no "=", no leftover group and zero pad bits only, so one byte string has exactly one encoding.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910public enum Base32 {11    private static let alphabet = [UInt8]("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".utf8)1213    public static func encode(_ bytes: [UInt8]) -> String {14        var out = [UInt8](), acc: UInt32 = 0, bits = 015        for b in bytes {16            acc = (acc << 8) | UInt32(b); bits += 817            while bits >= 5 { bits -= 5; out.append(alphabet[Int((acc >> UInt32(bits)) & 31)]) }18            acc &= (1 << UInt32(bits)) - 119        }20        if bits > 0 { out.append(alphabet[Int((acc << UInt32(5 - bits)) & 31)]) }21        return String(decoding: out, as: UTF8.self)22    }2324    /** nil on any character outside the alphabet, on a leftover 5-bit group or on non-zero padding bits. */25    public static func decode(_ text: String) -> [UInt8]? { decode(ascii: [UInt8](text.utf8)) }2627    static func decode(ascii: [UInt8]) -> [UInt8]? {28        var out = [UInt8](), acc: UInt32 = 0, bits = 029        for c in ascii {30            let v: UInt3231            switch c {32            case 65...90: v = UInt32(c - 65)33            case 50...55: v = UInt32(c - 50 + 26)34            default: return nil35            }36            acc = (acc << 5) | v; bits += 537            if bits >= 8 { bits -= 8; out.append(UInt8((acc >> UInt32(bits)) & 0xff)) }38            acc &= (1 << UInt32(bits)) - 139        }40        guard bits < 5, acc == 0 else { return nil }41        return out42    }43}44
Files main
Menu

Theme