Linux jpg to base64

How to base64 encode and decode from command-line

Overiew

In this tutorial, you will learn how to base64 encode and decode from the command-line on Linux. You will also learn what base64 encoding is and why it should never be used to protect data from unauthorized access.

Base64 encoding and decoding data has many use cases. One being is ensuring data integrity when transferring data over the network, while another is storing Secrets in Kubernetes.

After reading this tutorial you will understand how to easily encode files or strings, and then decode them back.

How to base64 encode on Ubuntu, Debian, OSX, and Red Hat

If you are running popular linux distributions, such as Ubuntu, Debian, CentOS, or Red Hat, the base64 command-line tool is typically pre-installed. You should not have to perform any additional steps.

OSX also comes bundled with its own version of base64.

Why Base64 Encode Data

Transferring an ASCII file over the network can cause corruption if not decoded correctly. The reason is ASCII files are string converted to bytes, and when those bytes are decoded incorrectly back to ASCII your data becomes corrupt.

Base64 was introduced as a way to convert your ASCII data into arbitrary bytes, where they could then be transferred as bytes, and decoded correctly back to ASCII.

In short, base64 encoding ensures the integrity of our data when transferred over the network.

Base64 is not Encryption

Encoding files is not encryption and should never be used to secure sensitive data on disk. Rather it is a useful way of transferring or storing large data in the form of a string.

While it may obfuscate that actual data from should surfers, anyone who has access to base64 encoded data can easily decode it.

Base64 Encoding a String

To base64 encode string you can pipe an echo command into the base64 command-line tool. To ensure no extra, hidden characters are added use the -n flag.

Without the -n flag you may capture a hidden characters, like line returns or spaces, which will corrupt your base64 encoding.

Which will output the following

Base64 Encoding a File

To base64 encode a file

This will output a very long, base64 encoded string. You may want to write the stdout to file instead.

Decoding Strings

To decode with base64 you need to use the —decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it.

Using the example encoding shown above, let’s decode it back into its original form.

Provided your encoding was not corrupted the output should be your original string.

Decoding Files

To decode a file with contents that are base64 encoded, you simply provide the path of the file with the —decode flag.

As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.

Conclusion

In this tutorial, you learned how to base64 encode files and strings. This something commonly done to transfer files in such a way that it remains

Источник

How to base64 encode image in linux bash / shell

I’m trying to base64 encode an image in a shell script and put it into variable:

I’ve also tried something like this:

but still with no success.

I want to do something like this:

but still have had no success.

6 Answers 6

You need to use cat to get the contents of the file named ‘DSC_0251.JPG’, rather than the filename itself.

Читайте также:  Linux не могу пробросить порт

However, base64 can read from the file itself:

Encode

On Linux

Single line result:

In variable for HTML :

On OSX

On OSX, the base64 binary is different, and the parameters are different. If you want to use it on OSX, you should remove -w 0 .

Single line result:

In variable for HTML :

Generic OSX/Linux

As Shell Function

As Shell Script

Create base64.sh file with following content:

Make it executable:

Decode

Get you readable data back:

There is a Linux command for that: base64

To assign result to variable use

Base 64 for html:

If you need input from termial, try this

-n option will not input «\n» character to base64 command.

To base64 it and put it in your clipboard:

Not the answer you’re looking for? Browse other questions tagged linux image shell variables base64 or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.8.40416

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How to encode and decode data in base64 and base64URL by using unix commands?

Base64 encode can be achieved by

And Base64 decode can be achieved by

How to achieve Base64URL encode/decode?

Is it just enough to replace «+» with «-» and «/» with » _» ?

When to do the padding «#»(adding/remove «#» to be considered )?

3 Answers 3

This is the same suggestion as @jps but shorter. Also remember that echo by default always adds newline at the end, so when you want to encode it, you must add -n .

Decoding it back with bulit-in bash tools is more complicated as I didn’t find an easy way to pad the string back with ‘=’ so that the length will dividable by 4. Probably can be done with awk but I didn’t dig deep enough. If you have local ruby it becomes trivial:

If you already have a base64 encoded string you just need to replace «+» with «-» and «/» with » _» to get a base64url encoded string. To achieve this, you can use the following command:

echo Some_data_to_be_converted | base64 | sed ‘s/+/-/g; s,/,_,g’

Base64 encoding maps the input bytes (8 bit) to a 6 bit representation. 4 base64 characters can encode 4*6=24 bits, which equals 3 bytes. Whenever the number of bytes in your input can’t be divided by 3, padding is required according to the standard.

The padding character is =

As the = character is used for key-value pairs in URLs, you can’t use it directly for padding if you intend to use the encoded value in an URL. You can either just ommit the padding, because most implementations will still work and just ignore the 2 or 4 unused bits on the end. Or, if the receiver really needs padding, you have to replace the = by it’s URL safe representation %3d .

