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