Contents

pambrozy/bases

A package for encoding and decoding data using Base16, Base32, Base64 and Base85 encodings.

Usage

Encoding data

To encode data, firstly create an encoder, providing an alphabet to the initializer init(alphabet:):

let encoder = Base32.Encoder(alphabet: .rfc4648)

Then use the encode(_:) method:

let encodedString = encoder.encode(dataToEncode)

Alternatively, you can use the base32EncodedString(alphabet:) method of Data:

let encodedString = dataToEncode.base32EncodedString(alphabet: .rfc4648)

Decoding data

To decode data, start by creating a decoder, providing an alphabet to the initializer init(alphabet:):

let decoder = Base32.Decoder(alphabet: .rfc4648)

Then use the decode(_:) method:

do {
    let decodedData = try decoder.decode(stringToDecode)
} catch {
    print("Cannot decode: \(error.localizedDescription)")
}

Alternatively, use one of the Data initializers:

let decodedFromString = Data(base32Encoded: stringToDecode, alphabet: .rfc4648)

let decodedFromData = Data(base32Encoded: dataToDecode, alphabet: .rfc4648)

Using with JSONEncoder and JSONDecoder

You can use the encoders and decoders from this package in JSONEncoder and JSONDecoder.

In the next few examples we will use the Example struct:

struct Example: Codable {
    let data: Data
}

Let's create an instance of it:

let example = Example(data: Data([65, 66, 67]))
Encoding

To encode the struct, create an instance of JSONEncoder and set its dataEncodingStrategy to an appropriate encoder:

let encoder = JSONEncoder()
encoder.dataEncodingStrategy = .base32(alphabet: .rfc4648)

Then encode the data:

do {
    let encodedExample = try encoder.encode(example)
    print(String(decoding: encodedExample, as: UTF8.self))
    // Prints: {"data":"IFBEG==="}
} catch {
    print("Cannot encode: \(error.localizedDescription)")
}
Decoding

To decode a JSON string, create an instance of JSONDecoder and set its dataDecodingStrategy to an appropriate decoder:

let decoder = JSONDecoder()
decoder.dataDecodingStrategy = .base32(alphabet: .rfc4648)

Then decode the data:

do {
    let decodedExample = try decoder.decode(Example.self, from: encodedExample)
    print(Array(decodedExample.data))
    // Prints: [65, 66, 67]
} catch {
    print("Cannot decode: \(error.localizedDescription)")
}

License

Bases is released under the 2-Clause BSD License. See LICENSE for details.

Package Metadata

Repository: pambrozy/bases

Default branch: main

README: README.md