Источник

How to encode base64 via command line?

Is there a terminal command in Mac OS X which will base64 encode a file or stdin?

17 Answers 17

openssl can do this for you, and it’s all installed with OS X by default; no need to install darwinports.

Without the -in option reads from stdin

Openssl can be used more succinctly:

[ echo -n -> must be used, or encoding will be done including new line character ]

It should be available by default on OS X.

base64 command is available by default on my OS X 10.9.4.

You can use base64 and base64 -D to encode and decode a string in the terminal, or base64 -in file and base64 -D -in file to encode and decode a file.

On macOS I always use:

echo -n «STRING» | base64

-n is to avoid a new line character on the end of the line.

Since Python is provided with OS X by default, you can use it as below:

Or install coreutils via Brew ( brew install coreutils ) which will provide base64 command:

In terms of speed, I would use openssl followed by perl, followed by uuencode. In terms of portability, I would use uuencode followed by Perl followed by openssl (If you care about reusing the code on as many other UNIX like stock platforms as possible). Be careful though because not all UNIX variants support the -m switch (iirc AIX does, HP/UX does, Solaris doesn’t).

Читайте также:  Save locations windows 10

Use the -m switch to uuencode file_in.txt per base64 as specified by RFC1521 and write it to filename.b64 (with filename_when_uudecoded.txt as the default filename when decoded):

You can also pipe it right to the clipboard (at least on mac):

openssl base64 -in [filename] | pbcopy

Python

Python comes preinstalled on all macs nowadays.

In Terminal run python (or ipython).

Of course, both operations can be converted to a oneliner but this way it is more readable.

OpenSSL

Omitting the -out / -output. filename will print to stdout.

base64

Another ootb utility present both in OSX and Ubuntu:

Источник

К вопросу о кроссбраузерных Data URI

BASE64

Поскольку изображения передаются в base64, стоит осветить некоторые, связанные с этой кодировкой, моменты

  • Во первых: base64 понимает только [A-Za-z0-9+/].
    При дешифровке браузерами или ruby либой все прочее символы дропаются.
    Консольный base64 на линуксе их не дропает и выводит ошибку.
  • Во вторых: base64 конвертит каждые 3 исходных байта (в нашем случае, ASCII символы) в 4 ASCII символа.
    Поэтому декодированную CSS строку надо уравновешивать, к примеру, нулями, что бы она правильно себя вела внутри закодированного файла.

Формат секций в JPEG:[заголовок][data]

C jpeg все просто и описано у bolk‘а:

