bsp; //shift the 6 bit bytes into a single 4 octet word
int res=(unenc[0]<<18)+(unenc[1]<<12)+(unenc[2]<<6)+unenc[3];
byte c;
int k=16;
//shift each octet down to read it as char and add to StringBuffer
while(k>=0)
{
c=(byte)(res>>k);
if ( c>0 )
sb.append((char)c);
k-=8;
}
//reset j and the unencode buffer
j=0;
unenc[0]=0;unenc[1]=0;unenc[2]=0;unenc[3]=0;
}
}
return sb.toString();
}
/** encode plaintext data to a base 64 string
* @param plain the text to convert. If plain is longer than 76 characters this method
* returns null (see RFC2045).
* @return the encoded text (or null if string was longer than 76 chars).
*/
public static String encode(String plain)
{
if(plain.length()>76)
return null;
int maxturns;
StringBuffer sb=new StringBuffer();
//the encode buffer
byte[] enc=new byte[3];
boolean end=false;
for(int i=0,j=0;!end;i++)
{
char _ch=plain.charAt(i);
if(i==plain.length()-1)
end=true;
enc[j++]=(byte)plain.charAt(i);
if(j==3 || end)
{
int res;
//this is a bit inefficient at the end point
//worth it for the small decrease in code size?
res=(enc[0]<<16)+(enc[1]<<8)+enc[2];
int b;
int lowestbit=18-(j*6);
for(int toshift=18;toshift>=lowestbit;toshift-=6)
{
b=res>>>toshift;
b&=63;
if(b>=0&&b<26)
sb.append((char)(b+65));
if(b>=26&&b<52)
sb.append((char)(b+71));
 
int res=(unenc[0]<<18)+(unenc[1]<<12)+(unenc[2]<<6)+unenc[3];
byte c;
int k=16;
//shift each octet down to read it as char and add to StringBuffer
while(k>=0)
{
c=(byte)(res>>k);
if ( c>0 )
sb.append((char)c);
k-=8;
}
//reset j and the unencode buffer
j=0;
unenc[0]=0;unenc[1]=0;unenc[2]=0;unenc[3]=0;
}
}
return sb.toString();
}
/** encode plaintext data to a base 64 string
* @param plain the text to convert. If plain is longer than 76 characters this method
* returns null (see RFC2045).
* @return the encoded text (or null if string was longer than 76 chars).
*/
public static String encode(String plain)
{
if(plain.length()>76)
return null;
int maxturns;
StringBuffer sb=new StringBuffer();
//the encode buffer
byte[] enc=new byte[3];
boolean end=false;
for(int i=0,j=0;!end;i++)
{
char _ch=plain.charAt(i);
if(i==plain.length()-1)
end=true;
enc[j++]=(byte)plain.charAt(i);
if(j==3 || end)
{
int res;
//this is a bit inefficient at the end point
//worth it for the small decrease in code size?
res=(enc[0]<<16)+(enc[1]<<8)+enc[2];
int b;
int lowestbit=18-(j*6);
for(int toshift=18;toshift>=lowestbit;toshift-=6)
{
b=res>>>toshift;
b&=63;
if(b>=0&&b<26)
sb.append((char)(b+65));
if(b>=26&&b<52)
sb.append((char)(b+71));