Base64.cpp
Go to the documentation of this file.00001
00009 #include <string>
00010 #include <cstring>
00011 #include "Base64Buffer.h"
00012 #include "PKIFBase64.h"
00013 #include "PKIFException.h"
00014 #include "components.h"
00015 #include "PKIFCommonErrors.h"
00016
00017 #include "boost/numeric/conversion/cast.hpp"
00018
00019 using boost::numeric_cast;
00020 using boost::bad_numeric_cast;
00021
00022
00031 bool CAC_API B64Decode(const char * encoded, unsigned char ** decoded, unsigned long * decodedLen)
00032 {
00033 CBase64Buffer b64;
00034
00035
00036 unsigned long dlen = 0;
00037 try
00038 {
00039 dlen = numeric_cast<unsigned long>(strlen(encoded));
00040 }
00041 catch(bad_numeric_cast &)
00042 {
00043 throw CPKIFException(TOOLKIT_UTILS, COMMON_INVALID_INPUT, "string len is an impossibly long number.");
00044 }
00045 unsigned char * outbuf = new unsigned char[dlen];
00046 memset(outbuf,0x00,dlen);
00047 if(!b64.decode(encoded,dlen,outbuf,&dlen)) {
00048 delete[] outbuf;
00049 return false;
00050 }
00051 *decoded = outbuf;
00052 *decodedLen = dlen;
00053 return true;
00054 }
00055
00056
00065 bool CAC_API PEMDecode(const char * encoded, unsigned char ** decoded, unsigned long * decodedLen)
00066 {
00067 if(!encoded)
00068 return false;
00069 else
00070 {
00071 unsigned long encodedLen = numeric_cast<unsigned long>(strlen(encoded));
00072 return PEMDecode_l(encoded, encodedLen, decoded, decodedLen);
00073 }
00074 }
00075
00076 bool CAC_API PEMDecode_l(const char * encoded, unsigned long sourceLen, unsigned char ** decoded, unsigned long * decodedLen)
00077 {
00078 if(NULL == encoded || 0 >= sourceLen)
00079 return false;
00080
00081
00082
00083
00084
00085
00086
00087
00088
00089
00090
00091
00092
00093
00094
00095
00096
00097
00098
00099
00100
00101
00102
00103
00104 int start = 0;
00105
00106 if('-' == encoded[start]) {
00107 while('\n' != *(encoded + start)) {
00108 start++;
00109 }
00110 start++;
00111 }
00112
00113 std::string copy(encoded+start, sourceLen-start);
00114 std::string::iterator pos = copy.begin();
00115 std::string::iterator copyEnd = copy.end();
00116
00117
00118 if('-' == *pos)
00119 {
00120 while('\n' != *pos && copyEnd != pos)
00121 {
00122 ++pos;
00123 }
00124 ++pos;
00125 }
00126
00127 size_t index = copy.find("-", std::distance(copy.begin(), pos));
00128 if(index != std::string::npos)
00129 {
00130 copy[index] = 0x00;
00131 }
00132 bool rv = B64Decode(copy.c_str(),decoded,decodedLen);
00133 return rv;
00134 }
00143 bool CAC_API B64Encode(const unsigned char * plain, unsigned long plainLen, char ** encoded)
00144 {
00145 CBase64Buffer b64;
00146
00147 unsigned long encodedLen = plainLen * 2;
00148 char * outBuf = new char[encodedLen];
00149 if(!outBuf) return false;
00150
00151 memset(outBuf,0x00,encodedLen);
00152 if(!b64.encode(plain,plainLen,outBuf,&encodedLen)) {
00153 delete[] outBuf;
00154 return false;
00155 }
00156
00157 *encoded = outBuf;
00158 return true;
00159 }