]> gitweb.factorcode.org Git - factor.git/blob - contrib/crypto/base64.factor
fix contrib/crypto
[factor.git] / contrib / crypto / base64.factor
1 USING: kernel math math-contrib sequences namespaces io strings hashtables ;
2 IN: crypto-internals
3
4 : ch>base64 ( ch -- ch )
5     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" nth ;
6
7 : base64>ch ( ch -- ch )
8     {
9         f f f f f f f f f f f f f f f f f f f f f f f f f f f f f f f f f
10         f f f f f f f f f f 62 f f f 63 52 53 54 55 56 57 58 59 60 61 f f
11         f 0 f f f 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
12         22 23 24 25 f f f f f f 26 27 28 29 30 31 32 33 34 35 36 37 38 39
13         40 41 42 43 44 45 46 47 48 49 50 51
14     } nth ;
15
16 : encode3 ( seq -- seq )
17     be> 4 [ 3 swap - -6 * shift HEX: 3f bitand ch>base64 ] map-with ;
18
19 : decode4 ( str -- str )
20     [ base64>ch ] map 0 [ swap 6 shift bitor ] reduce 3 >be ;
21
22 : >base64-rem ( str -- str )
23     [ 3 0 pad-right encode3 ] keep length 1+ head 4 CHAR: = pad-right ;
24
25 IN: crypto
26 : >base64 ( str -- str )
27     #! cut string into two pieces, convert 3 bytes at a time
28     #! pad string with = when not enough bits
29     [ length dup 3 mod - ] keep cut swap
30     [
31         3 group [ encode3 % ] each
32         dup empty? [ drop ] [ >base64-rem % ] if
33     ] "" make ;
34
35 : base64> ( str -- str )
36     #! input length must be a mulitple of 4
37     [
38         [ 4 group [ decode4 % ] each ] keep [ CHAR: = = not ] count-end 
39     ] SBUF" " make swap [ dup pop* ] times >string ;
40