base64.go 1.7 KB

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