Base64

Standard

Descrizione

Esempio di conversione di una stringa in Base64.


Sorgente

#include <stdio.h>
#include <string.h>

char get_char (char);

int main (int argc, char *argv[])
{
 int len, t_len, i = 0;

 if ( argc < 2 ) {
      fprintf (stderr, "Uso: %s <stringa da cifrare in base64>\n", *argv);
      return 1;
 }

 t_len = strlen (argv[1]);
 for ( len = t_len - (t_len % 3); i < len; i += 3 ) {
       putchar (get_char (argv[1][i] >> 2));
       putchar (get_char (((argv[1][i] << 4) | (argv[1][i + 1] >> 4)) & 0x3F));
       putchar (get_char (((argv[1][i + 1] << 2) | (argv[1][i + 2] >> 6)) & 0x3F));
       putchar (get_char (argv[1][i + 2] & 0x3F));
 }

 switch (t_len % 3) {
   case 1: putchar (get_char (argv[1][i] >> 2));
           putchar (get_char (((argv[1][i] << 4) | 0x00) & 0x3F));
           printf ("==");
           break;
   case 2: putchar (get_char (argv[1][i] >> 2));
           putchar (get_char (((argv[1][i] << 4) | (argv[1][i + 1] >> 4)) & 0x3F));
           putchar (get_char (((argv[1][i + 1] << 2) | 0x00) & 0x3F));
           putchar ('=');
           break;
 }
 putchar ('\n');

 return 0;
}


char get_char (char c)
{
 if ( c >= 0 && c <= 25 )
      return c + 'A';

 if ( c > 25 && c <= 51 )
      return c + 'G';

 if ( c > 51 && c <= 61 )
      return c - 4;

 return (c == 62) ? '+' : '/';
}