base32.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Base32 implementation
  2. //
  3. // Copyright 2010 Google Inc.
  4. // Author: Markus Gutschke
  5. //
  6. // Licensed under the Apache License, Version 2.0 (the "License");
  7. // you may not use this file except in compliance with the License.
  8. // You may obtain a copy of the License at
  9. //
  10. // http://www.apache.org/licenses/LICENSE-2.0
  11. //
  12. // Unless required by applicable law or agreed to in writing, software
  13. // distributed under the License is distributed on an "AS IS" BASIS,
  14. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. // See the License for the specific language governing permissions and
  16. // limitations under the License.
  17. #include "base32.h"
  18. int base32_decode(const uint8_t* encoded, uint8_t* result, int bufSize) {
  19. int buffer = 0;
  20. int bitsLeft = 0;
  21. int count = 0;
  22. for(const uint8_t* ptr = encoded; count < bufSize && *ptr; ++ptr) {
  23. uint8_t ch = *ptr;
  24. if(ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-') {
  25. continue;
  26. }
  27. buffer <<= 5;
  28. // Deal with commonly mistyped characters
  29. if(ch == '0') {
  30. ch = 'O';
  31. } else if(ch == '1') {
  32. ch = 'L';
  33. } else if(ch == '8') {
  34. ch = 'B';
  35. }
  36. // Look up one base32 digit
  37. if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  38. ch = (ch & 0x1F) - 1;
  39. } else if(ch >= '2' && ch <= '7') {
  40. ch -= '2' - 26;
  41. } else {
  42. return -1;
  43. }
  44. buffer |= ch;
  45. bitsLeft += 5;
  46. if(bitsLeft >= 8) {
  47. result[count++] = buffer >> (bitsLeft - 8);
  48. bitsLeft -= 8;
  49. }
  50. }
  51. if(count < bufSize) {
  52. result[count] = '\000';
  53. }
  54. return count;
  55. }