base64.c

Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2009 Michael Brown <mbrown@fensystems.co.uk>.
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License as
00006  * published by the Free Software Foundation; either version 2 of the
00007  * License, or any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful, but
00010  * WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  * General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
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 /** @file
00027  *
00028  * Base64 encoding
00029  *
00030  */
00031 
00032 static const char base64[64] =
00033         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
00034 
00035 /**
00036  * Base64-encode a string
00037  *
00038  * @v raw               Raw string
00039  * @v encoded           Buffer for encoded string
00040  *
00041  * The buffer must be the correct length for the encoded string.  Use
00042  * something like
00043  *
00044  *     char buf[ base64_encoded_len ( strlen ( raw ) ) + 1 ];
00045  *
00046  * (the +1 is for the terminating NUL) to provide a buffer of the
00047  * correct size.
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 }

Generated on Tue Apr 6 20:00:51 2010 for gPXE by  doxygen 1.5.7.1