github.com/ader1990/go@v0.0.0-20140630135419-8c24447fa791/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 nn -= nn % 5 183 } 184 e.enc.Encode(e.out[0:], p[0:nn]) 185 if _, e.err = e.w.Write(e.out[0 : nn/5*8]); e.err != nil { 186 return n, e.err 187 } 188 n += nn 189 p = p[nn:] 190 } 191 192 // Trailing fringe. 193 for i := 0; i < len(p); i++ { 194 e.buf[i] = p[i] 195 } 196 e.nbuf = len(p) 197 n += len(p) 198 return 199 } 200 201 // Close flushes any pending output from the encoder. 202 // It is an error to call Write after calling Close. 203 func (e *encoder) Close() error { 204 // If there's anything left in the buffer, flush it out 205 if e.err == nil && e.nbuf > 0 { 206 e.enc.Encode(e.out[0:], e.buf[0:e.nbuf]) 207 e.nbuf = 0 208 _, e.err = e.w.Write(e.out[0:8]) 209 } 210 return e.err 211 } 212 213 // NewEncoder returns a new base32 stream encoder. Data written to 214 // the returned writer will be encoded using enc and then written to w. 215 // Base32 encodings operate in 5-byte blocks; when finished 216 // writing, the caller must Close the returned encoder to flush any 217 // partially written blocks. 218 func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser { 219 return &encoder{enc: enc, w: w} 220 } 221 222 // EncodedLen returns the length in bytes of the base32 encoding 223 // of an input buffer of length n. 224 func (enc *Encoding) EncodedLen(n int) int { return (n + 4) / 5 * 8 } 225 226 /* 227 * Decoder 228 */ 229 230 type CorruptInputError int64 231 232 func (e CorruptInputError) Error() string { 233 return "illegal base32 data at input byte " + strconv.FormatInt(int64(e), 10) 234 } 235 236 // decode is like Decode but returns an additional 'end' value, which 237 // indicates if end-of-message padding was encountered and thus any 238 // additional data is an error. This method assumes that src has been 239 // stripped of all supported whitespace ('\r' and '\n'). 240 func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) { 241 olen := len(src) 242 for len(src) > 0 && !end { 243 // Decode quantum using the base32 alphabet 244 var dbuf [8]byte 245 dlen := 8 246 247 for j := 0; j < 8; { 248 if len(src) == 0 { 249 return n, false, CorruptInputError(olen - len(src) - j) 250 } 251 in := src[0] 252 src = src[1:] 253 if in == '=' && j >= 2 && len(src) < 8 { 254 // We've reached the end and there's padding 255 if len(src)+j < 8-1 { 256 // not enough padding 257 return n, false, CorruptInputError(olen) 258 } 259 for k := 0; k < 8-1-j; k++ { 260 if len(src) > k && src[k] != '=' { 261 // incorrect padding 262 return n, false, CorruptInputError(olen - len(src) + k - 1) 263 } 264 } 265 dlen, end = j, true 266 // 7, 5 and 2 are not valid padding lengths, and so 1, 3 and 6 are not 267 // valid dlen values. See RFC 4648 Section 6 "Base 32 Encoding" listing 268 // the five valid padding lengths, and Section 9 "Illustrations and 269 // Examples" for an illustration for how the 1st, 3rd and 6th base32 270 // src bytes do not yield enough information to decode a dst byte. 271 if dlen == 1 || dlen == 3 || dlen == 6 { 272 return n, false, CorruptInputError(olen - len(src) - 1) 273 } 274 break 275 } 276 dbuf[j] = enc.decodeMap[in] 277 if dbuf[j] == 0xFF { 278 return n, false, CorruptInputError(olen - len(src) - 1) 279 } 280 j++ 281 } 282 283 // Pack 8x 5-bit source blocks into 5 byte destination 284 // quantum 285 switch dlen { 286 case 8: 287 dst[4] = dbuf[6]<<5 | dbuf[7] 288 fallthrough 289 case 7: 290 dst[3] = dbuf[4]<<7 | dbuf[5]<<2 | dbuf[6]>>3 291 fallthrough 292 case 5: 293 dst[2] = dbuf[3]<<4 | dbuf[4]>>1 294 fallthrough 295 case 4: 296 dst[1] = dbuf[1]<<6 | dbuf[2]<<1 | dbuf[3]>>4 297 fallthrough 298 case 2: 299 dst[0] = dbuf[0]<<3 | dbuf[1]>>2 300 } 301 dst = dst[5:] 302 switch dlen { 303 case 2: 304 n += 1 305 case 4: 306 n += 2 307 case 5: 308 n += 3 309 case 7: 310 n += 4 311 case 8: 312 n += 5 313 } 314 } 315 return n, end, nil 316 } 317 318 // Decode decodes src using the encoding enc. It writes at most 319 // DecodedLen(len(src)) bytes to dst and returns the number of bytes 320 // written. If src contains invalid base32 data, it will return the 321 // number of bytes successfully written and CorruptInputError. 322 // New line characters (\r and \n) are ignored. 323 func (enc *Encoding) Decode(dst, src []byte) (n int, err error) { 324 src = bytes.Map(removeNewlinesMapper, src) 325 n, _, err = enc.decode(dst, src) 326 return 327 } 328 329 // DecodeString returns the bytes represented by the base32 string s. 330 func (enc *Encoding) DecodeString(s string) ([]byte, error) { 331 s = strings.Map(removeNewlinesMapper, s) 332 dbuf := make([]byte, enc.DecodedLen(len(s))) 333 n, err := enc.Decode(dbuf, []byte(s)) 334 return dbuf[:n], err 335 } 336 337 type decoder struct { 338 err error 339 enc *Encoding 340 r io.Reader 341 end bool // saw end of message 342 buf [1024]byte // leftover input 343 nbuf int 344 out []byte // leftover decoded output 345 outbuf [1024 / 8 * 5]byte 346 } 347 348 func (d *decoder) Read(p []byte) (n int, err error) { 349 if d.err != nil { 350 return 0, d.err 351 } 352 353 // Use leftover decoded output from last read. 354 if len(d.out) > 0 { 355 n = copy(p, d.out) 356 d.out = d.out[n:] 357 return n, nil 358 } 359 360 // Read a chunk. 361 nn := len(p) / 5 * 8 362 if nn < 8 { 363 nn = 8 364 } 365 if nn > len(d.buf) { 366 nn = len(d.buf) 367 } 368 nn, d.err = io.ReadAtLeast(d.r, d.buf[d.nbuf:nn], 8-d.nbuf) 369 d.nbuf += nn 370 if d.nbuf < 8 { 371 return 0, d.err 372 } 373 374 // Decode chunk into p, or d.out and then p if p is too small. 375 nr := d.nbuf / 8 * 8 376 nw := d.nbuf / 8 * 5 377 if nw > len(p) { 378 nw, d.end, d.err = d.enc.decode(d.outbuf[0:], d.buf[0:nr]) 379 d.out = d.outbuf[0:nw] 380 n = copy(p, d.out) 381 d.out = d.out[n:] 382 } else { 383 n, d.end, d.err = d.enc.decode(p, d.buf[0:nr]) 384 } 385 d.nbuf -= nr 386 for i := 0; i < d.nbuf; i++ { 387 d.buf[i] = d.buf[i+nr] 388 } 389 390 if d.err == nil { 391 d.err = err 392 } 393 return n, d.err 394 } 395 396 type newlineFilteringReader struct { 397 wrapped io.Reader 398 } 399 400 func (r *newlineFilteringReader) Read(p []byte) (int, error) { 401 n, err := r.wrapped.Read(p) 402 for n > 0 { 403 offset := 0 404 for i, b := range p[0:n] { 405 if b != '\r' && b != '\n' { 406 if i != offset { 407 p[offset] = b 408 } 409 offset++ 410 } 411 } 412 if offset > 0 { 413 return offset, err 414 } 415 // Previous buffer entirely whitespace, read again 416 n, err = r.wrapped.Read(p) 417 } 418 return n, err 419 } 420 421 // NewDecoder constructs a new base32 stream decoder. 422 func NewDecoder(enc *Encoding, r io.Reader) io.Reader { 423 return &decoder{enc: enc, r: &newlineFilteringReader{r}} 424 } 425 426 // DecodedLen returns the maximum length in bytes of the decoded data 427 // corresponding to n bytes of base32-encoded data. 428 func (enc *Encoding) DecodedLen(n int) int { return n / 8 * 5 }