/
base64u.go
73 lines (60 loc) · 2.11 KB
/
base64u.go
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
64
65
66
67
68
69
70
71
72
73
package enc
// NOTE: This is a translation of base64u.c from IODINE project into go.
/*
* Copyright (c) 2006-2014 Erik Ekman <yarrick@kryo.se>,
* 2006-2009 Bjorn Andersson <flex@kryo.se>
* Mostly rewritten 2009 J.A.Bezemer@opensourcepartners.nl
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
import (
"encoding/base64"
"fmt"
"github.com/pkg/errors"
)
const (
cb64u = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789_"
)
var iodineBase64uEncoding = base64.NewEncoding(cb64u).WithPadding(base64.NoPadding)
// -------------------------------------------------------
// Base64uEncoder encodes 3 bytes to 4 characters and uses an alternative character map.
type Base64uEncoder struct {
}
func (b *Base64uEncoder) Name() string {
return "Base64u"
}
func (b *Base64uEncoder) String() string {
return fmt.Sprintf("%v(%v)", b.Name(), string(b.Code()))
}
func (b *Base64uEncoder) Code() byte {
return 'U'
}
func (b *Base64uEncoder) Encode(data []byte) []byte {
return []byte(iodineBase64uEncoding.EncodeToString(data))
}
func (b *Base64uEncoder) Decode(data []byte) ([]byte, error) {
res, err := iodineBase64uEncoding.DecodeString(string(data))
if err != nil {
err = errors.WithStack(err)
return nil, err
}
return res, nil
}
func (b *Base64uEncoder) TestPatterns() [][]byte {
return [][]byte{
[]byte("aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ_0129-"),
}
}
func (b *Base64uEncoder) Ratio() float64 {
return 4.0 / 3.0
}