xosseh

base64.c

Dec 14th, 2023
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #include "base64.h"
  6.  
  7. size_t b64_encoded_size(size_t inlen)
  8. {
  9.     size_t ret;
  10.  
  11.     ret = inlen;
  12.     if (inlen % 3 != 0)
  13.         ret += 3 - (inlen % 3);
  14.     ret /= 3;
  15.     ret *= 4;
  16.  
  17.     return ret;
  18. }
  19.  
  20. char *b64_encode(char *in)
  21. {
  22.     const char b64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  23.     size_t len = strlen(in);
  24.     char   *out;
  25.     size_t  elen;
  26.     size_t  i;
  27.     size_t  j;
  28.     size_t  v;
  29.  
  30.     if (in == NULL || len == 0)
  31.         return NULL;
  32.  
  33.     elen = b64_encoded_size(len);
  34.     out  = malloc(elen+1);
  35.     out[elen] = '\0';
  36.  
  37.     for (i=0, j=0; i<len; i+=3, j+=4) {
  38.         v = in[i];
  39.         v = i+1 < len ? v << 8 | in[i+1] : v << 8;
  40.         v = i+2 < len ? v << 8 | in[i+2] : v << 8;
  41.  
  42.         out[j]   = b64chars[(v >> 18) & 0x3F];
  43.         out[j+1] = b64chars[(v >> 12) & 0x3F];
  44.         if (i+1 < len) {
  45.             out[j+2] = b64chars[(v >> 6) & 0x3F];
  46.         } else {
  47.             out[j+2] = '=';
  48.         }
  49.         if (i+2 < len) {
  50.             out[j+3] = b64chars[v & 0x3F];
  51.         } else {
  52.             out[j+3] = '=';
  53.         }
  54.     }
  55.  
  56.     return out;
  57. }
  58.  
  59. int main(int argc, char **argv)
  60. {
  61.     (void)argc;
  62.     (void)argv;
  63.     char *data = "123456SO+PA=SOPA!";
  64.     char       *enc;
  65.  
  66.     printf("data:    '%s'\n", data);
  67.  
  68.     enc = b64_encode(data);
  69.     printf("encoded: '%s'\n", enc);
  70.  
  71.     free(enc);
  72.  
  73.     return 0;
  74. }
  75.  
Add Comment
Please, Sign In to add comment