2

Me propuse crear un script en bash que me devolviera la codificación de una cadena de texto pasada como parámetro en base64. En vez de recurrir a algo así de fácil:

echo "Hola mundo" | base64

Preferí descomponer paso a paso el procedimiento de conversión con comandos de bash.

Resultó algo como esto:

echo -n $cadena | while IFS= read -r -n1 item; do printf "%08d" $(printf "%d\n" "'$item" | echo "ibase=10;obase=2;$(echo $(cat))" | bc); done | awk '{ for(i=0;i<length($0)/6;i++) { print substr($0"000000",6*i+1,6)} }' | while read item; do echo "ibase=2;$item" | bc; done | awk -v b64="$b64" -v cad="$cadena" '{ printf "%s", substr(b64,$0+1,1) } END { print substr("===",1,( 3 - length(cad) % 3 ) % 3)}'

Lo he codificado como OneLiner, de modo que fuera ejecutable directamente desde el terminal sin necesidad de correr ningún archivo de scripting. Me preguntaba si este código se podría reducir a algo mucho más corto. Se me ocurre, por ejemplo, conversiones de decimal a binario y viceversa sin necesidad de componer la expresión matemática para pasárselo al comando "bc". Quizá algún formateo de cadena que se pueda agrupar en un mismo "awk", etc.

Hace tiempo que no toco bash y quizá empecé la casa por el tejado, pero es típico en mí :D.

Gracias por adelantado.

P.D: por si es de interés, estoy usando una versión de Ubuntu bajo docker.

2
  • Como extrañaba las buenas preguntas como esta! Veré si dentro de poco te contesto a esta pregunta
    – Cuauhtli
    Commented el 8 may. a las 6:51
  • Gracias Cuauhtli. Me alegro que te haya gustado mi pregunta. Commented el 8 may. a las 8:02

1 respuesta 1

0

La respuesta a si se puede reducir a un comando más corto está entre, "no lo sé", y "no sin usar perl, o base64, o un programa que tengas que instalar a parte", y "no lo intenté".

Sin embargo, tengo una implementación que te puede interesar. Es una que no es completamente robusta pero puede guiarte para hacer una más robusta, sin embargo funciona para cosas que creo son básicas.

Para esta respuesta, me basé por completo en esta página dedicada al algoritmo de base64: https://base64.guru/learn/base64-algorithm/encode

Ahí se establecen ciertos pasos, pero debido a que traté de economizar unos pocos, yo hice los siguientes:

  1. Convertir la cadena de texto en representación binaria
  2. Verificar la representación binaria
  3. Añadirle un padding a la representación
  4. Convertir la representación binaria con el padding, a representacion de los índices en base decimal
  5. Convertir los índices a la representación en la base64 y concatenar el resultado
  6. Hacer el calculo de los signos "=" y añadirlos a la cadena final

Para cada representación, utilicé varios mappeos, osea, hice uso de arrays asociativos en BASH:

  1. Para convertir cada caracter ascii en su representación en binario
  2. Para convertir cada representacion en binario en representación decimal de los indices de la tabla de base 64
  3. Para obtener cada valor de la tabla de base 64 usando sus respectivos índices

En estos arrays asociativos no tomé todos los caracteres porque me dio flojera. Sin embargo, tengo los básicos como: minúsculas, mayúsculas, números, y uno que otro caracter especial como commas, letras acentuadas, brackets, etc.

Son dos scripts que hice: el primero tiene los mapeos, y el segundo todas las operaciones de ingestión, transformación, y presentación.

mappings.sh:

