Кодирование и декодирование в формате base64

Оглавление

Рабочее место менеджера по продажам

Каждый день менеджеры создают кучу документов. Это и заказы покупателей и сопутствующие документы, которые создаются на основании. Менеджеру всегда необходимо иметь под рукой наиболее эффективный инструмент для формирования заявки от покупателя. Таковым я постарался сделать и эту обработку.

Обработка «Рабочее место менеджера продаж» позволяет быстро узнать информацию о товарах на складах, цены товара в различных типах цен номенклатуры, узнать какие цены у поставщиков по выбранному товару и так далее.

Много месяцев текущая обработка работает на благо сотрудников и приносит действительно большую пользу. Правда, она более внедрена в работу организации, но даже её модифицированная часть для общества должна принести не менее выгоды в работе с товарами и и заказами покупателей. Так что вот она.

5 стартмани

(Functional) Comparison to classes in .NET

General

base64Url isn’t supported, so hacky solutions like

string base64 = Convert.ToBase64String(data);
string base64Url = base64.Replace('+', '-').Replace('/', '_').TrimEnd('=');

are needed. This isn’t ideal, as there are avoidable allocations and several iterations over the encoded string (see here and here for benchmark results).

gfoidl.Base64 supports encoding / decoding to / from base64Url in a direct way.
Encoding for UTF-8 is supported, as well as .
Decoding for UTF-8 is supported, as well as .

Further SIMD isn’t utilized in the .NET classes.
(Note: I’ve opened an issue to add SIMD-support to these classes).

Convert.ToBase64XYZ / Convert.FromBase64XYZ

These methods only support as types for encoding,
and as types for decoding, where can also be or .

To support UTF-8 another method call like

byte[] utf8Encoded = Encoding.ASCII.GetBytes(base64String);

is needed.

Java 8 для базы 64

Java 8 наконец-то добавила возможности Base64 в стандартный API. Это делается через класс утилиты java.util.Base64 .

Давайте начнем с рассмотрения базового процесса кодирования.

2.1. Java 8 Basic Base64

Базовый кодер упрощает работу и кодирует вход как есть, без какого-либо разделения строк.

Выходные данные отображаются на набор символов в A-Za-z0-9+/ набор символов, и декодер отклоняет любой символ за пределами этого набора.

Давайте сначала закодируем простую строку :

String originalInput = "test input";
String encodedString = Base64.getEncoder().encodeToString(originalInput.getBytes());

Обратите внимание, как мы получаем полный API кодировщика с помощью простого метода GetEncoder() utility. Теперь давайте расшифруем эту строку обратно в исходную форму:

Теперь давайте расшифруем эту строку обратно в исходную форму:

byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
String decodedString = new String(decodedBytes);

2.2. Кодировка Java 8 Base64 Без Заполнения

В кодировке Base64 длина выходной кодированной строки должна быть кратна трем. Если нет, то вывод будет дополнен дополнительными символами pad ( = ).

После декодирования эти дополнительные символы заполнения будут отброшены. Чтобы углубиться в заполнение в Base64, ознакомьтесь с этим подробным ответом на Переполнение стека .

Если нам нужно пропустить заполнение вывода — возможно, потому, что результирующая строка никогда не будет декодирована обратно — мы можем просто выбрать кодирование без заполнения :

String encodedString = 
  Base64.getEncoder().withoutPadding().encodeToString(originalInput.getBytes());

2.3. Кодировка URL-адресов Java 8

Кодировка URL-адресов очень похожа на базовый кодер, который мы рассмотрели выше. Он использует безопасный алфавит Base64 URL и имени файла и не добавляет никакого разделения строк:

String originalUrl = "https://www.google.co.nz/?gfe_rd=cr&ei=dzbFV&gws_rd=ssl#q=java";
String encodedUrl = Base64.getUrlEncoder().encodeToString(originalURL.getBytes());

