base64.c
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 FILE_LICENCE ( GPL2_OR_LATER );
00020
00021 #include <stdint.h>
00022 #include <string.h>
00023 #include <assert.h>
00024 #include <gpxe/base64.h>
00025
00026
00027
00028
00029
00030
00031
00032 static const char base64[64] =
00033 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049 void base64_encode ( const char *raw, char *encoded ) {
00050 const uint8_t *raw_bytes = ( ( const uint8_t * ) raw );
00051 uint8_t *encoded_bytes = ( ( uint8_t * ) encoded );
00052 size_t raw_bit_len = ( 8 * strlen ( raw ) );
00053 unsigned int bit;
00054 unsigned int tmp;
00055
00056 for ( bit = 0 ; bit < raw_bit_len ; bit += 6 ) {
00057 tmp = ( ( raw_bytes[ bit / 8 ] << ( bit % 8 ) ) |
00058 ( raw_bytes[ bit / 8 + 1 ] >> ( 8 - ( bit % 8 ) ) ) );
00059 tmp = ( ( tmp >> 2 ) & 0x3f );
00060 *(encoded_bytes++) = base64[tmp];
00061 }
00062 for ( ; ( bit % 8 ) != 0 ; bit += 6 )
00063 *(encoded_bytes++) = '=';
00064 *(encoded_bytes++) = '\0';
00065
00066 DBG ( "Base64-encoded \"%s\" as \"%s\"\n", raw, encoded );
00067 assert ( strlen ( encoded ) == base64_encoded_len ( strlen ( raw ) ) );
00068 }