0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011
0012 #include <linux/kernel.h>
0013 #include <linux/types.h>
0014 #include <linux/export.h>
0015 #include <linux/string.h>
0016 #include <linux/base64.h>
0017
0018 static const char base64_table[65] =
0019 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
0020
0021
0022
0023
0024
0025
0026
0027
0028
0029
0030
0031
0032 int base64_encode(const u8 *src, int srclen, char *dst)
0033 {
0034 u32 ac = 0;
0035 int bits = 0;
0036 int i;
0037 char *cp = dst;
0038
0039 for (i = 0; i < srclen; i++) {
0040 ac = (ac << 8) | src[i];
0041 bits += 8;
0042 do {
0043 bits -= 6;
0044 *cp++ = base64_table[(ac >> bits) & 0x3f];
0045 } while (bits >= 6);
0046 }
0047 if (bits) {
0048 *cp++ = base64_table[(ac << (6 - bits)) & 0x3f];
0049 bits -= 6;
0050 }
0051 while (bits < 0) {
0052 *cp++ = '=';
0053 bits += 2;
0054 }
0055 return cp - dst;
0056 }
0057 EXPORT_SYMBOL_GPL(base64_encode);
0058
0059
0060
0061
0062
0063
0064
0065
0066
0067
0068
0069
0070
0071
0072
0073 int base64_decode(const char *src, int srclen, u8 *dst)
0074 {
0075 u32 ac = 0;
0076 int bits = 0;
0077 int i;
0078 u8 *bp = dst;
0079
0080 for (i = 0; i < srclen; i++) {
0081 const char *p = strchr(base64_table, src[i]);
0082
0083 if (src[i] == '=') {
0084 ac = (ac << 6);
0085 bits += 6;
0086 if (bits >= 8)
0087 bits -= 8;
0088 continue;
0089 }
0090 if (p == NULL || src[i] == 0)
0091 return -1;
0092 ac = (ac << 6) | (p - base64_table);
0093 bits += 6;
0094 if (bits >= 8) {
0095 bits -= 8;
0096 *bp++ = (u8)(ac >> bits);
0097 }
0098 }
0099 if (ac & ((1 << bits) - 1))
0100 return -1;
0101 return bp - dst;
0102 }
0103 EXPORT_SYMBOL_GPL(base64_decode);