00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #include "adchpp.h"
00020
00021 #include "Encoder.h"
00022 #include "common.h"
00023
00024 namespace adchpp {
00025
00026 using namespace std;
00027
00028 const int8_t Encoder::base32Table[256] = {
00029 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00030 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00031 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00032 -1,-1,26,27,28,29,30,31,-1,-1,-1,-1,-1,-1,-1,-1,
00033 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
00034 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,
00035 -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
00036 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,
00037 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00038 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00039 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00040 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00041 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00042 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00043 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00044 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
00045 };
00046
00047 const char Encoder::base32Alphabet[32] = {
00048 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
00049 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
00050 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
00051 'Y', 'Z', '2', '3', '4', '5', '6', '7'
00052 };
00053
00054 string& Encoder::toBase32(const uint8_t* src, size_t len, string& dst) {
00055
00056 size_t i, index;
00057 uint8_t word;
00058 dst.reserve(((len * 8) / 5) + 1);
00059
00060 for(i = 0, index = 0; i < len;) {
00061
00062 if (index > 3) {
00063 word = (uint8_t)(src[i] & (0xFF >> index));
00064 index = (index + 5) % 8;
00065 word <<= index;
00066 if ((i + 1) < len)
00067 word |= src[i + 1] >> (8 - index);
00068
00069 i++;
00070 } else {
00071 word = (uint8_t)(src[i] >> (8 - (index + 5))) & 0x1F;
00072 index = (index + 5) % 8;
00073 if (index == 0)
00074 i++;
00075 }
00076
00077 dcassert(word < 32);
00078 dst += base32Alphabet[word];
00079 }
00080 return dst;
00081 }
00082
00083 void Encoder::fromBase32(const char* src, uint8_t* dst, size_t len) {
00084 size_t i, index, offset;
00085
00086 memset(dst, 0, len);
00087 for(i = 0, index = 0, offset = 0; src[i]; i++) {
00088
00089 int8_t tmp = base32Table[(unsigned char)src[i]];
00090
00091 if(tmp == -1)
00092 continue;
00093
00094 if (index <= 3) {
00095 index = (index + 5) % 8;
00096 if (index == 0) {
00097 dst[offset] |= tmp;
00098 offset++;
00099 if(offset == len)
00100 break;
00101 } else {
00102 dst[offset] |= tmp << (8 - index);
00103 }
00104 } else {
00105 index = (index + 5) % 8;
00106 dst[offset] |= (tmp >> index);
00107 offset++;
00108 if(offset == len)
00109 break;
00110 dst[offset] |= tmp << (8 - index);
00111 }
00112 }
00113 }
00114
00115 }