Декодирование происходит во многом таким же образом. Метод утилиты getUrlDecoder() возвращает java.util.Base64.Decoder , который затем используется для декодирования URL-адреса:

byte[] decodedBytes = Base64.getUrlDecoder().decode(encodedUrl);
String decodedUrl = new String(decodedBytes);

2.4. Кодировка MIME Java 8

Давайте начнем с создания некоторого базового ввода MIME для кодирования:

private static StringBuilder getMimeBuffer() {
    StringBuilder buffer = new StringBuilder();
    for (int count = 0; count < 10; ++count) {
        buffer.append(UUID.randomUUID().toString());
    }
    return buffer;
}

Кодер MIME генерирует выходные данные в кодировке Base64, используя базовый алфавит, но в удобном для MIME формате.

Каждая строка вывода содержит не более 76 символов и заканчивается возвратом каретки, за которым следует перевод строки ( \r\n ):

StringBuilder buffer = getMimeBuffer();
byte[] encodedAsBytes = buffer.toString().getBytes();
String encodedMime = Base64.getMimeEncoder().encodeToString(encodedAsBytes);

Метод утилиты getMimeDecoder() возвращает java.util.Base64.Decoder , который затем используется в процессе декодирования:

byte[] decodedBytes = Base64.getMimeDecoder().decode(encodedMime);
String decodedMime = new String(decodedBytes);

Decode eval gzinflate base64_decode.

Base64 decoder above will show something like this

<?php
eval(gzinflate(base64_decode('K64sLknN1VCJd3cNiVZPzk1Rj9W0BgA=')));
?>

It’s so, because this code was first compressed using gzdeflate and compressed data was encoded into base64. The script above will decode, decompress an execute obfuscated part of code.

Example below illustrate that kind of code obfuscation:

$ob=’system($_GET);’; // Original // system($_GET);
$gzcompressed = base64_encode(gzdeflate($ob)); // Obfuscated // K64sLknN1VCJd3cNiVZPzk1Rj9W0BgA=
$gzcompressed1 = base64_encode(gzdeflate($gzcompressed)); // Obfuscated two times // 8zYzKfbJzvMzDHP2SjFO9ssMiwqoyjYMyrIMN3BKd7QFAA==
$decompressed1 = gzinflate(base64_decode($gzcompressed1)); // Deobfuscated one time // K64sLknN1VCJd3cNiVZPzk1Rj9W0BgA=
$decompressed = gzinflate(base64_decode($decompressed1)); // Deobfuscated two times // system($_GET);

To decode gzinflate base64_decode construction automatically, paste your code below included php tags.

Base64 tools:

How base64 encoding works.Decode eval gzinflate encoding.Image base64 encoder. Image base64 decode.Convert decimal to binary, binary to decimal.Convert decimal to hexadecimal, binary, octal.Generate MD5, SHA1, SHA256 and other hashes.Decrypt Cisco 7 and Cisco VPN passwords.Mac address database. MAC address range lookup.Crack MD5 passwords.Information about an ip address.Find ISP ip address ranges.Check if port is open.

More Info and Resources

The Base 64 Alphabet

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

RFC’s

  • RFC 1866 — Hypertext Markup Language — 2.0
  • RFC 2045 — Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies
  • RFC 2046 — Definition of media types
  • RFC 2077 — Model top-level media type
  • RFC 2396 — Uniform Resource Identifiers (URI): Generic Syntax
  • RFC 2397 — The «data» URL scheme
  • RFC 3023 — Media types based on XML
  • RFC 4648 — The Base16, Base32, and Base64 Data Encodings
  • RFC 6657 — Update to MIME regarding «charset» Parameter Handling in Textual Media Types
  • RFC 5988 — Web Linking

Type image

GIF image; Defined in RFC 2045 and RFC 2046
JPEG JFIF image; Defined in RFC 2045 and RFC 2046
JPEG JFIF image; Associated with Internet Explorer; Listed in ms775147(v=vs.85) — Progressive JPEG, initiated before global browser support for progressive JPEGs (Microsoft and Firefox).
Portable Network Graphics; Registered, Defined in RFC 2083
SVG vector image; Defined in SVG Tiny 1.2 Specification Appendix M
Tag Image File Format (only for Baseline TIFF); Defined in RFC 3302
ICO image; Registered

