欢迎光临
未来你我一起携手

Base64非默认编码表加密测试 C++下Base64编码与解码

Base64加密下会有一张编码表。但如果这张编码表顺序被打乱了呢?

思路来源于FreeBuf:http://www.freebuf.com/articles/database/140773.html

代码基于C++语言编写,先放出来C++下的Base64加密

unsigned char * base64 = (unsigned char *)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
CString base64encode(CString src, int srclen)
{
	int n, buflen, i, j;
	static unsigned char *dst;
	CString buf = src;
	buflen = n = srclen;
	dst = (unsigned char*)malloc(buflen / 3 * 4 + 3);
	memset(dst, 0, buflen / 3 * 4 + 3);
	for (i = 0, j = 0; i <= buflen - 3; i += 3, j += 4) {
		dst[j] = (buf[i] & 0xFC) >> 2;
		dst[j + 1] = ((buf[i] & 0x03) << 4) + ((buf[i + 1] & 0xF0) >> 4);
		dst[j + 2] = ((buf[i + 1] & 0x0F) << 2) + ((buf[i + 2] & 0xC0) >> 6);
		dst[j + 3] = buf[i + 2] & 0x3F;
	}
	if (n % 3 == 1) {
		dst[j] = (buf[i] & 0xFC) >> 2;
		dst[j + 1] = ((buf[i] & 0x03) << 4);
		dst[j + 2] = 64;
		dst[j + 3] = 64;
		j += 4;
	}
	else if (n % 3 == 2) {
		dst[j] = (buf[i] & 0xFC) >> 2;
		dst[j + 1] = ((buf[i] & 0x03) << 4) + ((buf[i + 1] & 0xF0) >> 4);
		dst[j + 2] = ((buf[i + 1] & 0x0F) << 2);
		dst[j + 3] = 64;
		j += 4;
	}
	for (i = 0; i<j; i++) /* map 6 bit value to base64 ASCII character */
		dst[i] = base64[(int)dst[i]];
	dst[j] = 0;
	return CString(dst);
}

调用方法如下:

printf("%s",base64encode(“hello”,5));

第一个参数是要编码的字符串,后面就是这个字符串长度。如此一来,编码过后为aGVsbG8=,现在要做的就是打乱编码。然后这个不是重点。另外。我们在打乱编码以后,也是可以正常编码的。上面是一段编码的,我们来进行一下解码。首先我们把编码字符串进行修改为:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=

然后我们编码试试来解码(此时的hello被编码成了AgvSBg8=)

CString base64decode(CString inpt,int * len)
{
     int n,i,j,pad;
     unsigned char *p;
     static unsigned char *dst;
     unsigned char * src;
     *len=0;
     pad=0;
     n=inpt.GetLength();
     src=new unsigned char [n];
     for(i=0;i<n;i++)
         src[i]=inpt[i];
 
     while(n>0&&src[n-1]=='=') {
         src[n-1]=0;
         pad++;
         n--;
     }
     for(i=0;i<n;i++)   { /* map base64 ASCII character to 6 bit value */
         p=(unsigned char *)strchr((const char *)base64,(int)src[i]);
         if(!p)
              break;
         src[i]=p-(unsigned char *)base64;
     }
 
     dst=(unsigned char *)malloc(n*3/4+1);
     memset(dst,0,n*3/4+1);
     for(i=0,j=0;i<n;i+=4,j+=3) {
         dst[j]=(src[i]<<2) + ((src[i+1]&0x30)>>4);
         dst[j+1]=((src[i+1]&0x0F)<<4) + ((src[i+2]&0x3C)>>2);
         dst[j+2]=((src[i+2]&0x03)<<6) + src[i+3];
         *len+=3;
     }
     *len-=pad;
     return CString(dst);
}

解码即可还原成原来字符串hello

 

未经允许不得转载:卧栏听雨 » Base64非默认编码表加密测试
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址