base64_valid.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Determine whether a string looks like valid base64-encoded data.
  3. */
  4. #include "misc.h"
  5. static inline bool valid_char_main(char c)
  6. {
  7. return ((c >= 'A' && c <= 'Z') ||
  8. (c >= 'a' && c <= 'z') ||
  9. (c >= '0' && c <= '9') ||
  10. c == '+' || c == '/');
  11. }
  12. bool base64_valid(ptrlen data)
  13. {
  14. size_t blocklen = 0, nequals = 0;
  15. for (size_t i = 0; i < data.len; i++) {
  16. char c = ((const char *)data.ptr)[i];
  17. if (c == '\n' || c == '\r')
  18. continue;
  19. if (valid_char_main(c)) {
  20. if (nequals) /* can't go back to data after = */
  21. return false;
  22. blocklen++;
  23. if (blocklen == 4)
  24. blocklen = 0;
  25. continue;
  26. }
  27. if (c == '=') {
  28. if (blocklen == 0 && nequals) /* started a fresh block */
  29. return false;
  30. nequals++;
  31. blocklen++;
  32. if (blocklen == 4) {
  33. if (nequals > 2)
  34. return false; /* nonsensical final block */
  35. blocklen = 0;
  36. }
  37. continue;
  38. }
  39. return false; /* bad character */
  40. }
  41. if (blocklen == 0 || blocklen == 2 || blocklen == 3)
  42. return true; /* permit eliding the trailing = */
  43. return false;
  44. }