1 ## Copyright (C) 2007 Muthiah Annamalai <muthiah.annamalai@uta.edu>
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn {Function File} {@var{rval} =} base64decode (@var{code})
18 ## @deftypefnx {Function File} {@var{rval} =} base64decode (@var{code}, @var{as_string})
19 ## Convert a base64 @var{code} (a string of printable characters according to RFC 2045)
20 ## into the original ASCII data set of range 0-255. If option @var{as_string} is
21 ## passed, the return value is converted into a string.
25 ## ##base64decode(base64encode('Hakuna Matata'),true)
26 ## base64decode('SGFrdW5hIE1hdGF0YQ==',true)
27 ## ##returns 'Hakuna Matata'
31 ## See: http://www.ietf.org/rfc/rfc2045.txt
33 ## @seealso {base64encode}
36 function z = base64decode (X, as_string)
43 if ( any(X(:) < 0) || any(X(:) > 255))
44 error("base64decode is expecting integers in the range 0 .. 255");
47 ## decompose strings into the 4xN matrices
53 Y=[Y X(z-3:z)']; #keep adding columns
67 ## Work backwards. Starting at step in table,
68 ## lookup the index of the element in the table.
70 ## 6-bit encoding table, plus 1 for padding
71 ## 26*2 + 10 + 2 + 1 = 64 + 1, '=' is EOF stop mark.
72 table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
79 ## decode the incoming matrix &
80 ## write the values into Va matrix.
81 Va = -1*ones(size(Xa));
83 iAZ = (Xa >= 'A').*(Xa <= 'Z') > 0;
86 iaz = (Xa >= 'a').*(Xa <= 'z') > 0;
87 Va(iaz)=Xa(iaz)-'a'+26;
89 i09 = (Xa >= '0').*(Xa <= '9') > 0;
90 Va(i09)=Xa(i09)-'0'+52;
92 is = (Xa == '/') ; Va(is) = 63;
93 ip = (Xa == '+') ; Va(ip) = 62;
94 ieq = (Xa == '=') ; Va(ieq) = 0;
95 clear is; clear ieq; clear ip; clear i09;
96 clear iaz; clear iAZ; clear Xa; clear X;
118 ## +1 not required due to ASCII subtraction
119 ## actual decoding work
120 b1 = Y1*4 + fix(Y2/16);
121 b2 = mod(Y2,16)*16+fix(Y3/4);
122 b3 = mod(Y3,4)*64 + Y4;
124 ZEROS=sum(sum(Y==0));
141 ## is this expected behaviour?
144 while ( ( L > 0) && ( z(L)==0 ) )
152 %!assert(base64decode(base64encode('Hakuna Matata'),true),'Hakuna Matata')
153 %!assert(base64decode(base64encode([1:255])),[1:255])
154 %!assert(base64decode(base64encode('taken'),true),'taken')
155 %!assert(base64decode(base64encode('sax'),true),'sax')
156 %!assert(base64decode(base64encode('H'),true),'H')
157 %!assert(base64decode(base64encode('Ta'),true),'Ta')