Открываем HEX-редактор:
FF D8 — заголовок JPEG для IE
FF E0 — объявление секции APP0, куда прячется всё до данных изображения,
«;background-color:url(data:image/jpeg;base64,» — это видят остальные браузеры.
Когда IE декодирует эту строку, то получается хлам, который ни на что не влияет
FF D8 — начало JPEG для остальных браузеров
«данные изображения» — это место видят уже все браузеры

Смысл в том, что бы строка в CSS выглядела как:

И дешифровалась в IE как:

А другие ее видели как:

Из-за особенностей base64 надо дополнительно передавать некоторое кол-во символов, что бы строка шифровалась\дешифровалась верно. Они вставляются до и после CSS. Количество просчитывалось и подбиралось опытным путем:
/9j/4AA0;background-image:url(data:image/jpeg;base64;00,

Мой скрипт, который это процесс автоматизирует:

#!/usr/bin/ruby
require ‘base64’
# тут строка ВСЕГДА равна одному значению:
a= «/9j/4AA0;background-image:url(data:image/jpeg;base64;00,»

#Основной файл
b=Base64.encode64( File .open( «#» , ‘r’ )<|f| f.read>)

# перегонка файла обратно в base64
#cat test | base64 | tr -d «\n» > jpeg64.txt
File .open( ‘temp2’ , ‘w’ )<|o| o.write(Base64.encode64( File .open( 'temp' , 'r' )<|f| f.read>))>
# File .delete( ‘temp’ )

c= File .open( ‘temp2’ , ‘r’ )<|f| f.read>.gsub(/\/9j\/4AA0backgroundimageurldataimage\/jpegbase6400/, «/9j/4AA0;background-image:url(data:image/jpeg;base64;00,» ).gsub(/\n/, «» )

File .open( ‘out_jpeg64’ , ‘w’ )<|s| s.write( "#\);» )>
File .delete( ‘temp2’ )
# можно вставлять в css
# cat output64 | tr -d «\n»
# и хорошо поверить mhtml.

* This source code was highlighted with Source Code Highlighter .

70

  • Переместить содержимое General Color Table в Local Color Table
  • Я выбрал второй вариант, это делает base64 строку более читаемой и позволяет конвертировать любые не анимированные gif.

    Более менее стандартный вариант секций GIF: [заголовок][размер][data][00]

    Многие GIF имеют не совсем корректный порядок полей. Например если сделать `convert jpeg gif` то полученный файл адекватно обрабатываться скриптом не будет. Юзайте GIMP.

    Первые 13 байт это та инфа, сокращать которую нельзя. Причем 11 байт является сложно-составным и описывает Global Color Table. Его меняем на 00
    Вырезаем таблицу цветов (от 14 байта и до камента — 21 FE xx, где xx — размер коммента)
    Коммент с css и первыми 13ю байтами.
    Вырезаем таблицу цветов (от 14 байта и до камента — 21 FE xx, где xx — размер коммента)
    ‘Внутренний кoммент’ длиной в 1 символ
    Вырезаем таблицу цветов (от 14 байта и до камента — 21 FE xx, где xx — размер коммента)
    2c 00 00 00 00 — Image descriptor. Его 10й байт является сложно-составным и описывает Local Color Table. Переносим из 11-го байта все что переносится (объявить Local Color Table, сортирована\нет, размер Local color table), подробнее в спецификации формата.
    Вставляем таблицу цветов
    Продолжение Image descriptor

    Смысл в том, что бы строка в CSS выглядела как:

    При том что до всех правок файл выглядел как:

    Мой скрипт для автоматизации процесса:

    #!/usr/bin/ruby
    # CONVERT INCORRECTLY TRANSFER DATA. USE GIMP INSTEAD
    # USE: ./GIF_SCRIPT.RB [GIF_FILE]
    require ‘base64’

    # FUTURE HEADER
    header=orig[0..25]

    # GREP GENERAL COLOR TABLE
    # [26..1565]/6 = 256 BYTE (MAX SIZE OF COLOR TABLE)
    color_table=orig[26..1565][/(.*)21fe/,1]
    if color_table. class == NilClass
    color_table=orig[26..1575][/(.*?)2c0000/,1]
    end

    Читайте также:  Шрифты windows для интерфейсов

    # FOR DEBUGING
    #puts color_table
    #puts color_table.length
    puts «COLORS IN PALLETE: #«

    # GIF IMAGE DATA
    data=orig[/2c0000.*/]

    # SAVE 11 BYTE ‘S INFO AND ADOPT IT FOR LOCAL COLOR TABLE
    eleven=header[20..21].to_i(16).to_s(2)
    local_mix=»10#00#«.to_i(2).to_s(16)

    # 11 BYTE TO ZERO
    header[20..21]=»00″
    # DECLARE LOCAL COLOR TABLE
    data[18..19]=local_mix

    # MAGIC COMMENT
    comment=Base64.decode64(«;background-image:url(data:image/gif;base64;pzd,»).unpack(«H*»).to_s

    # WRITE ALL IN ONE FILE
    var=header+»21fe313030″+comment+header+»21fe013000″+data[0..19]+color_table+data[20..-1]
    File.open(‘ out .gif ‘,’ w ‘)

    # MAKE STRING CSS READEABLE
    c=File.open(‘ temp ‘,’ r ‘)<|f| f.read>.gsub(/backgroundimageurldataimage\/gifbase64pzd/,»;background-image:url(data:image/gif;base64;pzd,»).gsub(/\n/,»»)
    File.delete(‘ temp ‘)

    # JUST PASTE TEXT FROM THIS FILE TO CSS
    File.open(‘ out_gif64 ‘,’ w’)<|s| s.write( "#\);» )>

    * This source code was highlighted with Source Code Highlighter .

    Для анимированного гифа скрипта нет. Я считаю что лучше использовать анимированными CSS sprites.

    Теоретические выкладки:

    • Для каждого кадра делать Local Color Table смысла не имеет, т.к. это увеличит размер.
    • Анимированные гифы с кол-вом цветов 64 могут обрабатываться с включением General Color Table в коммент
    • Application Extension и Comment Extension могут идти подряд, что увеличивает возможный размер x2.
    • На просторах интернета я встретил информацию о том, что в Application Extension фактически 2 блока задают размер.

    21 ff SizeSize ‘NETSCAPE2.0’ SizeSize 01 00 00, где SizeSize — 2 байта отвечающие за размер, а 01 байт отвечающий за infinitive loop.

  • Что, в теории, может предоставить возможность ‘забить’ большее кол-во цветов. Но все-равно меньше 256 (около 230).
  • После gif это тихая гавань. У секций размер не ограничен, у них 4байтные заголовки и их очень удобно искать. Для сравнения, для gif я ломал голову и дебажил скрипт почти весь день, а для png все сделал за час.

    Формат секций в PNG: [размер(4 байта)][data][CRC(4 байта)]

    И тут не обошлось без подводных камней. CRC очень важен для IE, если CRC битый то IE не будет отображать картинку. Всем же остальным глубоко параллельно битый он или нет.

    Многие PNG имеют не совсем верную структуру, во всяком случае, мой скрипт с нми работать не будет, пока не прогнать их через optipng. Помимо оптимизации изображения, эта прога выставит поля в нужном порядке. Также, мною замечено что Photoshop иногда режет поля sRGB и им сохраненные png обрабатываются не всегда.

    CSS будем прятать в секции tEXt

    PNG надо сразу заоптимизировать с помощью optipng, потом нарезать таким образом, что бы tExt был сразу за IHDR.
    В секции tEXt обязательно должен передаваться keyword00, его длина учитывается в общей длине секции. У меня это ‘Comment ‘

    Общий порядок:

    IHDR
    tExt
    Другая служебная информация
    data

    Было:

    Стало:

    Скрипт хорошо комментирован, и в спецификации тоже можно многое почерпнуть

    IE6 не видит прозрачности, иногда это можно исправить с помощью bKGD выставляя нужный Background color.

    После чего запускаем `optipng -fix FILE` что бы исправить CRC секции tEXt

    Мой скрипт для автоматизации процесса:

    #!/usr/bin/ruby
    #
    #. RUN optipng FIRST .
    #
    # USE: ./PNG_SCRIPT.RB [PNG_FILE]
    require ‘base64’
    # OPEN GIF FILE IN HEX
    orig= File .open( «#» , ‘r’ )<|f| f.read.unpack( "H*" )>.to_s

    #sRGB — 73 52 47 42 & -4b (8 characters)
    #srgb_phys=orig[66..171]
    #check for tEXt existence
    if orig[/74455874/]. class == NilClass
    srgb_phys=orig[/(.<8>73524742.*?)49444154/,1][0..-9]
    else
    srgb_phys=orig[/(.<8>73524742.*?)74455874/,1][0..-9]
    end

    #tEXt — 74 45 58 74 –њ–Њ—Б–ї–µ–і–љ–Є–µ 8 –љ–∞–і–Њ –Љ–µ–љ—П—В—М –љ–∞ CRC 00000000
    #text=orig[172..245]
    #text=orig[/(.<8>74455874.*?)49444154/,1][0..-9]

    #IDAT — 49444154
    #data=orig[246..-1]
    data=orig[/.<8>49444154.*/]

    #MAGIC COMMENT
    comment=Base64.decode64( «;background-image:url(data:image/png;base64;pzd,» ).unpack( «H*» ).to_s

    ###### OUTER PNG
    # «00000059» + «74455874» + «436f6d6d656e7400»
    # tEXt_length + ‘tEXt’ + ‘Comment.’
    # «3030» — two zero for base64 balance
    ###### INNER PNG
    # «00000008» + «74455874» + «436f6d6d656e7400» + «00000000»
    # min_tEXt_length + ‘tEXt’ + ‘Comment.’ + blank CRC
    #
    # CRC field one for two PNG ‘s
    # IE can’ t live without it, but others feel indifferently
    var =ihdr+ «00000059» + «74455874» + «436f6d6d656e7400» + «3030» +comment+ihdr+ «00000008» + «74455874» + «436f6d6d656e7400» + «00000000» +srgb_phys+data

    File .open( ‘out.png’ , ‘w’ )

    # CRC FIX
    puts «optipng -fix started. »
    `optipng -fix out .png`
    puts «optipng -fix completed»

    # MAKE STRING CSS READEABLE
    c= File .open( ‘temp’ , ‘r’ )<|f| f.read>.gsub(/backgroundimageurldataimage\/pngbase64pzd/, «;background-image:url(data:image/png;base64;pzd,» ).gsub(/\n/, «» )
    File .delete( ‘temp’ )

    # JUST PASTE TEXT FROM THIS FILE TO CSS
    File .open( ‘out_png64’ , ‘w’ )<|s| s.write( "#\);» )>

    * This source code was highlighted with Source Code Highlighter .

    MHTML

    —_
    Content-Type: text/css;

    */
    html, body <
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    >

    #half_logo <
    /*
    —_
    Content-Location:logo
    Content-Transfer-Encoding:base64
    Content-Type: image/png;*/

    */
    background-image: url(mhtml:http://192.168.1.2/test.css!logo) !ie;
    /*
    —_—
    */

    * This source code was highlighted with Source Code Highlighter .

    Тестировалось в FF 3.6, Opera 10.10, chromium, chrome, IE6-8

    Источник

    Оцените статью