github.com/flyinox/gosm@v0.0.0-20171117061539-16768cb62077/src/encoding/base32/base32.go (about)

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