Class Bech32

java.lang.Object
com.codename1.crypto.encoding.Bech32

public final class Bech32 extends Object
Bech32 (BIP-173) and Bech32m (BIP-350) encoding, bit regrouping and the SegWit address helpers built on them.
  • Field Details

    • BECH32

      public static final int BECH32
      Checksum variant constant for original Bech32 (BIP-173).
      See Also:
    • BECH32M

      public static final int BECH32M
      Checksum variant constant for Bech32m (BIP-350).
      See Also:
  • Method Details

    • encode

      public static String encode(String hrp, byte[] data, int variant)

      Encodes an HRP and 5-bit data into a Bech32 or Bech32m string.

      Parameters
      • hrp: the human readable part, 1 to 83 printable ASCII characters (33 to 126); uppercase is folded
      • data: values in the range 0 to 31
      • variant: BECH32 or BECH32M
      Returns

      the lowercase encoded string

      Throws
      • IllegalArgumentException: for an invalid HRP, data value, variant or total length over 90
    • decode

      public static Bech32.Decoded decode(String str)

      Decodes and validates a Bech32 or Bech32m string.

      Parameters
      • str: the encoded text
      Returns

      the HRP, data and checksum variant

      Throws
      • IllegalArgumentException: for any violation of the BIP-173/BIP-350 rules
    • convertBits

      public static byte[] convertBits(byte[] data, int fromBits, int toBits, boolean pad)

      Regroups bits, for example 8-bit bytes to 5-bit values and back.

      Parameters
      • data: input values, each fitting in fromBits bits
      • fromBits: input group size, 1 to 8
      • toBits: output group size, 1 to 8
      • pad: whether leftover bits are zero padded (encoding) or must be zero and shorter than a group (decoding)
      Returns

      the regrouped values

      Throws
      • IllegalArgumentException: for an out-of-range value or invalid padding
    • encodeSegwitAddress

      public static String encodeSegwitAddress(String hrp, int witnessVersion, byte[] program)

      Encodes a SegWit address, using Bech32 for witness version 0 and Bech32m otherwise.

      Parameters
      • hrp: the network prefix such as bc or tb
      • witnessVersion: 0 to 16
      • program: the witness program, 2 to 40 bytes (20 or 32 for version 0)
      Returns

      the address

      Throws
      • IllegalArgumentException: if the version or program length is invalid
    • decodeSegwitAddress

      public static Bech32.SegwitAddress decodeSegwitAddress(String hrp, String addr)

      Decodes and validates a SegWit address.

      Parameters
      • hrp: the expected network prefix, compared without regard to case
      • addr: the address
      Returns

      the witness version and program

      Throws
      • IllegalArgumentException: if the address is invalid or has another HRP