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