由于实在不到原创地址,所以没法给出链接,但对原创表示感谢。
我测试了一下,发现下面程序的编解码器是正确的。 Base64编解码非常常见, 要大致弄清原理。 另外, 在编解码前, 最好判断一下,待定字符串是否已经是密文/明文的。 有方法哈!
下面静静欣赏Base64编解码过程:
#include <stdio.h> #include <malloc.h> #include <string.h> char *base64_encode(const char *toBeEncoded); char *base64_decode(const char *toBeDecoded); // 64 + 1, 最后的'='是填充符号 char table[] = { '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' , '+', '/' , '=' }; char *base64_encode(const char *src) { int count = 0; char *dst = NULL; int tmp = 0, buf = 0; char in[4] = {0}; int i = 0, j = 0; count = strlen(src) / 3 + (strlen(src) % 3 ? 1 : 0); dst = (char *)malloc(count * 4 + 1); memset(dst, 0, count * 4 + 1); for(j = 0; j < count; j++) { memset(in, 0, sizeof(in)); strncpy(in, src + j * 3, 3); buf = 0; for(i = 0; i < strlen(in); i++) { tmp = (long)in[i]; tmp <<= (16 - i * 8); buf |= tmp; } for(i = 0; i < 4; i++) { if(strlen(in) + 1 > i) { tmp = buf >> (18 - 6 * i); tmp &= 0x3f; dst[j * 4 + i] = table[tmp]; } else { dst[j * 4 + i] = '='; } } } return dst; } char *base64_decode(const char *src) { int count = 0, len = 0; char *dst = NULL; int tmp = 0, buf = 0; int i = 0, j = 0, k = 0; char in[5] = {0}; len = strlen(src); count = len / 4; dst = (char *)malloc(count * 3 + 1); memset(dst, 0, count * 3 + 1); for(j = 0; j < count; j++) { memset(in, 0, sizeof(in)); strncpy(in, src + j * 4, 4); buf = 0; for(i = 0; i < 4; i++) { tmp = (long)in[i]; if(tmp == '=') { tmp = 0; } else { for(k = 0; ; k++) { if(table[k] == tmp) break; } tmp = k; } tmp <<= (18 - i * 6); buf |= tmp; } for(i = 0; i < 3; i++) { tmp = buf >> (16 - i * 8); tmp &= 0xff; dst[j * 3 + i] = tmp; } } return dst; } int main() { char *src = NULL, *dst = NULL; src = "Microsoft & Apple!"; printf("%d\n", strlen(src)); dst = base64_encode(src); printf("%s\n", dst); printf("%d\n", strlen(dst)); printf("%s\n", base64_decode(dst)); return 0; }