librsync  2.0.2
base64.c
1 /*= -*- c-basic-offset: 4; indent-tabs-mode: nil; -*-
2  *
3  * librsync -- the library for network deltas
4  *
5  * Copyright (C) 2000 by Martin Pool <mbp@sourcefrog.net>
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public License
9  * as published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this program; if not, write to the Free Software
19  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20  */
21 
22 #include "config.h"
23 
24 #include <string.h>
25 #include <stdlib.h>
26 #include <stdio.h>
27 
28 #include "librsync.h"
29 
30 /** Decode a base64 string in-place - simple and slow algorithm.
31  *
32  * See RFC1521 for the specification of base64. */
33 size_t rs_unbase64(char *s)
34 {
35  char const *b64 =
36  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
37  int bit_offset, byte_offset, idx, i, n;
38  unsigned char *d = (unsigned char *)s;
39  char *p;
40 
41  n = i = 0;
42 
43  while (*s && (p = strchr(b64, *s))) {
44  idx = (int)(p - b64);
45  byte_offset = (i * 6) / 8;
46  bit_offset = (i * 6) % 8;
47  d[byte_offset] &= ~((1 << (8 - bit_offset)) - 1);
48  if (bit_offset < 3) {
49  d[byte_offset] |= (idx << (2 - bit_offset));
50  n = byte_offset + 1;
51  } else {
52  d[byte_offset] |= (idx >> (bit_offset - 2));
53  d[byte_offset + 1] = 0;
54  d[byte_offset + 1] |= (idx << (8 - (bit_offset - 2))) & 0xFF;
55  n = byte_offset + 2;
56  }
57  s++;
58  i++;
59  }
60 
61  return n;
62 }
63 
64 /** Encode a buffer as base64 - simple and slow algorithm. */
65 void rs_base64(unsigned char const *buf, int n, char *out)
66 {
67  char const *b64 =
68  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
69  int bytes, i;
70 
71  /* work out how many bytes of output there are */
72  bytes = ((n * 8) + 5) / 6;
73 
74  for (i = 0; i < bytes; i++) {
75  int byte = (i * 6) / 8;
76  int bit = (i * 6) % 8;
77 
78  if (bit < 3) {
79  if (byte >= n)
80  abort();
81  *out = b64[(buf[byte] >> (2 - bit)) & 0x3F];
82  } else {
83  if (byte + 1 == n) {
84  *out = b64[(buf[byte] << (bit - 2)) & 0x3F];
85  } else {
86  *out =
87  b64[(buf[byte] << (bit - 2) | buf[byte + 1] >> (10 - bit)) &
88  0x3F];
89  }
90  }
91  out++;
92  }
93  *out = 0;
94 }
rs_base64
void rs_base64(unsigned char const *buf, int n, char *out)
Encode a buffer as base64.
Definition: base64.c:65
librsync.h
rs_unbase64
size_t rs_unbase64(char *s)
Decode a base64 buffer in place.
Definition: base64.c:33