www.pudn.com > MailSoftware.rar > base64str.cpp


// base64str.cpp - written and placed in the public domain by Wei Dai 
// rewritten to single decoding of strings by Thomas Kuiper 
#include "stdafx.h" 
#include  
 
#include "base64str.h" 
 
static const int MAX_LINE_LENGTH = 72; 
 
static const unsigned char vec[] = 
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; 
 
static const unsigned char padding = '='; 
 
 
Base64StrDecoder::Base64StrDecoder(char *string) 
{ 
	inBufSize=0; 
	bufpos = 0; 
	Put((unsigned char*)(string),strlen(string)); 
	InputFinished(); 
 
} 
 
void Base64StrDecoder::DecodeQuantum() 
{ 
 
	 
	if (bufpos == 250) {inBufSize=0;return;} 
 
	unsigned char out; 
 
	out = (unsigned char)((inBuf[0] << 2) | (inBuf[1] >> 4)); 
 
	buffer[bufpos] = out; 
	bufpos++; 
 
	 
	out = (unsigned char)((inBuf[1] << 4) | (inBuf[2] >> 2)); 
	if (inBufSize > 2) {buffer[bufpos] = out; bufpos++;} 
 
	out = (unsigned char)((inBuf[2] << 6) | inBuf[3]); 
	if (inBufSize > 3) {buffer[bufpos] = out; bufpos++;} 
 
	 
	inBufSize=0; 
} 
 
int Base64StrDecoder::ConvToNumber(unsigned char inByte) 
{ 
	if (inByte >= 'A' && inByte <= 'Z') 
		return (inByte - 'A'); 
 
	if (inByte >= 'a' && inByte <= 'z') 
		return (inByte - 'a' + 26); 
 
	if (inByte >= '0' && inByte <= '9') 
		return (inByte - '0' + 52); 
 
	if (inByte == '+') 
		return (62); 
 
	if (inByte == '/') 
		return (63); 
 
	return (-1); 
} 
 
void Base64StrDecoder::Put(unsigned char inByte) 
{ 
	int i=ConvToNumber(inByte); 
	if (i >= 0) 
		inBuf[inBufSize++]=(unsigned char) i; 
	if (inBufSize==4) 
		DecodeQuantum(); 
} 
 
void Base64StrDecoder::Put(const unsigned char* inString, unsigned int len) 
{ 
 
	while (len--) 
		Base64StrDecoder::Put(*inString++); 
} 
 
void Base64StrDecoder::InputFinished() 
{ 
	if (inBufSize) 
	{ 
		for (int i=inBufSize;i<4;i++) 
			inBuf[i]=0; 
 
		DecodeQuantum(); 
	} 
buffer[bufpos] = '\0';	 
}