static
const byte gBase64Encode[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'+', '/'
};
/* porting assistance from yaSSL by Raphael HUCK */
int Base64_Encode(const byte* in, word32 inLen, byte* out, word32* outLen)
{
word32 i = 0;
word32 j = 0;
word32 outSz = (inLen + 3 - 1) / 3 * 4;
if (outSz > *outLen) return BAD_FUNC_ARG;
while (inLen > 2) {
byte b1 = in[j++];
byte b2 = in[j++];
byte b3 = in[j++];
/* encoded idx */
byte e1 = b1 >> 2;
byte e2 = ((b1 & 0x3) << 4) | (b2 >> 4);
byte e3 = ((b2 & 0xF) << 2) | (b3 >> 6);
byte e4 = b3 & 0x3F;
/* store */
out[i++] = gBase64Encode[e1];
out[i++] = gBase64Encode[e2];
out[i++] = gBase64Encode[e3];
out[i++] = gBase64Encode[e4];
inLen -= 3;
}
/* last integral */
if (inLen) {
int twoBytes = (inLen == 2);
byte b1 = in[j++];
byte b2 = (twoBytes) ? in[j++] : 0;
byte e1 = b1 >> 2;
byte e2 = ((b1 & 0x3) << 4) | (b2 >> 4);
byte e3 = (b2 & 0xF) << 2;
out[i++] = gBase64Encode[e1];
out[i++] = gBase64Encode[e2];
out[i++] = (twoBytes) ? gBase64Encode[e3] : PAD;
out[i++] = PAD;
}
if (i < *outLen)
{
out[i] = '\0';
}
if (i != outSz)
return ASN_INPUT_E;
*outLen = outSz;
return 0;
}