You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

base64.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // (C) Copyright 2012, Jeramey Crawford <jeramey@antihe.ro>. All
  2. // rights reserved. Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package common
  5. const (
  6. alphabet = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  7. )
  8. // Base64_24Bit is a variant of Base64 encoding, commonly used with password
  9. // hashing algorithms to encode the result of their checksum output.
  10. //
  11. // The algorithm operates on up to 3 bytes at a time, encoding the following
  12. // 6-bit sequences into up to 4 hash64 ASCII bytes.
  13. //
  14. // 1. Bottom 6 bits of the first byte
  15. // 2. Top 2 bits of the first byte, and bottom 4 bits of the second byte.
  16. // 3. Top 4 bits of the second byte, and bottom 2 bits of the third byte.
  17. // 4. Top 6 bits of the third byte.
  18. //
  19. // This encoding method does not emit padding bytes as Base64 does.
  20. func Base64_24Bit(src []byte) []byte {
  21. if len(src) == 0 {
  22. return []byte{} // TODO: return nil
  23. }
  24. dstlen := (len(src)*8 + 5) / 6
  25. dst := make([]byte, dstlen)
  26. di, si := 0, 0
  27. n := len(src) / 3 * 3
  28. for si < n {
  29. val := uint(src[si+2])<<16 | uint(src[si+1])<<8 | uint(src[si])
  30. dst[di+0] = alphabet[val&0x3f]
  31. dst[di+1] = alphabet[val>>6&0x3f]
  32. dst[di+2] = alphabet[val>>12&0x3f]
  33. dst[di+3] = alphabet[val>>18]
  34. di += 4
  35. si += 3
  36. }
  37. rem := len(src) - si
  38. if rem == 0 {
  39. return dst
  40. }
  41. val := uint(src[si+0])
  42. if rem == 2 {
  43. val |= uint(src[si+1]) << 8
  44. }
  45. dst[di+0] = alphabet[val&0x3f]
  46. dst[di+1] = alphabet[val>>6&0x3f]
  47. if rem == 2 {
  48. dst[di+2] = alphabet[val>>12]
  49. }
  50. return dst
  51. }