test_base64.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <stddef.h>
  2. #include <stdint.h>
  3. #include "types.h"
  4. #include "base64.h"
  5. #include <string.h>
  6. #include <assert.h>
  7. #include <stdio.h>
  8. #include <sodium/randombytes.h>
  9. struct texttestcase {
  10. const char *in;
  11. const char *out;
  12. } tests0[] = {
  13. { "" ,"" },
  14. { "f" ,"Zg==" },
  15. { "fo" ,"Zm8=" },
  16. { "foo" ,"Zm9v" },
  17. { "foob" ,"Zm9vYg==" },
  18. { "fooba" ,"Zm9vYmE=" },
  19. { "foobar","Zm9vYmFy" },
  20. { "foobarf" ,"Zm9vYmFyZg==" },
  21. { "foobarfo" ,"Zm9vYmFyZm8=" },
  22. { "foobarfoo" ,"Zm9vYmFyZm9v" },
  23. { "foobarfoob" ,"Zm9vYmFyZm9vYg==" },
  24. { "foobarfooba" ,"Zm9vYmFyZm9vYmE=" },
  25. { "foobarfoobar","Zm9vYmFyZm9vYmFy" },
  26. };
  27. int main(void)
  28. {
  29. char buf[1024], buf2[1024];
  30. size_t r;
  31. for (size_t i = 0; i < sizeof(tests0)/sizeof(tests0[0]); ++i) {
  32. base64_to(buf, (const u8 *)tests0[i].in, strlen(tests0[i].in));
  33. if (strcmp(buf, tests0[i].out) != 0) {
  34. printf("invalid encoding result: \"%s\" -> encoded as \"%s\", but expected \"%s\".\n",
  35. tests0[i].in, buf, tests0[i].out);
  36. return 1;
  37. }
  38. if (strlen(buf) != BASE64_TO_LEN(strlen(tests0[i].in))) {
  39. printf("encoded length mismatch: got %d expected %d\n",
  40. (int) strlen(buf), (int) BASE64_TO_LEN(strlen(tests0[i].in)));
  41. return 1;
  42. }
  43. if (!base64_valid(buf,0)) {
  44. printf("encoded data is considered invalid\n");
  45. return 1;
  46. }
  47. r = base64_from((u8 *)buf2, buf, strlen(buf));
  48. buf2[r] = '\000';
  49. if (strcmp(buf2, tests0[i].in) != 0) {
  50. printf("invalid decoding result: encoded \"%s\", decoded as \"%s\", but expected \"%s\".\n",
  51. tests0[i].out, buf2, tests0[i].in);
  52. return 1;
  53. }
  54. }
  55. return 0;
  56. }