declare -A char_to_bin_table
char_to_bin_table=(
    [" "]="00100000"
    [\!]="00100001"
    [\"]="00100010"
    [\#]="00100011"
    [\$]="00100100"
    [\%]="00100101"
    [\&]="00100110"
    [\']="00100111"
    [\(]="00101000"
    [\)]="00101001"
    [\*]="00101010"
    [\+]="00101011"
    [\,]="00101100"
    [\-]="00101101"
    [\.]="00101110"
    [\/]="00101111"
    [0]="00110000"
    [1]="00110001"
    [2]="00110010"
    [3]="00110011"
    [4]="00110100"
    [5]="00110101"
    [6]="00110110"
    [7]="00110111"
    [8]="00111000"
    [9]="00111001"
    [\:]="00111010"
    [\;]="00111011"
    [\<]="00111100"
    [\=]="00111101"
    [\>]="00111110"
    [\?]="00111111"
    [\@]="01000000"
    [A]="01000001"
    [B]="01000010"
    [C]="01000011"
    [D]="01000100"
    [E]="01000101"
    [F]="01000110"
    [G]="01000111"
    [H]="01001000"
    [I]="01001001"
    [J]="01001010"
    [K]="01001011"
    [L]="01001100"
    [M]="01001101"
    [N]="01001110"
    [O]="01001111"
    [P]="01010000"
    [Q]="01010001"
    [R]="01010010"
    [S]="01010011"
    [T]="01010100"
    [U]="01010101"
    [V]="01010110"
    [W]="01010111"
    [X]="01011000"
    [Y]="01011001"
    [Z]="01011010"
    [\[]="01011011"
    [\\]="01011100"
    [\]]="01011101"
    [\^]="01011110"
    [_]="01011111"
    [\`]="01100000"
    [a]="01100001"
    [b]="01100010"
    [c]="01100011"
    [d]="01100100"
    [e]="01100101"
    [f]="01100110"
    [g]="01100111"
    [h]="01101000"
    [i]="01101001"
    [j]="01101010"
    [k]="01101011"
    [l]="01101100"
    [m]="01101101"
    [n]="01101110"
    [o]="01101111"
    [p]="01110000"
    [q]="01110001"
    [r]="01110010"
    [s]="01110011"
    [t]="01110100"
    [u]="01110101"
    [v]="01110110"
    [w]="01110111"
    [x]="01111000"
    [y]="01111001"
    [z]="01111010"
    [\{]="01111011"
    [\|]="01111100"
    [\}]="01111101"
    [\~]="01111110"
    [Á]="11000001"
    [É]="11001001"
    [Í]="11001101"
    [Ó]="11010011"
    [Ú]="11011010"
    [á]="11100001"
    [é]="11101001"
    [í]="11101101"
    [ó]="11110011"
    [ú]="11111010"
)

declare -A bin_to_dec_index=(
    ["00000000"]="0"
    ["00000001"]="1"
    ["00000010"]="2"
    ["00000011"]="3"
    ["00000100"]="4"
    ["00000101"]="5"
    ["00000110"]="6"
    ["00000111"]="7"
    ["00001000"]="8"
    ["00001001"]="9"
    ["00001010"]="10"
    ["00001011"]="11"
    ["00001100"]="12"
    ["00001101"]="13"
    ["00001110"]="14"
    ["00001111"]="15"
    ["00010000"]="16"
    ["00010001"]="17"
    ["00010010"]="18"
    ["00010011"]="19"
    ["00010100"]="20"
    ["00010101"]="21"
    ["00010110"]="22"
    ["00010111"]="23"
    ["00011000"]="24"
    ["00011001"]="25"
    ["00011010"]="26"
    ["00011011"]="27"
    ["00011100"]="28"
    ["00011101"]="29"
    ["00011110"]="30"
    ["00011111"]="31"
    ["00100000"]="32"
    ["00100001"]="33"
    ["00100010"]="34"
    ["00100011"]="35"
    ["00100100"]="36"
    ["00100101"]="37"
    ["00100110"]="38"
    ["00100111"]="39"
    ["00101000"]="40"
    ["00101001"]="41"
    ["00101010"]="42"
    ["00101011"]="43"
    ["00101100"]="44"
    ["00101101"]="45"
    ["00101110"]="46"
    ["00101111"]="47"
    ["00110000"]="48"
    ["00110001"]="49"
    ["00110010"]="50"
    ["00110011"]="51"
    ["00110100"]="52"
    ["00110101"]="53"
    ["00110110"]="54"
    ["00110111"]="55"
    ["00111000"]="56"
    ["00111001"]="57"
    ["00111010"]="58"
    ["00111011"]="59"
    ["00111100"]="60"
    ["00111101"]="61"
    ["00111110"]="62"
    ["00111111"]="63"
    ["01000000"]="64"
    ["01000001"]="65"
    ["01000010"]="66"
    ["01000011"]="67"
    ["01000100"]="68"
    ["01000101"]="69"
    ["01000110"]="70"
    ["01000111"]="71"
    ["01001000"]="72"
    ["01001001"]="73"
    ["01001010"]="74"
    ["01001011"]="75"
    ["01001100"]="76"
    ["01001101"]="77"
    ["01001110"]="78"
    ["01001111"]="79"
    ["01010000"]="80"
    ["01010001"]="81"
    ["01010010"]="82"
    ["01010011"]="83"
    ["01010100"]="84"
    ["01010101"]="85"
    ["01010110"]="86"
    ["01010111"]="87"
    ["01011000"]="88"
    ["01011001"]="89"
    ["01011010"]="90"
    ["01011011"]="91"
    ["01011100"]="92"
    ["01011101"]="93"
    ["01011110"]="94"
    ["01011111"]="95"
    ["01100000"]="96"
    ["01100001"]="97"
    ["01100010"]="98"
    ["01100011"]="99"
    ["01100100"]="100"
    ["01100101"]="101"
    ["01100110"]="102"
    ["01100111"]="103"
    ["01101000"]="104"
    ["01101001"]="105"
    ["01101010"]="106"
    ["01101011"]="107"
    ["01101100"]="108"
    ["01101101"]="109"
    ["01101110"]="110"
    ["01101111"]="111"
    ["01110000"]="112"
    ["01110001"]="113"
    ["01110010"]="114"
    ["01110011"]="115"
    ["01110100"]="116"
    ["01110101"]="117"
    ["01110110"]="118"
    ["01110111"]="119"
    ["01111000"]="120"
    ["01111001"]="121"
    ["01111010"]="122"
    ["01111011"]="123"
    ["01111100"]="124"
    ["01111101"]="125"
    ["01111110"]="126"
    ["01111111"]="127"
    ["10000000"]="128"
    ["10000001"]="129"
    ["10000010"]="130"
    ["10000011"]="131"
    ["10000100"]="132"
    ["10000101"]="133"
    ["10000110"]="134"
    ["10000111"]="135"
    ["10001000"]="136"
    ["10001001"]="137"
    ["10001010"]="138"
    ["10001011"]="139"
    ["10001100"]="140"
    ["10001101"]="141"
    ["10001110"]="142"
    ["10001111"]="143"
    ["10010000"]="144"
    ["10010001"]="145"
    ["10010010"]="146"
    ["10010011"]="147"
    ["10010100"]="148"
    ["10010101"]="149"
    ["10010110"]="150"
    ["10010111"]="151"
    ["10011000"]="152"
    ["10011001"]="153"
    ["10011010"]="154"
    ["10011011"]="155"
    ["10011100"]="156"
    ["10011101"]="157"
    ["10011110"]="158"
    ["10011111"]="159"
    ["10100000"]="160"
    ["10100001"]="161"
    ["10100010"]="162"
    ["10100011"]="163"
    ["10100100"]="164"
    ["10100101"]="165"
    ["10100110"]="166"
    ["10100111"]="167"
    ["10101000"]="168"
    ["10101001"]="169"
    ["10101010"]="170"
    ["10101011"]="171"
    ["10101100"]="172"
    ["10101101"]="173"
    ["10101110"]="174"
    ["10101111"]="175"
    ["10110000"]="176"
    ["10110001"]="177"
    ["10110010"]="178"
    ["10110011"]="179"
    ["10110100"]="180"
    ["10110101"]="181"
    ["10110110"]="182"
    ["10110111"]="183"
    ["10111000"]="184"
    ["10111001"]="185"
    ["10111010"]="186"
    ["10111011"]="187"
    ["10111100"]="188"
    ["10111101"]="189"
    ["10111110"]="190"
    ["10111111"]="191"
    ["11000000"]="192"
    ["11000001"]="193"
    ["11000010"]="194"
    ["11000011"]="195"
    ["11000100"]="196"
    ["11000101"]="197"
    ["11000110"]="198"
    ["11000111"]="199"
    ["11001000"]="200"
    ["11001001"]="201"
    ["11001010"]="202"
    ["11001011"]="203"
    ["11001100"]="204"
    ["11001101"]="205"
    ["11001110"]="206"
    ["11001111"]="207"
    ["11010000"]="208"
    ["11010001"]="209"
    ["11010010"]="210"
    ["11010011"]="211"
    ["11010100"]="212"
    ["11010101"]="213"
    ["11010110"]="214"
    ["11010111"]="215"
    ["11011000"]="216"
    ["11011001"]="217"
    ["11011010"]="218"
    ["11011011"]="219"
    ["11011100"]="220"
    ["11011101"]="221"
    ["11011110"]="222"
    ["11011111"]="223"
    ["11100000"]="224"
    ["11100001"]="225"
    ["11100010"]="226"
    ["11100011"]="227"
    ["11100100"]="228"
    ["11100101"]="229"
    ["11100110"]="230"
    ["11100111"]="231"
    ["11101000"]="232"
    ["11101001"]="233"
    ["11101010"]="234"
    ["11101011"]="235"
    ["11101100"]="236"
    ["11101101"]="237"
    ["11101110"]="238"
    ["11101111"]="239"
    ["11110000"]="240"
    ["11110001"]="241"
    ["11110010"]="242"
    ["11110011"]="243"
    ["11110100"]="244"
    ["11110101"]="245"
    ["11110110"]="246"
    ["11110111"]="247"
    ["11111000"]="248"
    ["11111001"]="249"
    ["11111010"]="250"
    ["11111011"]="251"
    ["11111100"]="252"
    ["11111101"]="253"
    ["11111110"]="254"
    ["11111111"]="255"
)

declare -A base64_rep=(
    ["0"]="A"
    ["1"]="B"
    ["2"]="C"
    ["3"]="D"
    ["4"]="E"
    ["5"]="F"
    ["6"]="G"
    ["7"]="H"
    ["8"]="I"
    ["9"]="J"
    ["10"]="K"
    ["11"]="L"
    ["12"]="M"
    ["13"]="N"
    ["14"]="O"
    ["15"]="P"
    ["16"]="Q"
    ["17"]="R"
    ["18"]="S"
    ["19"]="T"
    ["20"]="U"
    ["21"]="V"
    ["22"]="W"
    ["23"]="X"
    ["24"]="Y"
    ["25"]="Z"
    ["26"]="a"
    ["27"]="b"
    ["28"]="c"
    ["29"]="d"
    ["30"]="e"
    ["31"]="f"
    ["32"]="g"
    ["33"]="h"
    ["34"]="i"
    ["35"]="j"
    ["36"]="k"
    ["37"]="l"
    ["38"]="m"
    ["39"]="n"
    ["40"]="o"
    ["41"]="p"
    ["42"]="q"
    ["43"]="r"
    ["44"]="s"
    ["45"]="t"
    ["46"]="u"
    ["47"]="v"
    ["48"]="w"
    ["49"]="x"
    ["50"]="y"
    ["51"]="z"
    ["52"]="0"
    ["53"]="1"
    ["54"]="2"
    ["55"]="3"
    ["56"]="4"
    ["57"]="5"
    ["58"]="6"
    ["59"]="7"
    ["60"]="8"
    ["61"]="9"
    ["62"]="+"
    ["63"]="/"
)

main.sh:

#!/usr/bin/env bash

. mappings.sh

declare -a base_64_indexes

export array_characters_str
export chars_to_bin
export base64_result
export equals

declare -a bin_rep_with_padding
declare -a bin_padding_rep_to_dec

map_char_to_bin_representation() {
    local -r string="$1"
    for ((i=0; i < ${#string}; i++)); do
        character="${string:$i:1}"
        chars_to_bin="$chars_to_bin""${char_to_bin_table[$character]}"
    done
}

create_equals() {
    modulo=$(( ${#string_to_convert} % 3))
    [ $modulo -eq 1 ] && amount_equals=2
    [ $modulo -eq 2 ] && amount_equals=1
    [ $modulo -eq 0 ] && amount_equals=0

    [ $amount_equals -ne 0 ] && equals="$(eval "printf '=%.0s' {1..$amount_equals}")"
}

verify_mapping() {

    local -ri string_to_convert_length="${#1}"
    local -ri expected_chars=$((string_to_convert_length*8))
    local -ri chars_to_bin_len="${#2}"
    
    [ $expected_chars -ne $chars_to_bin_len ] && {
        echo >&2 "[ERROR] Expected bytes are:  \"$expected_chars\", but found, \"$((chars_to_bin_len))\" chars"
        exit 1
    }
}

return_with_padding() {
    local -ri reminder="$(( ${#chars_to_bin} % 6 ))"
    local -ri times_to_div="$(( ${#chars_to_bin} / 6 ))"

    offset=0
    for ((i=0; i < times_to_div; i++)); do
        offset=$((6*i))
        bin_rep_with_padding+=("00${chars_to_bin:$offset:6}")
    done
    [ "$reminder" -ne 0 ] && {
        offset=$((offset+6))
        last_padding_chars=$((6-reminder))
        right_padding="$(eval "printf '0%.0s' {1..$last_padding_chars}")"
        bin_rep_with_padding+=("00${chars_to_bin:$offset:$reminder}${right_padding}")
    }
}

convert_bin_padding_rep_to_dec() {
    for padding_rep in ${bin_rep_with_padding[@]}; do
        decimal_rep="${bin_to_dec_index["$padding_rep"]}"
        base_64_indexes+=("$decimal_rep")
    done
}

convert_index_to_base64_str() {
    for index in ${base_64_indexes[@]}; do
        base64_char="${base64_rep[$index]}"
        base64_result="${base64_result}${base64_char}"
    done
}

main() {
    local -r string_to_convert="$1"
    map_char_to_bin_representation "$string_to_convert"
    verify_mapping "$string_to_convert" "$chars_to_bin"
    return_with_padding "$chars_to_bin"
    convert_bin_padding_rep_to_dec
    convert_index_to_base64_str
    create_equals "$string_to_convert"
    echo -e "${base64_result}${equals}"
}

read string_to_convert
main "$string_to_convert"

Y la forma de usarla es la siguiente:

$ echo -n "Mi cadena [de] {texto}" | ./main.sh
TWkgY2FkZW5hIFtkZV0ge3RleHRvfQ==
$ echo -n "Mi cadena [de] {texto}" | base64
TWkgY2FkZW5hIFtkZV0ge3RleHRvfQ==

Nota: como recordatorio, este scriot no toma en cuenta a los saltos de líneas y otros caracteres. Es sólo para cadenas de caracteres no tan exóticos.

1
  • 1
    Una respuesta excepcional Cuahtli, muy larga, pero me ha ayudado a refrescar algunos conceptos de bash. Muchas gracias por tu ayuda. Commented el 14 may. a las 15:05

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.