base32.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 <string.h>
  18. #include "base32.h"
  19. int base32_decode(const uint8_t* encoded, uint8_t* result, int bufSize) {
  20. int buffer = 0;
  21. int bitsLeft = 0;
  22. int count = 0;
  23. for(const uint8_t* ptr = encoded; count < bufSize && *ptr; ++ptr) {
  24. uint8_t ch = *ptr;
  25. if(ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' || ch == '-') {
  26. continue;
  27. }
  28. buffer <<= 5;
  29. // Deal with commonly mistyped characters
  30. if(ch == '0') {
  31. ch = 'O';
  32. } else if(ch == '1') {
  33. ch = 'L';
  34. } else if(ch == '8') {
  35. ch = 'B';
  36. }
  37. // Look up one base32 digit
  38. if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
  39. ch = (ch & 0x1F) - 1;
  40. } else if(ch >= '2' && ch <= '7') {
  41. ch -= '2' - 26;
  42. } else {
  43. return -1;
  44. }
  45. buffer |= ch;
  46. bitsLeft += 5;
  47. if(bitsLeft >= 8) {
  48. result[count++] = buffer >> (bitsLeft - 8);
  49. bitsLeft -= 8;
  50. }
  51. }
  52. if(count < bufSize) {
  53. result[count] = '\000';
  54. }
  55. return count;
  56. }