我的qq密码的md5是:cbfd2857e0ec3ebfad4173e0a89c7530
我修改了程序,loveyouforever27加密后是:aeCjGRYVgDokmoyiPBUr1w==
发现老K算的是:aeCjGRYVgDokmoyiPBUr16iZkQ==
在处理多余字节时处理方式不一样,md5是16个字节,3个一组余一个,填充0凑4字节,填充部分在编码时用=号来代替。我的理解和这个在线计算器一样:http://md5.
MD5值是否需要调整字节序呢?
去看MD5算法发现MD5值是四个32bit整数连接而成,貌似不需要调整字节序,难道我又干了蠢事?还和老K蠢到一起去了。
这是我的代码,通过#define BASE64_TEST开关base64编码测试,可以去这里测试:http://md5.
#include <stdio.h>
#include <string.h>
void base64(void *data, int length);
#define BASE64_TEST_LENGTH 40
//#define BASE64_TEST
int main(void)
{
int i;
unsigned char ch;
unsigned char *str=NULL;
int md5[4];
char md5_string[9];
#ifdef BASE64_TEST
char test[BASE64_TEST_LENGTH];
printf("请输入base64测试字符串:");
scanf("%s",test);
printf("\nbase64加密后的字符串:");
base64(test,strlen(test));
#else
printf("请输入32个字符的md5字符串:");
for(i=0;i<4;++i)
{
fgets(md5_string,9,stdin);
sscanf(md5_string, "%x",&md5[i]);
//翻转字节序
str = (unsigned char *)(md5 + i);
ch = str[0];
str[0] = str[3];
str[3] = ch;
ch = str[1];
str[1] = str[2];
str[2] = ch;
}
printf("\nbase64加密后的字符串:");
base64(md5,sizeof(md5));
#endif
return 0;
}
void base64(void *data, int length)
{
const char Base64_Alphabet[]=
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int i;
unsigned char ch[4];
unsigned char *str = (unsigned char*)data;
for(i=0;i+2<length;i+=3)
{
ch[0] = str[i]>>2;
ch[1] = (str[i]<<4 & 0x3f) | (str[i+1]>>4);
ch[2] = (str[i+1]<<2 & 0x3f) | (str[i+2]>>6);
ch[3] = str[i+2] & 0x3f;
putchar(Base64_Alphabet[ch[0]]);
putchar(Base64_Alphabet[ch[1]]);
putchar(Base64_Alphabet[ch[2]]);
putchar(Base64_Alphabet[ch[3]]);
}
if(length % 3 == 0)
{
puts("\n");
return ;
}
if(length % 3 == 1)
{
putchar(Base64_Alphabet[str[i]>>2]);
putchar(Base64_Alphabet[str[i]<<4 & 0x30]);
puts("==\n");
return ;
}
if(length % 3 == 2)
{
putchar(Base64_Alphabet[str[i]>>2]);
putchar(Base64_Alphabet[(str[i]<<4 & 0x3f) | (str[i+1]>>4)]);
putchar(Base64_Alphabet[(str[i+1]<<2 & 0x3f)]);
puts("=\n");
}
}