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