Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdint.h>
- /* base64 charset for fast encoding */
- static const uint8_t enc_ch[] =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
- /* decode charset */
- static const uint8_t dec_ch[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63,
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 0, 0, 0,
- 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0,
- 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
- 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
- };
- static void b64enc_block(uint8_t *in, uint8_t *out, size_t len)
- {
- out[0] = enc_ch[in[0] >> 2];
- out[1] = enc_ch[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
- out[2] = len > 1 ? enc_ch[((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6)] : '=';
- out[3] = len > 2 ? enc_ch[in[2] & 0x3f] : '=';
- }
- static void b64dec_block(uint8_t *in, uint8_t *out)
- {
- out[0] = dec_ch[in[0]] << 2 | dec_ch[in[1]] >> 4;
- out[1] = dec_ch[in[1]] << 4 | dec_ch[in[2]] >> 2;
- out[2] = ((dec_ch[in[2]] << 6) & 0xc0) | dec_ch[in[3]];
- }
- int b64enc(uint8_t *in, uint8_t *out, size_t len)
- {
- int i, o;
- for(i = 0, o = 0; i < len; i += 3, o += 4)
- b64enc_block(in + i, out + o, len - i);
- return o;
- }
- int b64dec(uint8_t *in, uint8_t *out, size_t len)
- {
- int i, o;
- for(i = 0, o = 0; i < len; i += 4, o += 3)
- b64dec_block(in + i, out + o);
- return o;
- }
- #ifdef STANDALONE
- /* simple main to test the functions */
- int main(int argc, char *argv[])
- {
- /* usually base64 text is formatted in 76 characters line so
- * every 57 input bytes we get 76 characters (57 / 3 * 4 = 76)
- */
- uint8_t dec[58];
- uint8_t enc[77];
- size_t len;
- if(argc != 2 || argv[1][0] != '-' || (argv[1][1] != 'd' && argv[1][1] != 'e')) {
- fprintf(stderr, "usage: %s [-e|-d]\n", *argv);
- return 1;
- }
- if(argv[1][1] == 'e')
- while((len = fread(dec, 1, 57, stdin))) {
- len = b64enc(dec, enc, len);
- enc[len] = 0;
- puts((char *)enc);
- }
- else
- while((len = fread(enc, 1, 76, stdin))) {
- len = b64dec(enc, dec, len);
- dec[len] = 0;
- fputs((char *)dec, stdout);
- /* skip the \n */
- if(!fread(enc, 1, 1, stdin))
- return 0;
- }
- fclose(stdin);
- fclose(stdout);
- return 0;
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement