encode as base64, returning allocated string */
| 74 | encode as base64, returning allocated string |
| 75 | */ |
| 76 | char *base64_encode(const uint8_t *d, int len) |
| 77 | { |
| 78 | uint32_t bit_offset, byte_offset, idx, i; |
| 79 | uint32_t bytes = (len*8 + 5)/6; |
| 80 | uint32_t pad_bytes = (bytes % 4) ? 4 - (bytes % 4) : 0; |
| 81 | |
| 82 | char *out = new char[bytes+pad_bytes+1]; |
| 83 | if (!out) { |
| 84 | return nullptr; |
| 85 | } |
| 86 | |
| 87 | for (i=0;i<bytes;i++) { |
| 88 | byte_offset = (i*6)/8; |
| 89 | bit_offset = (i*6)%8; |
| 90 | if (bit_offset < 3) { |
| 91 | idx = (d[byte_offset] >> (2-bit_offset)) & 0x3FU; |
| 92 | } else { |
| 93 | idx = (d[byte_offset] << (bit_offset-2)) & 0x3FU; |
| 94 | if (byte_offset+1 < len) { |
| 95 | idx |= (d[byte_offset+1] >> (8-(bit_offset-2))); |
| 96 | } |
| 97 | } |
| 98 | out[i] = b64[idx]; |
| 99 | } |
| 100 | |
| 101 | for (;i<bytes+pad_bytes;i++) { |
| 102 | out[i] = '='; |
| 103 | } |
| 104 | out[i] = 0; |
| 105 | |
| 106 | return out; |
| 107 | } |