Misc

  • Image to data URI convertor
  • : Your one-stop HTML5 spot for all things Data URL
  • The data: URI kitchen
  • php: data://
  • Using Data URLs Effectively with Cascading Style Sheets
  • getID3: PHP script that extracts useful information from MP3s & other multimedia file formats:

Missing Data

Its not uncommon to experience Missing Data in a pipeline. A source will send data through a pipeline but have nothing in the sink. This is usually due to the compiler matching the wrong function. For example:

string source = "FF 88 00", destination;
StringSink ss(source,
    new HexDecoder(
        new StringSink(destination)
    ) // HexDecoder
); // StringSink

After the above code executes, will likely be empty because the compiler coerces the (the pointer) to a (the parameter), which leaves the ‘s attached transformation . The compiler will do so without warning, even with . To resolve the issue, explicitly specify the parameter:

string source = "FF 88 00", destination;
StringSink ss(source, true /*pumpAll*/,
    new HexDecoder(
        new StringSink(destination)
    ) // HexDecoder
); // StringSink

Another way data ends up missing is failing to call when pumping data. For example, the following may not produce expected results:

// The 4-bit nibble will be buffered waiting for another nibble
string source = "FF 88 0", destination;

HexDecoder decoder(new StringSink(destination));
decoder.Put(source.data(), source.size());

// Do something with destination

In the case of a Base64 encoder, the filter will buffer the first two octets while waiting on a third octet. Be sure to call when data comes up missing:

Binary to base64

Since a little math is involved to determine the encoded size we’ll use this
simple function to help us out.

It’s pretty self explanatory but if you didn’t read the paragraphs above that
explain the math, I highly recommend you go back and do so.

Now we need to move the mapping table. Unlike decoding this is an array which
we’ll reference by index as we encode. This table is used to turn 3 byte
sequences into characters.

The encode function works in blocks of 3 bytes of binary data to turn it into
base64 ASCII characters.

Here we push the 3 bytes into an . If there are less than 3 bytes just
shift so we can properly pull the value back out later.

Next we pull the base64 character out of the mapping. 0x3F is used because it
is 6 bits where all are set (a mask). Since each output byte is split into a
series of 6 bits we need to only map using the bits being put into a given
output byte.

Finally, add the byte or an for padding if there are less than 3 bytes in
the last block. 1 and 2 fewer than 3 bytes gets 1 or 2 padding characters.

Обработка «Распознавание штрихкода с помощью утилиты Zbar» для Документооборот ред. 2

В связи с тем, что стандартный функционал программы «Документооборот» ред. 2.1 дает возможность распознавания штрихкодов только форма EAN-13, данная обработка — альтернативный способ для распознавания штрихкода в программе 1С: Документооборот ред. 2 с помощью утилиты Zbar, которая распознает в том числе и в формате Code 128 (один из стандартных штрихкодов кодирования документов, например, «Управление торговлей» ред. 11), а также с возможностью поэтапно проследить все действия от распознавания до прикрепления к документу или простой загрузки в каталоги файлов в базе 1С.

5 стартмани

How base64 encoding works?

Base64 encode example A.

× Let’s begin with a string «Base64»

B a s e 6 4

× Hexadecimal representation:

42 61 73 65 36 34

× Binary representation: Binary converter

01000010 01100001 01110011 01100101 00110110 00110100

× Now we need to split the result in groups of 6 bits.

010000 100110 000101 110011 011001 010011 011000 110100

× Next, convert the groups of 6 bits into decimal representation.

16 38 5 51 25 19 24 52

× Now we can use the to convert the decimal values into base64 equivalent.

Q m F z Z T Y

Base64 encode example B.

