summaryrefslogtreecommitdiff
path: root/simulation/encoding.go
blob: 98d1d4a83ee0c26c1c3306b10b52e232695a17b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main

import (
	"encoding/base32"
	"errors"
	"fmt"
	"net/url"
	"strings"
)

// 32 characters for decoding, using RFC 3548.
const TALER_BASE32_CHARACTER_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"

func talerBase32Encode(byts []byte) string {
	return talerBase32Encoding().EncodeToString(byts)
}

func talerBase32Decode(str string) ([]byte, error) {

	decoded, err := talerBase32Encoding().DecodeString(strings.ToUpper(str))
	if err != nil {
		return nil, err
	}
	return decoded, nil
}

func talerBase32Encoding() *base32.Encoding {
	// 32 characters for decoding, using RFC 3548.
	// character set copied from [TALER-EXCHANGE]/src/util/crypto_confirmation.c
	return base32.NewEncoding(TALER_BASE32_CHARACTER_SET)
}

func ParseWopid(wopid string) ([]byte, error) {

	unescaped, err := url.PathUnescape(wopid)
	if err != nil {
		fmt.Println("encoding", err)
		return nil, errors.New("decoding failed")
	}

	wopidBytes, err := talerBase32Decode(unescaped)
	if err != nil {
		return nil, err
	}

	if len(wopidBytes) != 32 {
		err = errors.New("invalid wopid")
		fmt.Println("encoding", err)
		return nil, err
	}

	return wopidBytes, nil
}

func FormatWopid(wopid []byte) string {

	return url.PathEscape(talerBase32Encode(wopid))
}

func ParseEddsaPubKey(key EddsaPublicKey) ([]byte, error) {

	return talerBase32Decode(string(key))
}