1// Copyright 2011 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5// Package base32 implements base32 encoding as specified by RFC 4648.
6package base32
7
8import (
9	"io"
10	"strconv"
11)
12
13/*
14 * Encodings
15 */
16
17// An Encoding is a radix 32 encoding/decoding scheme, defined by a
18// 32-character alphabet. The most common is the "base32" encoding
19// introduced for SASL GSSAPI and standardized in RFC 4648.
20// The alternate "base32hex" encoding is used in DNSSEC.
21type Encoding struct {
22	encode    string
23	decodeMap [256]byte
24	padChar   rune
25}
26
27// Alphabet returns the Base32 alphabet used
28func (enc *Encoding) Alphabet() string {
29	return enc.encode
30}
31
32const (
33	StdPadding rune = '='
34	NoPadding  rune = -1
35)
36
37const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
38const encodeHex = "0123456789ABCDEFGHIJKLMNOPQRSTUV"
39
40// NewEncoding returns a new Encoding defined by the given alphabet,
41// which must be a 32-byte string.
42func NewEncoding(encoder string) *Encoding {
43	e := new(Encoding)
44	e.padChar = StdPadding
45	e.encode = encoder
46	for i := 0; i < len(e.decodeMap); i++ {
47		e.decodeMap[i] = 0xFF
48	}
49	for i := 0; i < len(encoder); i++ {
50		e.decodeMap[encoder[i]] = byte(i)
51	}
52	return e
53}
54
55// NewEncoding returns a new case insensitive Encoding defined by the
56// given alphabet, which must be a 32-byte string.
57func NewEncodingCI(encoder string) *Encoding {
58	e := new(Encoding)
59	e.padChar = StdPadding
60	e.encode = encoder
61	for i := 0; i < len(e.decodeMap); i++ {
62		e.decodeMap[i] = 0xFF
63	}
64	for i := 0; i < len(encoder); i++ {
65		e.decodeMap[asciiToLower(encoder[i])] = byte(i)
66		e.decodeMap[asciiToUpper(encoder[i])] = byte(i)
67	}
68	return e
69}
70
71func asciiToLower(c byte) byte {
72	if c >= 'A' && c <= 'Z' {
73		return c + 32
74	}
75	return c
76}
77
78func asciiToUpper(c byte) byte {
79	if c >= 'a' && c <= 'z' {
80		return c - 32
81	}
82	return c
83}
84
85// WithPadding creates a new encoding identical to enc except
86// with a specified padding character, or NoPadding to disable padding.
87func (enc Encoding) WithPadding(padding rune) *Encoding {
88	enc.padChar = padding
89	return &enc
90}
91
92// StdEncoding is the standard base32 encoding, as defined in
93// RFC 4648.
94var StdEncoding = NewEncodingCI(encodeStd)
95
96// HexEncoding is the ``Extended Hex Alphabet'' defined in RFC 4648.
97// It is typically used in DNS.
98var HexEncoding = NewEncodingCI(encodeHex)
99
100var RawStdEncoding = NewEncodingCI(encodeStd).WithPadding(NoPadding)
101var RawHexEncoding = NewEncodingCI(encodeHex).WithPadding(NoPadding)
102
103/*
104 * Encoder
105 */
106
107// Encode encodes src using the encoding enc, writing
108// EncodedLen(len(src)) bytes to dst.
109//
110// The encoding pads the output to a multiple of 8 bytes,
111// so Encode is not appropriate for use on individual blocks
112// of a large data stream. Use NewEncoder() instead.
113func (enc *Encoding) Encode(dst, src []byte) {
114	if len(src) == 0 {
115		return
116	}
117
118	for len(src) > 0 {
119		var carry byte
120
121		// Unpack 8x 5-bit source blocks into a 5 byte
122		// destination quantum
123		switch len(src) {
124		default:
125			dst[7] = enc.encode[src[4]&0x1F]
126			carry = src[4] >> 5
127			fallthrough
128		case 4:
129			dst[6] = enc.encode[carry|(src[3]<<3)&0x1F]
130			dst[5] = enc.encode[(src[3]>>2)&0x1F]
131			carry = src[3] >> 7
132			fallthrough
133		case 3:
134			dst[4] = enc.encode[carry|(src[2]<<1)&0x1F]
135			carry = (src[2] >> 4) & 0x1F
136			fallthrough
137		case 2:
138			dst[3] = enc.encode[carry|(src[1]<<4)&0x1F]
139			dst[2] = enc.encode[(src[1]>>1)&0x1F]
140			carry = (src[1] >> 6) & 0x1F
141			fallthrough
142		case 1:
143			dst[1] = enc.encode[carry|(src[0]<<2)&0x1F]
144			dst[0] = enc.encode[src[0]>>3]
145		}
146
147		// Pad the final quantum
148		if len(src) < 5 {
149			if enc.padChar != NoPadding {
150				dst[7] = byte(enc.padChar)
151				if len(src) < 4 {
152					dst[6] = byte(enc.padChar)
153					dst[5] = byte(enc.padChar)
154					if len(src) < 3 {
155						dst[4] = byte(enc.padChar)
156						if len(src) < 2 {
157							dst[3] = byte(enc.padChar)
158							dst[2] = byte(enc.padChar)
159						}
160					}
161				}
162			}
163			break
164		}
165		src = src[5:]
166		dst = dst[8:]
167	}
168}
169
170// EncodeToString returns the base32 encoding of src.
171func (enc *Encoding) EncodeToString(src []byte) string {
172	buf := make([]byte, enc.EncodedLen(len(src)))
173	enc.Encode(buf, src)
174	return string(buf)
175}
176
177type encoder struct {
178	err  error
179	enc  *Encoding
180	w    io.Writer
181	buf  [5]byte    // buffered data waiting to be encoded
182	nbuf int        // number of bytes in buf
183	out  [1024]byte // output buffer
184}
185
186func (e *encoder) Write(p []byte) (n int, err error) {
187	if e.err != nil {
188		return 0, e.err
189	}
190
191	// Leading fringe.
192	if e.nbuf > 0 {
193		var i int
194		for i = 0; i < len(p) && e.nbuf < 5; i++ {
195			e.buf[e.nbuf] = p[i]
196			e.nbuf++
197		}
198		n += i
199		p = p[i:]
200		if e.nbuf < 5 {
201			return
202		}
203		e.enc.Encode(e.out[0:], e.buf[0:])
204		if _, e.err = e.w.Write(e.out[0:8]); e.err != nil {
205			return n, e.err
206		}
207		e.nbuf = 0
208	}
209
210	// Large interior chunks.
211	for len(p) >= 5 {
212		nn := len(e.out) / 8 * 5
213		if nn > len(p) {
214			nn = len(p)
215			nn -= nn % 5
216		}
217		e.enc.Encode(e.out[0:], p[0:nn])
218		if _, e.err = e.w.Write(e.out[0 : nn/5*8]); e.err != nil {
219			return n, e.err
220		}
221		n += nn
222		p = p[nn:]
223	}
224
225	// Trailing fringe.
226	for i := 0; i < len(p); i++ {
227		e.buf[i] = p[i]
228	}
229	e.nbuf = len(p)
230	n += len(p)
231	return
232}
233
234// Close flushes any pending output from the encoder.
235// It is an error to call Write after calling Close.
236func (e *encoder) Close() error {
237	// If there's anything left in the buffer, flush it out
238	if e.err == nil && e.nbuf > 0 {
239		e.enc.Encode(e.out[0:], e.buf[0:e.nbuf])
240		e.nbuf = 0
241		_, e.err = e.w.Write(e.out[0:8])
242	}
243	return e.err
244}
245
246// NewEncoder returns a new base32 stream encoder. Data written to
247// the returned writer will be encoded using enc and then written to w.
248// Base32 encodings operate in 5-byte blocks; when finished
249// writing, the caller must Close the returned encoder to flush any
250// partially written blocks.
251func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser {
252	return &encoder{enc: enc, w: w}
253}
254
255// EncodedLen returns the length in bytes of the base32 encoding
256// of an input buffer of length n.
257func (enc *Encoding) EncodedLen(n int) int {
258	if enc.padChar == NoPadding {
259		return (n*8 + 4) / 5 // minimum # chars at 5 bits per char
260	}
261	return (n + 4) / 5 * 8
262}
263
264/*
265 * Decoder
266 */
267
268type CorruptInputError int64
269
270func (e CorruptInputError) Error() string {
271	return "illegal base32 data at input byte " + strconv.FormatInt(int64(e), 10)
272}
273
274// decode is like Decode but returns an additional 'end' value, which
275// indicates if end-of-message padding was encountered and thus any
276// additional data is an error. This method assumes that src has been
277// stripped of all supported whitespace ('\r' and '\n').
278func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) {
279	olen := len(src)
280	for len(src) > 0 && !end {
281		// Decode quantum using the base32 alphabet
282		var dbuf [8]byte
283		dlen := 8
284
285		for j := 0; j < 8; {
286			if len(src) == 0 {
287				if enc.padChar != NoPadding {
288					return n, false, CorruptInputError(olen - len(src) - j)
289				}
290				dlen = j
291				break
292			}
293			in := src[0]
294			src = src[1:]
295			if in == byte(enc.padChar) && j >= 2 && len(src) < 8 {
296				if enc.padChar == NoPadding {
297					return n, false, CorruptInputError(olen)
298				}
299
300				// We've reached the end and there's padding
301				if len(src)+j < 8-1 {
302					// not enough padding
303					return n, false, CorruptInputError(olen)
304				}
305				for k := 0; k < 8-1-j; k++ {
306					if len(src) > k && src[k] != byte(enc.padChar) {
307						// incorrect padding
308						return n, false, CorruptInputError(olen - len(src) + k - 1)
309					}
310				}
311				dlen, end = j, true
312				// 7, 5 and 2 are not valid padding lengths, and so 1, 3 and 6 are not
313				// valid dlen values. See RFC 4648 Section 6 "Base 32 Encoding" listing
314				// the five valid padding lengths, and Section 9 "Illustrations and
315				// Examples" for an illustration for how the 1st, 3rd and 6th base32
316				// src bytes do not yield enough information to decode a dst byte.
317				if dlen == 1 || dlen == 3 || dlen == 6 {
318					return n, false, CorruptInputError(olen - len(src) - 1)
319				}
320				break
321			}
322			dbuf[j] = enc.decodeMap[in]
323			if dbuf[j] == 0xFF {
324				return n, false, CorruptInputError(olen - len(src) - 1)
325			}
326			j++
327		}
328
329		// Pack 8x 5-bit source blocks into 5 byte destination
330		// quantum
331		switch dlen {
332		case 8:
333			dst[4] = dbuf[6]<<5 | dbuf[7]
334			fallthrough
335		case 7:
336			dst[3] = dbuf[4]<<7 | dbuf[5]<<2 | dbuf[6]>>3
337			fallthrough
338		case 5:
339			dst[2] = dbuf[3]<<4 | dbuf[4]>>1
340			fallthrough
341		case 4:
342			dst[1] = dbuf[1]<<6 | dbuf[2]<<1 | dbuf[3]>>4
343			fallthrough
344		case 2:
345			dst[0] = dbuf[0]<<3 | dbuf[1]>>2
346		}
347
348		if len(dst) > 5 {
349			dst = dst[5:]
350		}
351
352		switch dlen {
353		case 2:
354			n += 1
355		case 4:
356			n += 2
357		case 5:
358			n += 3
359		case 7:
360			n += 4
361		case 8:
362			n += 5
363		}
364	}
365	return n, end, nil
366}
367
368// Decode decodes src using the encoding enc. It writes at most
369// DecodedLen(len(src)) bytes to dst and returns the number of bytes
370// written. If src contains invalid base32 data, it will return the
371// number of bytes successfully written and CorruptInputError.
372// New line characters (\r and \n) are ignored.
373func (enc *Encoding) Decode(dst, s []byte) (n int, err error) {
374	// FIXME: if dst is the same as s use decodeInPlace
375	stripped := make([]byte, 0, len(s))
376	for _, c := range s {
377		if c != '\r' && c != '\n' {
378			stripped = append(stripped, c)
379		}
380	}
381	n, _, err = enc.decode(dst, stripped)
382	return
383}
384
385func (enc *Encoding) decodeInPlace(strb []byte) (n int, err error) {
386	off := 0
387	for _, b := range strb {
388		if b == '\n' || b == '\r' {
389			continue
390		}
391		strb[off] = b
392		off++
393	}
394	n, _, err = enc.decode(strb, strb[:off])
395	return
396}
397
398// DecodeString returns the bytes represented by the base32 string s.
399func (enc *Encoding) DecodeString(s string) ([]byte, error) {
400	strb := []byte(s)
401	n, err := enc.decodeInPlace(strb)
402	if err != nil {
403		return nil, err
404	}
405	return strb[:n], nil
406}
407
408type decoder struct {
409	err    error
410	enc    *Encoding
411	r      io.Reader
412	end    bool       // saw end of message
413	buf    [1024]byte // leftover input
414	nbuf   int
415	out    []byte // leftover decoded output
416	outbuf [1024 / 8 * 5]byte
417}
418
419func (d *decoder) Read(p []byte) (n int, err error) {
420	if d.err != nil {
421		return 0, d.err
422	}
423
424	// Use leftover decoded output from last read.
425	if len(d.out) > 0 {
426		n = copy(p, d.out)
427		d.out = d.out[n:]
428		return n, nil
429	}
430
431	// Read a chunk.
432	nn := len(p) / 5 * 8
433	if nn < 8 {
434		nn = 8
435	}
436	if nn > len(d.buf) {
437		nn = len(d.buf)
438	}
439	nn, d.err = io.ReadAtLeast(d.r, d.buf[d.nbuf:nn], 8-d.nbuf)
440	d.nbuf += nn
441	if d.nbuf < 8 {
442		return 0, d.err
443	}
444
445	// Decode chunk into p, or d.out and then p if p is too small.
446	nr := d.nbuf / 8 * 8
447	nw := d.nbuf / 8 * 5
448	if nw > len(p) {
449		nw, d.end, d.err = d.enc.decode(d.outbuf[0:], d.buf[0:nr])
450		d.out = d.outbuf[0:nw]
451		n = copy(p, d.out)
452		d.out = d.out[n:]
453	} else {
454		n, d.end, d.err = d.enc.decode(p, d.buf[0:nr])
455	}
456	d.nbuf -= nr
457	for i := 0; i < d.nbuf; i++ {
458		d.buf[i] = d.buf[i+nr]
459	}
460
461	if d.err == nil {
462		d.err = err
463	}
464	return n, d.err
465}
466
467type newlineFilteringReader struct {
468	wrapped io.Reader
469}
470
471func (r *newlineFilteringReader) Read(p []byte) (int, error) {
472	n, err := r.wrapped.Read(p)
473	for n > 0 {
474		offset := 0
475		for i, b := range p[0:n] {
476			if b != '\r' && b != '\n' {
477				if i != offset {
478					p[offset] = b
479				}
480				offset++
481			}
482		}
483		if offset > 0 {
484			return offset, err
485		}
486		// Previous buffer entirely whitespace, read again
487		n, err = r.wrapped.Read(p)
488	}
489	return n, err
490}
491
492// NewDecoder constructs a new base32 stream decoder.
493func NewDecoder(enc *Encoding, r io.Reader) io.Reader {
494	return &decoder{enc: enc, r: &newlineFilteringReader{r}}
495}
496
497// DecodedLen returns the maximum length in bytes of the decoded data
498// corresponding to n bytes of base32-encoded data.
499func (enc *Encoding) DecodedLen(n int) int {
500	if enc.padChar == NoPadding {
501		return (n*5 + 7) / 8
502	}
503
504	return n / 8 * 5
505}
506