× We will split the string «Base64» into two smaller strings: «Ba» and «se64» and encode it into Base64.So, we have:

B a

× Hexadecimal representation:

42 61

× Binary representation:

01000010 01100001

× We can split it in two groups of 6 bits. But the last group is only 4 bits long,so we need to add two extra bits of ‘0’ and remember it by putting a ‘=’ at the end.

010000 100110 000100

× In decimal:

16 38 4

× Base64 encoded equivalent:

Q m E =

Base64 encode example C.

s e 6 4

× Hexadecimal representation:

73 65 36 34

× Binary representation:

01110011 01100101 00110110 00110100

× Splitted in groups of 6 bits. The last group contains only two bits.Because of this we need to add four extra bits of ‘0’ and put two ‘=’ at the end.

011100 110110 010100 110110 001101 000000

× Base64 encoded string will be:

c 2 U 2 N A==

About

  • Character set: Our website uses the UTF-8 character set, so your input data is transmitted in that format. Change this option if you want to convert the data to another character set before encoding. Note that in case of text data, the encoding scheme does not contain the character set, so you may have to specify the appropriate set during the decoding process. As for files, the binary option is the default, which will omit any conversion; this option is required for everything except plain text documents.
  • Newline separator: Unix and Windows systems use different line break characters, so prior to encoding either variant will be replaced within your data by the selected option. For the files section, this is partially irrelevant since files already contain the corresponding separators, but you can define which one to use for the «encode each line separately» and «split lines into chunks» functions.
  • Encode each line separately: Even newline characters are converted to their Base64 encoded forms. Use this option if you want to encode multiple independent data entries separated with line breaks. (*)
  • Split lines into chunks: The encoded data will become a continuous text without any whitespaces, so check this option if you want to break it up into multiple lines. The applied character limit is defined in the MIME (RFC 2045) specification, which states that the encoded lines must be no more than 76 characters long. (*)
  • Perform URL-safe encoding: Using standard Base64 in URLs requires encoding of «+», «/» and «=» characters into their percent-encoded form, which makes the string unnecessarily longer. Enable this option to encode into an URL- and filename- friendly Base64 variant (RFC 4648 / Base64URL) where the «+» and «/» characters are respectively replaced by «-» and «_», as well as the padding «=» signs are omitted.
  • Live mode: When you turn on this option the entered data is encoded immediately with your browser’s built-in JavaScript functions, without sending any information to our servers. Currently this mode supports only the UTF-8 character set.

(*) These options cannot be enabled simultaneously since the resulting output would not be valid for the majority of applications.Safe and secureCompletely freeDetails of the Base64 encodingDesignExampleMan is distinguished, not only by his reason, but …ManTWFu

Text content M a n
ASCII 77 97 110
Bit pattern 1 1 1 1 1 1 1 1 1 1 1 1
Index 19 22 5 46
Base64-encoded T W F u

расшифровка base64_decode описание

  1. Скачать
  1. base64_decode — это функция, которая противоположна base64_encode . Те данные, зашифрованные base64_encode можно декодировать с помощью base64_decode

    base64_decode ( string $var ) : string|false
    Что означает выше приведенная информация спецификации base64_decode!?

    base64_decode — написание функции base64_decode

    «string» — передаваемое значение в функцию должно иметь тип данных string

    bool — тип данных bool

    $var — переменная с данными

    $strict — Если параметр strict задан как TRUE, функция base64_decode() вернет FALSE в случае, если входные данные содержат символы, не входящие в алфавит base64. В противном случае такие символы будут отброшены.

    «: string|false» — возвращает тип данных строку, либо false.

    Для того, что продемонстрировать, как работает данное декодирование base64_decode

    Мы должны какие-то данные зашифровать например «Hello world!»

    Hello world! = SGVsbG8gd29ybGQh

    Полученные данные помещаем в переменную: :

    $example = ‘SGVsbG8gd29ybGQh ‘;

    Применяем к данной строке расшифровка base64_decode :

    base64_decode ($example);

    Выводим с помощью echo

    echo base64_decode ($example);

    Hello world!

    Как вы наверное знаете, что некоторые функции категорически не работают с кириллицей в utf-8 по причине, которую мы вот тут разбирали.

    Для того, чтобы проверить работу функции base64_decode с кириллицей utf-8, нам опять понадобится сперва зашифровать «Привет мир!» :

    Привет мир! = 0J/RgNC40LLQtdGCINC80LjRgCE=

    Полученные данные помещаем в переменную:

    $example = ‘0J/RgNC40LLQtdGCINC80LjRgCE=’;

    Выводим :

    echo base64_decode ($example);

    Привет мир!

  2. Как расшифровать данные с помощью base64_decode?

    Чтобы получить строку, которая закодирована ранее, для вашего удобства сделаю два поля —

    декодировать.

    На данной в поле введите данные и нажмите отправить.

    Скопируйте результат.

    Вставьте скопированную строку в поле ниже и нажмите Декодировать base64_decode.

