Base64cp » История » Версия 1
Андрей Волков, 2013-06-03 19:38
1 | 1 | Андрей Волков | h1. Декодирование base64 средствами bash |
---|---|---|---|
2 | |||
3 | <pre> |
||
4 | #!/bin/bash |
||
5 | |||
6 | # Base64 decoding routine written entirely in bash, with no external dependencies. |
||
7 | # |
||
8 | # Usage: |
||
9 | # base64decode < input > output |
||
10 | # |
||
11 | # This code is absurly inefficient; it runs aproximately 12,000 times slower than |
||
12 | # the perl-based decoder. The difference is that this code doesn't require you to |
||
13 | # install any external programs, which may be important in some cases. |
||
14 | # |
||
15 | # To decode using perl instead, use the following: |
||
16 | # |
||
17 | # base64decode() { |
||
18 | # perl -e 'use MIME::Base64 qw(decode_base64);$/=undef;print decode_base64(<>);' |
||
19 | # } |
||
20 | # |
||
21 | |||
22 | base64decode() { |
||
23 | L=0 |
||
24 | A=0 |
||
25 | P=0 |
||
26 | while read -n1 C ; do |
||
27 | printf -v N %i \'"$C" |
||
28 | if (( $N == 61 )) ; then |
||
29 | P=$(( $P + 1 )) # = (padding) |
||
30 | V=0 |
||
31 | elif (( $N == 43 )) ; then |
||
32 | V=62 # + |
||
33 | elif (( $N == 47 )) ; then |
||
34 | V=63 # / |
||
35 | elif (( $N < 48 )) ; then |
||
36 | continue |
||
37 | elif (( $N < 58 )) ; then |
||
38 | V=$(( $N + 4 )) # -48 + 52 (0-9) |
||
39 | elif (( $N < 65 )) ; then |
||
40 | continue |
||
41 | elif (( $N < 91 )) ; then |
||
42 | V=$(( $N - 65 )) # -65 + 0 (A-Z) |
||
43 | elif (( $N < 97 )) ; then |
||
44 | continue |
||
45 | elif (( $N < 123 )) ; then |
||
46 | V=$(( $N - 71 )) # -97 + 26 (a-z) |
||
47 | else |
||
48 | continue |
||
49 | fi |
||
50 | |||
51 | A=$(( ($A << 6) | $V )) |
||
52 | L=$(( $L + 1 )) |
||
53 | |||
54 | if [ $L == 4 ] ; then |
||
55 | printf -v X "%x" $(( ($A >> 16) & 0xFF )) |
||
56 | printf "\x$X" |
||
57 | if (( $P < 2 )) ; then |
||
58 | printf -v X "%x" $(( ($A >> 8) & 0xFF )) |
||
59 | printf "\x$X" |
||
60 | fi |
||
61 | if (( $P == 0 )) ; then |
||
62 | printf -v X "%x" $(( $A & 0xFF )) |
||
63 | printf "\x$X" |
||
64 | fi |
||
65 | A=0 |
||
66 | L=0 |
||
67 | P=0 |
||
68 | fi |
||
69 | done |
||
70 | } |
||
71 | |||
72 | base64decode |
||
73 | </pre> |