Own fork of MbedSmartRest

Dependents:   MbedSmartRestMain MbedSmartRestMain

Fork of MbedSmartRest by Cumulocity Official

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers b64.cpp Source File

b64.cpp

00001 // Simple Base64 code
00002 // (c) Copyright 2010 MCQN Ltd.
00003 // Released under Apache License, version 2.0
00004 
00005 #include "b64.h"
00006 
00007 /* Simple test program
00008 #include <stdio.h>
00009 void main()
00010 {
00011     char* in = "amcewen";
00012     char out[22];
00013 
00014     b64_encode(in, 15, out, 22);
00015     out[21] = '\0';
00016 
00017     printf(out);
00018 }
00019 */
00020 
00021 const char* b64_dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
00022 
00023 void b64_encode(const unsigned char* aInput, int aInputLen, unsigned char* aOutput, int aOutputLen)
00024 {
00025     // Work out if we've got enough space to encode the input
00026     // Every 6 bits of input becomes a byte of output
00027     if (aOutputLen*6 < aInputLen*8) {
00028         // FIXME Should we return an error here, or just the length
00029         return ;
00030     }
00031 
00032     if (aInputLen == 3)
00033     {
00034         aOutput[0] = b64_dictionary[aInput[0] >> 2];
00035         aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)];
00036         aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2|(aInput[2]>>6)];
00037         aOutput[3] = b64_dictionary[aInput[2]&0x3F];
00038     } else if (aInputLen == 2) {
00039         aOutput[0] = b64_dictionary[aInput[0] >> 2];
00040         aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4|(aInput[1]>>4)];
00041         aOutput[2] = b64_dictionary[(aInput[1]&0x0F)<<2];
00042         aOutput[3] = '=';
00043     } else if (aInputLen == 1) {
00044         aOutput[0] = b64_dictionary[aInput[0] >> 2];
00045         aOutput[1] = b64_dictionary[(aInput[0] & 0x3)<<4];
00046         aOutput[2] = '=';
00047         aOutput[3] = '=';
00048     } else {
00049         // Break the input into 3-byte chunks and process each of them
00050         int i;
00051         for (i = 0; i < aInputLen/3; i++) {
00052             b64_encode(&aInput[i*3], 3, &aOutput[i*4], 4);
00053         }
00054         if (aInputLen % 3 > 0) {
00055             // It doesn't fit neatly into a 3-byte chunk, so process what's left
00056             b64_encode(&aInput[i*3], aInputLen % 3, &aOutput[i*4], aOutputLen - (i*4));
00057         }
00058     }
00059 }
00060