package modhex
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
)
|
|
|
|
const hexChars = "0123456789abcdef"
|
|
const modhexChars = "cbdefghijklnrtuv"
|
|
|
|
var modhex2HexMap map[byte]byte
|
|
var hex2ModhexMap map[byte]byte
|
|
|
|
func init() {
|
|
hex2ModhexMap = make(map[byte]byte)
|
|
for i, h := range []byte(hexChars) {
|
|
hex2ModhexMap[h] = modhexChars[i]
|
|
}
|
|
|
|
modhex2HexMap = make(map[byte]byte)
|
|
for i, m := range []byte(modhexChars) {
|
|
modhex2HexMap[m] = hexChars[i]
|
|
}
|
|
}
|
|
|
|
// EncodeHex encodes a hex string into a modhex string
|
|
func EncodeHex(hex string) (string, error) {
|
|
size := len([]byte(hex))
|
|
|
|
if size%2 == 1 {
|
|
return "", errors.New("size of input hex input not even")
|
|
}
|
|
|
|
var modhex = make([]byte, size)
|
|
|
|
for i, h := range []byte(hex) {
|
|
if m, ok := hex2ModhexMap[h]; ok {
|
|
modhex[i] = m
|
|
} else {
|
|
return "", fmt.Errorf("input not hex encoded; position %d", i)
|
|
}
|
|
}
|
|
|
|
return string(modhex), nil
|
|
}
|
|
|
|
// DecodeHex decodes a modhex string into a hex string
|
|
func DecodeHex(modhex string) (string, error) {
|
|
size := len([]byte(modhex))
|
|
|
|
if size%2 == 1 {
|
|
return "", errors.New("size of modhex input not even")
|
|
}
|
|
|
|
var hex = make([]byte, size)
|
|
|
|
for i, m := range []byte(modhex) {
|
|
if h, ok := modhex2HexMap[m]; ok {
|
|
hex[i] = h
|
|
} else {
|
|
return "", fmt.Errorf("input not modhex encoded; position %d", i)
|
|
}
|
|
}
|
|
|
|
return string(hex), nil
|
|
}
|