| 1 | /************************************************* |
| 2 | * Exim - an Internet mail transport agent * |
| 3 | *************************************************/ |
| 4 | |
| 5 | /* Copyright (c) University of Cambridge 1995 - 2009 */ |
| 6 | /* See the file NOTICE for conditions of use and distribution. */ |
| 7 | |
| 8 | #include "../exim.h" |
| 9 | |
| 10 | |
| 11 | /************************************************* |
| 12 | * Encode byte-string in base 64 * |
| 13 | *************************************************/ |
| 14 | |
| 15 | /* This function encodes a string of bytes, containing any values whatsoever, |
| 16 | in base 64 as defined in RFC 2045 (MIME) and required by the SMTP AUTH |
| 17 | extension (RFC 2554). The encoding algorithm is written out in a |
| 18 | straightforward way. Turning it into some kind of compact loop is messy and |
| 19 | would probably run more slowly. |
| 20 | |
| 21 | Arguments: |
| 22 | clear points to the clear text bytes |
| 23 | len the number of bytes to encode |
| 24 | |
| 25 | Returns: a pointer to the zero-terminated base 64 string, which |
| 26 | is in working store |
| 27 | */ |
| 28 | |
| 29 | static uschar *enc64table = |
| 30 | US"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; |
| 31 | |
| 32 | uschar * |
| 33 | auth_b64encode(uschar *clear, int len) |
| 34 | { |
| 35 | uschar *code = store_get(4*((len+2)/3) + 1); |
| 36 | uschar *p = code; |
| 37 | |
| 38 | while (len-- >0) |
| 39 | { |
| 40 | register int x, y; |
| 41 | |
| 42 | x = *clear++; |
| 43 | *p++ = enc64table[(x >> 2) & 63]; |
| 44 | |
| 45 | if (len-- <= 0) |
| 46 | { |
| 47 | *p++ = enc64table[(x << 4) & 63]; |
| 48 | *p++ = '='; |
| 49 | *p++ = '='; |
| 50 | break; |
| 51 | } |
| 52 | |
| 53 | y = *clear++; |
| 54 | *p++ = enc64table[((x << 4) | ((y >> 4) & 15)) & 63]; |
| 55 | |
| 56 | if (len-- <= 0) |
| 57 | { |
| 58 | *p++ = enc64table[(y << 2) & 63]; |
| 59 | *p++ = '='; |
| 60 | break; |
| 61 | } |
| 62 | |
| 63 | x = *clear++; |
| 64 | *p++ = enc64table[((y << 2) | ((x >> 6) & 3)) & 63]; |
| 65 | |
| 66 | *p++ = enc64table[x & 63]; |
| 67 | } |
| 68 | |
| 69 | *p = 0; |
| 70 | |
| 71 | return code; |
| 72 | } |
| 73 | |
| 74 | /* End of b64encode.c */ |