Source file src/encoding/base32/base32.go

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

View as plain text