Php код для шифрования текста с помощью функции base64_decode

Style:

.kod {

display: block;

background: #fbfbfb;

margin: 10px 0 10px 0;

padding: 20px;

border: 1px solid #a7a7a7;

font-size: 14px;

word-break: break-word;

}

Php:

<?

if($_POST) { $result = ‘<a name=»result»></a><red> Ваш зашифрованный текст</red> : <div class=»kod»>’ . base64_decode (strip_tags($_POST)).'</div>’ ;}

?>

Html:

<? echo $result; ?>

<form method=»post» action=»#result»>

<textarea name=»example»></textarea>

<input name=»example1″ type=»submit» class=»width_100pro padding_10_0″>

</form>

Пользуйтесь на здоровье! Не забудьте сказать

Название скрипта :Расшифровка base64_decode
Ссылка на скачивание : Все скрипты на

Теги :

API reference

Strings are represented as a pointer and a length; they are not
zero-terminated. This was a conscious design decision. In the decoding step,
relying on zero-termination would make no sense since the output could contain
legitimate zero bytes. In the encoding step, returning the length saves the
overhead of calling on the output. If you insist on the trailing
zero, you can easily add it yourself at the given offset.

Flags

Some API calls take a argument.
That argument can be used to force the use of a specific codec, even if that codec is a no-op in the current build.
Mainly there for testing purposes, this is also useful on ARM where the only way to do runtime NEON detection is to ask the OS if it’s available.
The following constants can be used:

Set to for the default behavior, which is runtime feature detection on x86, a compile-time fixed codec on ARM, and the plain codec on other platforms.

Encoding

base64_encode

void base64_encode
    ( const char  *src
    , size_t       srclen
    , char        *out
    , size_t      *outlen
    , int          flags
    ) ;

Wrapper function to encode a plain string of given length.
Output is written to without trailing zero.
Output length in bytes is written to .
The buffer in has been allocated by the caller and is at least 4/3 the size of the input.

base64_stream_encode_init

void base64_stream_encode_init
    ( struct base64_state  *state
    , int                   flags
    ) ;

Call this before calling to init the state.

base64_stream_encode

void base64_stream_encode
    ( struct base64_state  *state
    , const char           *src
    , size_t                srclen
    , char                 *out
    , size_t               *outlen
    ) ;

Encodes the block of data of given length at , into the buffer at .
Caller is responsible for allocating a large enough out-buffer; it must be at least 4/3 the size of the in-buffer, but take some margin.
Places the number of new bytes written into (which is set to zero when the function starts).
Does not zero-terminate or finalize the output.

base64_stream_encode_final

void base64_stream_encode_final
    ( struct base64_state  *state
    , char                 *out
    , size_t               *outlen
    ) ;

Finalizes the output begun by previous calls to .
Adds the required end-of-stream markers if appropriate.
is modified and will contain the number of new bytes written at (which will quite often be zero).

Decoding

base64_decode

int base64_decode
    ( const char  *src
    , size_t       srclen
    , char        *out
    , size_t      *outlen
    , int          flags
    ) ;

Wrapper function to decode a plain string of given length.
Output is written to without trailing zero. Output length in bytes is written to .
The buffer in has been allocated by the caller and is at least 3/4 the size of the input.
Returns for success, and when a decode error has occured due to invalid input.
Returns if the chosen codec is not included in the current build.

base64_stream_decode_init

void base64_stream_decode_init
    ( struct base64_state  *state
    , int                   flags
    ) ;

Call this before calling to init the state.

base64_stream_decode

int base64_stream_decode
    ( struct base64_state  *state
    , const char           *src
    , size_t                srclen
    , char                 *out
    , size_t               *outlen
    ) ;

Decodes the block of data of given length at , into the buffer at .
Caller is responsible for allocating a large enough out-buffer; it must be at least 3/4 the size of the in-buffer, but take some margin.
Places the number of new bytes written into (which is set to zero when the function starts).
Does not zero-terminate the output.
Returns 1 if all is well, and 0 if a decoding error was found, such as an invalid character.
Returns -1 if the chosen codec is not included in the current build.
Used by the test harness to check whether a codec is available for testing.

Преобразование строки в массив байтов

Иногда нам нужно преобразовать Строку в байт[] . Самый простой способ сделать это-использовать метод String getBytes() :

String originalInput = "test input";
byte[] result = originalInput.getBytes();

assertEquals(originalInput.length(), result.length);
String originalInput = "test input";
byte[] result = originalInput.getBytes(StandardCharsets.UTF_16);

assertTrue(originalInput.length() < result.length);

Если наша строка Base64 закодирована, мы можем использовать декодер Base64 |:

String originalInput = "dGVzdCBpbnB1dA==";
byte[] result = Base64.getDecoder().decode(originalInput);

assertEquals("test input", new String(result));

Мы также можем использовать DatatypeConverter parseBase64Binary() метод :

String originalInput = "dGVzdCBpbnB1dA==";
byte[] result = DatatypeConverter.parseBase64Binary(originalInput);

assertEquals("test input", new String(result));

Наконец, мы можем преобразовать шестнадцатеричную строку в байт[] с помощью метода DatatypeConverter :

String originalInput = "7465737420696E707574";
byte[] result = DatatypeConverter.parseHexBinary(originalInput);

assertEquals("test input", new String(result));

Алгоритм работы

Изначально на вход поступает массив байт, каждый байт — это число от до 255, то есть максимальное количество бит в числе равно восьми (255 в двоичной системе счисления это 11111111). Необходимо взять 3 байта, это 24 бита, которые разбивают на 4 части – по 6 бит. Число из 6 бит (в десятичной системе) и будет представлять из себя очередной индекс в таблице для получения символа кодирования (6 бит – в двоичном виде 111111, в десятичном виде это число 63). Если размер исходного массива не кратен 3, тогда итоговую строку следует дополнить символом до размера кратного 3.

В качестве примера, продемонстрирую как происходит кодирование строки «». Для начала, необходимо получить массив байт, это будет 4 десятичных числа 100, 101, 109, 111. В двоичном виде это значения 1100100, 1100101, 1101101, 1101111.

Дополним количество бит в числах до 8, и разобьём на группы по 6 бит. Получим значения 011001, 000110, 010101, 101101, 011011, 110000. Переведём в десятичную систему счисления, получим числа 25, 6, 21, 45, 27, 48. Взяв символы из таблицы Base64 символов по данным индексам, получим строку . Во входящем массиве байт было 4 числа. Четыре не кратно трём, остаток от деления на три будет 1. Если остаток 1, то нужно дополнить двумя символами , если остаток будет 2, то дополнить одним символом . В данном случае дополнив имеющуюся строку .

Дополнив строку, получаем результат . Это и есть Base64 строка, полученная из строки «».

Наглядно процесс кодирования можно увидеть ниже:

Декодирование информации из Base64 строки представляет из себя обратный процесс. Нам необходимо разбить строку по 4 символа, получить их значения из таблицы символов Base64, затем полученную группу из 24 бит необходимо разбить на 3 части – получится 3 значения по 8 бит, которые мы помещаем в массив байт. Повторять данный процесс необходимо до конца имеющейся строки. Символ не будет участвовать в процессе, он будет только показывать, какое количество бит необходимо взять из конца строки.

Демонстрацию процесса декодирования можно увидеть ниже:

base64 [OPTION] [INFILE] [OUTFILE]

You can use different types of options with base64 command. Data can be taken from any file or standard input while encoding or decoding. After encode or decode, you can send the output in a file or print the output in the terminal.

Options:

-e or –encode

This option is used to encode any data from standard input or from any file. It is the default option.

-d or –decode

This option is used to decode any encoded data from standard input or from any file.

-n or –noerrcheck

By default, base64 checks error while decoding any data. You can use –n or –noerrcheck option to ignore checking at the time of decoding.

-u or –help

This option is used to get information about the usage of this command.

-i, –ignore-garbage

This option is used to ignore non-alphabet character while decoding.

–copyright

It is used to get copyright information.

–version

It is used to get the version information.

How you use the base64 command in Linux is shown in this tutorial by using some examples.

Example#1: Encoding text data

You can encode any text data by using base64 in the command line. When you want to encode any data using base64 then using -e or –encode option is optional. So, if you don’t mention any option with base64 then it will work for encoding. The following command will encode the data, ‘linuxhint.com’ and print the encoded data as output.

$ echo  ‘linuxhint.com’ | base64

Output:

Example#2: Decoding text data

The following command will decode the encoded text, ‘bGludXhoaW50LmNvbQ==‘ and print the original text as output.

$ echo ‘bGludXhoaW50LmNvbQo=’ | base64 —decode

Output:

Example#3: Encoding text file

Create a text file named, ‘sample.txt’ with the following text that will be encoded by using base64.

Sample.txt
PHP uses base64_encode and base64_decode for data encoding and decoding

You can print the encoded text in the command line or store the encoded text into another file. The following command will encode the content of the sample.txt file and print the encoded text in the terminal.

$ base64 sample.txt

Output:

The following commands will encode the content of the sample.txt file and save the encoded text into the encodedData.txt file.

$ base64 sample.txt > encodedData.txt
$ cat encodedData.txt

Output:

Example#4: Decoding text file

The following command will decode the content of the encodedData.txt file and print the output in the terminal

$ base64 -d encodedData.txt

Output:

The following commands will decode the content of the encodedData.txt file and store the decoded content into the file, originalData.txt.

$ base64 —decode encodedData.txt > originalData.txt
$ cat originalData.txt

Output:

Example#5: Encoding any user-defined text

Create a bash file named encode_user_data.sh with the following code. The following script will take any text data as input, encode the text by using base64 and print the encoded text as output.

#!/bin/bashecho «Enter Some text to encode»read textetext=`echo -n $text | base64`echo «Encoded text is : $etext»

Run the script.

$ base  encode_user_data.sh

Output:

Example#6: Checking user validity by decoding text

Create a bash file named checkValidity.sh and add the following code. In this example, a secret text is taken from the user.  A predefined encoded text is decoded by base64  and compared with the user input. If both values are equal then the output will be ‘You are authenticated’ otherwise the output will be ‘You are not authenticated’. Using this simple decoding code, normal validation can be done very easily.

#!/bin/bashecho «Type your secret code»read secretotext=`echo ‘Nzc3Nzk5Cg==’ | base64 —decode`if $secret == $otext ; thenecho «You are authenticated»elseecho «You are not authenticated»fi

Run the script.

$ bash  checkValidity.sh

Output:

Conclusion:

For any sensitive data like password or any confidential data, encoding and decoding system is not suitable at all. You must use encryption and decryption system for securing these type of data.