Base64 decode windows cmd

Unlock the potential of Base64 encoding in Windows CMD with certutil. Transform binary data to text seamlessly. Your guide to efficient data handling.

What is Base64?

Base64 is a binary-to-text encoding scheme that converts binary data into an ASCII string format, facilitating safe data transmission and storage. This encoding method represents binary information using a set of 64 characters, consisting of letters, numbers, and symbols. Base64 is widely employed in various applications, including email attachments and encoding binary files for inclusion in text-based formats like XML and JSON. It serves as a versatile solution for ensuring data integrity and compatibility across different systems and platforms.

What is Shell?

A shell is a command-line interface (CLI) software that allows users to interact with an operating system. It evaluates user input and forwards it to the operating system for execution. The term “shell” is more broad and can refer to any CLI, whether for Unix-like or Windows-based systems. Shells can have features such as scripting, variables, and the ability to automate activities via command sequences.

What is CMD?

The command-line interpreter application present in Windows operating systems is known as CMD, or Command Prompt. It provides a text-based interface via which users may interact with the system, run applications, and accomplish various tasks. CMD is a rudimentary command-line interface in comparison to more current command-line interfaces, with a limited selection of commands and features.

Base64 Encoding and Decoding in CMD

In CMD, you can use the certutil command-line tool to perform Base64 encoding and decoding. Although certutil is primarily used for managing certificates, it also includes the -encode and -decode operations, which can be used on any file, not just certificates.

Here is the syntax:

certutil <method> <inputFile> <outputFile>

This command is used to encode or decode a file using Base64 encoding or decoding with the certutil command-line tool in Windows. <method> represents either the -encode or -decode parameter, <inputFile> represents the name of the input file, and <outputFile> represents the name of the output file. The result of the encoding or decoding operation will be saved to the file specified by <outputFile>.

For example, if you want to encode a file named input.txt using Base64 encoding, you can use the following command:

certutil -encode input.txt output.b64

This will create an output.b64 file that contains the Base64 encoded contents of the input.txt file.

If you want to decode a Base64 encoded file named input.b64, you can use the following command:

certutil -decode input.b64 output.txt

This will create an output.txt file that contains the decoded contents of the input.b64 file.

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

1 2013-08-20 08:46:28 (изменено: VitAliS, 2013-08-20 08:47:19)

  • VitAliS
  • Разработчик
  • Неактивен
  • Рейтинг : [0|0]

Тема: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Может быть было где-то здесь уже, но по  крайней мере я не нашел.

Иногда нужно файл закодировать в текстовый вид при помощи кодировки base64, или наоборот раскодировать.

Раньше для этого я использовал утилиту base64.exe или Total Commander
Но проблема в том, что это сторонние инструменты.

Оказывается можно обойтись средствами ОС.
Есть в составе ОС Windows утилита certutil.exe предназначенная для работы с сертификатами.
Так вот, при помощи этой утилиты и можно кодировать/декодировать в/из base64 любые файлы. Для этого используются ключи -encode и -decode соответственно.

Пример:
Имеем текстовый файл file.txt с текстом: «Hello, world!»

certutil.exe -encode file.txt file.b64

на выходе имеем файл file.b64:


-----BEGIN CERTIFICATE-----
SABlAGwAbABvACwAIAB3AG8AcgBsAGQAIQANAAoA
-----END CERTIFICATE-----

В общем как-то так
Век живи, век учись

2 Ответ от Serge Yolkin 2013-08-20 14:03:25 (изменено: Serge Yolkin, 2013-08-21 00:08:54)

  • Serge Yolkin
  • Разработчик
  • Неактивен
  • Рейтинг : [1|0]

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Ага. Она ещё и хэш SHA1 считать умеет…

P.S. И не только SHA1, ещё и SHA256, SHA384, SHA512, MD2, MD4, MD5, но параметр HashAlgorithm обязательно должен быть в ВЕРХНЕМ РЕГИСТРЕ.

3 Ответ от Flasher 2013-08-20 14:31:03

  • Flasher
  • Заблокирован
  • Неактивен

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

VitAliS пишет:

Есть в составе ОС Windows утилита certutil.exe

На XP SP3 по умолчанию нет.

VitAliS пишет:

или Total Commander
Но проблема в том, что это сторонние инструменты.

Сторонние, но использовать тот же ТС только для этих целей (или как у некоторых — для FTP) — какое-то сомнительное по КПД занятие.

base64.exe, кстати, есть в двух вариантах. Плюс есть скриптовые решения. Я же периодически обращаюсь к UUDeview.

4 Ответ от UNDYING 2013-08-21 05:58:03

  • UNDYING
  • Участник
  • Неактивен
  • Рейтинг : [2|0]

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Flasher пишет:

На XP SP3 по умолчанию нет.

Есть в Windows 7 Pro, Server 2003 R2 Standard, Server 2008 R2 Standard, Server 2008 R2 Foundation;
По идее должна быть в Vista, 8, Server 2008/2012 Standart;
И всё-таки XP уже является устаревшей и неподдерживаемой ОС.

Минусы скриптовых решений — невысокая скорость работы. Бывают ситуации из разряда «обработать mbox/maildir объёмом в 2-3 ГБайт, возможно даже не один» — натравил VBS’ник и идешь скрашивать ожидание к девушкам, в соседнюю комнатушку. Сколько памяти «скушает» такой VBS, если «слепить» из него аналог ripmime — ужас!

5 Ответ от alexii 2013-08-21 09:14:29

  • alexii
  • Разработчик
  • Неактивен

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Да ну .

Минусы скриптовых решений — невысокая скорость работы.

Да бросьте. Не ручками же считаем.

6 Ответ от Flasher 2013-08-21 12:28:13

  • Flasher
  • Заблокирован
  • Неактивен

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

UNDYING пишет:

И всё-таки XP уже является устаревшей и неподдерживаемой ОС.

Устаревшая, но активно используемая, а значит пренебрегать ей как минимум нелогично. Поддержка заканчивается только 8 апреля следующего года. Я же вообще живу без апдейтов и не имею проблем.

UNDYING пишет:

Бывают ситуации из разряда «обработать mbox/maildir объёмом в 2-3 ГБайт, возможно даже не один» — натравил VBS’ник и идешь скрашивать ожидание к девушкам, в соседнюю комнатушку.

Сперва предлагаю опробовать. И раз речь о скриптах, то и цитату следовало бы приводить только с ними и без утилит, которые тоже в моих скриптах активно участвуют. Одно другому не мешает.

7 Ответ от VitAliS 2013-08-22 04:30:37

  • VitAliS
  • Разработчик
  • Неактивен
  • Рейтинг : [0|0]

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Flasher пишет:

На XP SP3 по умолчанию нет.

Согласен. Маленько ошибся.
Но эта утилита входит в Administrator Kit, который у меня всегда априори установлен, поэтому я и посчитал ее частью ОС

Flasher пишет:

но использовать тот же ТС только для этих целей (или как у некоторых — для FTP) — какое-то сомнительное по КПД занятие

Ну, вообще TC использовался не только для этих целей, просто в нем есть этот функционал

8 Ответ от Rumata 2013-08-25 09:45:26

  • Rumata
  • Разработчик
  • Неактивен

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Вообще утилита кривоватая какая-то:
— SHA1 пустого файла считать не умеет
— SHA1 выводит дамп а не строкой. Сравните (sha1sum — утилита с аналогичным функционалом в unix)


echo.>file1
sha1sum file1
certutil -hashfile file1

— отсутствует система в использовании параметров командной строки: то требует выходной файл, то не требует


CertUtil [Options] -hashfile InFile
CertUtil [Options] -encode InFile OutFile

— обязательность выходного файла напрягает. Странно, что они не сделали обычный вывод в STDOUT.
— избыточные сообщения в случае успешного выполнения команды и бессмысленные сообщения об ошибках.
— «пугливая» программа — боится перезаписать существующий файл.

( 2 * b ) || ! ( 2 * b )

9 Ответ от Rumata 2013-08-25 09:46:03

  • Rumata
  • Разработчик
  • Неактивен

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Serge Yolkin пишет:

Ага. Она ещё и хэш SHA1 считать умеет…

P.S. И не только SHA1, ещё и SHA256, SHA384, SHA512, MD2, MD4, MD5, но параметр HashAlgorithm обязательно должен быть в ВЕРХНЕМ РЕГИСТРЕ.

Покажите, пожалуйста, примеры вычислений сумм SHA256, SHA384, SHA512, MD2, MD4, MD5.

( 2 * b ) || ! ( 2 * b )

10 Ответ от Serge Yolkin 2013-08-26 22:07:24

  • Serge Yolkin
  • Разработчик
  • Неактивен
  • Рейтинг : [1|0]

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Rumata, для Вас — всегда пожалуйста

11 Ответ от Rumata 2013-08-26 23:44:25

  • Rumata
  • Разработчик
  • Неактивен

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Serge Yolkin
Я видел эту тему и честно пытался выполнить ее как написано в справке. Вот результат:


c:\tmp\zzz>dir /b *
hash2name.wsf

c:\tmp\zzz>echo.>test.txt

c:\tmp\zzz>wscript //job:run hash2name.wsf /MD5 test.txt

c:\tmp\zzz>dir /b *
hash2name.wsf
test.txt

Я проанализировал Ваш скрипт. По сути он — обертка вокруг команды:


certutil -hashfile test.txt MD5

Но эта команда у меня дает ошибку:


c:\tmp\zzz>CertUtil -hashfile "C:\tmp\zzz\test.txt" MD5
Expected no more than 1 args, received 2
CertUtil: Too many arguments

Usage:
  CertUtil [Options] -hashfile InFile
  Generate and display cryptographic hash over a file

Options:
  -gmt              -- Display times as GMT
  -seconds          -- Display times with seconds and milliseconds
  -v                -- Verbose operation
  -privatekey       -- Display private key data

CertUtil -?              -- Display a verb list (command list)
CertUtil -hashfile -?    -- Display help text for the "hashfile" verb
CertUtil -v -?           -- Display all help text for all verbs

Скорее всего мы пользуемся разными версиями программы. В интернете я встречал упоминание о другой версии. Вот моя:

File version: 6.0.6002.18005
Size: 781 KB

А какая у Вас?

( 2 * b ) || ! ( 2 * b )

12 Ответ от Serge Yolkin 2013-08-28 03:11:58

  • Serge Yolkin
  • Разработчик
  • Неактивен
  • Рейтинг : [1|0]

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Судя по формату (и по аналогии с другими продуктами МС) это номер версии ОС, а не файла. У Вас — WinXP. У меня поблизости XP нет… Писал и отлаживал скрипт на 7 (6.2.хххх…), а вчера поставил 8.1 (6.3.9431.0).

13 Ответ от alexii 2013-08-28 03:54:19

  • alexii
  • Разработчик
  • Неактивен

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Serge Yolkin, Windows XP:

??????????????????????????? Версия файла ???????????????????????????
? Полная версия:         5.2.3790.3959                             ?
? Язык:                  Русский                                   ?
? Описание:              CertUtil.exe                              ?
? Копирайт:              рпорация Майкрософт. Все права защищены.  ?
? Архитектура:           I386                                      ?
????????????????????????????????????????????????????????????????????
? Комментарий:                                                     ?
? Компания:              Microsoft Corporation                     ?
? Версия файла:          .2.3790.3959 (srv03_sp2_rtm.070216-1710)  ?
? Внутреннее имя:        CertUtil.exe                              ?
? Торговая марка:                                                  ?
? Оригинальное имя:      CertUtil.exe                              ?
? Частная сборка:                                                  ?
? Продукт:               Операционная система Microsoft® Windows®  ?
? Версия продукта:       5.2.3790.3959                             ?
? Специальная сборка:                                              ?
????????????????????????????????????????????????????????????????????
?                             { o Да }                             ?
????????????????????????????????????????????????????????????????????

14 Ответ от Rumata 2013-08-28 08:49:01

  • Rumata
  • Разработчик
  • Неактивен

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Serge Yolkin пишет:

Судя по формату (и по аналогии с другими продуктами МС) это номер версии ОС, а не файла. У Вас — WinXP. У меня поблизости XP нет… Писал и отлаживал скрипт на 7 (6.2.хххх…), а вчера поставил 8.1 (6.3.9431.0).

Нет. У меня виста.

( 2 * b ) || ! ( 2 * b )

15 Ответ от Serge Yolkin 2013-08-28 11:26:45

  • Serge Yolkin
  • Разработчик
  • Неактивен
  • Рейтинг : [1|0]

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

Чёрт! Про Висту я забыл… Хотя стояла когда-то. Считал обратным отсчётом и Висту пропустил, получилась XP. Прошу прощения.

16 Ответ от greg zakharov 2013-09-02 22:28:18

  • greg zakharov
  • Гость

Re: CMD/BAT: Кодирование/декодирование base64 средствами ОС

certutil.exe, на сколько помню, ставится с VS. Последней не пользуюсь (считаю vim лучшей IDE), поэтому утверждать ничего не буду. На счет кодирования. Учитывая, что PowerShell в Win7 имеется по умолчанию, то

[Convert]::ToBase64String((gc $file -enc byte))

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

Excerpt

If you want to encode or decode a string to Base64 from your command line, there are some simple steps to follow. Here are some practical ways to achieve this on different operating systems and shells.

Encoding String to Base64

Encoding in Windows

  1. Open your command prompt.

  2. Type the following command, replacing input_file and output_file with your desired inputs and outputs:

    1certutil -encode input_file output_file
    

    For example, to encode a string, you can use the following command:

    1echo -n "IToolkit" | certutil -encode -
    

Encoding in Linux

  1. Open your terminal.

  2. Type the following command, replacing input_file and output_file with your desired inputs and outputs:

    1base64 input_file -w 0 > output_file
    

    For example, to encode a string, you can use the following command:

    1echo -n "IToolkit" | base64
    

Encoding in Mac

  1. Open your terminal.

  2. Type the following command, replacing input_file and output_file with your desired inputs and outputs:

    1base64 -i input_file -o output_file
    

    For example, to encode a string, you can use the following command:

    1echo -n "IToolkit" | base64
    

Encoding in Shell

  1. Open your shell.

  2. Type the following command, replacing input_file and output_file with your desired inputs and outputs:

    1openssl enc -base64 -in input_file -out output_file
    

    For example, to encode a string, you can use the following command:

    1echo -n "IToolkit" | openssl enc -base64
    

The free Base64 Encode verification tool is as follows:

Decoding Base64 to String

Decoding in Windows

  1. Open your command prompt.

  2. Type the following command, replacing input_file and output_file with your desired inputs and outputs:

    1certutil -decode input_file output_file
    

    For example, to decode a string, you can use the following command:

    1echo -n "SVRvb2xraXQ=" | certutil -decodehex -
    

Decoding in Linux

  1. Open your terminal.

  2. Type the following command, replacing input_file and output_file with your desired inputs and outputs:

    1base64 -d input_file -w 0 > output_file
    

    For example, to decode a string, you can use the following command:

    1echo -n "SVRvb2xraXQ=" | base64 -d
    

Decoding in Mac

  1. Open your terminal.

  2. Type the following command, replacing input_file and output_file with your desired inputs and outputs:

    1base64 -D -i input_file -o output_file
    

    For example, to decode a string, you can use the following command:

    1echo -n "SVRvb2xraXQ=" | base64 -D
    

Decoding in Shell

  1. Open your shell.

  2. Type the following command, replacing input_file and output_file with your desired inputs and outputs:

    1openssl enc -base64 -d -in input_file -out output_file
    

    For example, to decode a string, you can use the following command:

    1echo -n "SVRvb2xraXQ=" | openssl enc -base64 -d
    

The free Base64 Decode verification tool is as follows:

Precautions when Using

  • Be careful with sensitive information; Base64 is not encryption.
  • Always double-check if you typed the correct syntax for your command.
  • Don’t forget to check if the output is correct.

In conclusion, encoding and decoding from Base64 in the command line is a practical skill that is useful in various contexts. By following these simple steps, you can easily encode and decode strings in Base64. Just be sure to follow the noted precautions to avoid any potential issues.

Using base64 to decode some text If you run base64 –decode without a file, you can type text (or copy and paste it), hit return/enter, and then control+d / ctrl+d and it will be decoded.

  1. How do I decode a base64 string in Windows?
  2. How do I decrypt base64?
  3. Can you decode base64?
  4. How do I decode base64 in Python?
  5. How long is a base64 encoded string?
  6. How decode Base64 in SQL?
  7. Is BTOA deprecated?
  8. Does Base64 always end in?
  9. How is base64 encoding done?

How do I decode a base64 string in Windows?

If you are using a Windows system, there is no built-in command to directly perform Base64 encoding and decoding. But you can use the built-in command «certutil -encode/-decode» to indirectly perform Base64 encoding and decoding.

How do I decrypt base64?

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.

Can you decode base64?

Base64 is an encoding, the strings you’ve posted are encoded. You can DECODE the base64 values into bytes (so just a sequence of bits). And from there, you need to know what these bytes represent and what original encoding they were represented in, if you wish to convert them again to a legible format.

How do I decode base64 in Python?

To decode an image using Python, we simply use the base64. decodestring(s) function. Python mentions the following regarding this function: > Decode the string s, which must contain one or more lines of base64 encoded data, and return a string containing the resulting binary data.

How long is a base64 encoded string?

BASE64 characters are 6 bits in length. They are formed by taking a block of three octets to form a 24-bit string, which is converted into four BASE64 characters.

How decode Base64 in SQL?

10 Answers

value( ‘xs:base64Binary(xs:hexBinary(sql:column(«bin»)))’ , ‘VARCHAR(MAX)’ ) Base64Encoding FROM ( SELECT CAST(‘TestData’ AS VARBINARY(MAX)) AS bin ) AS bin_sql_server_temp; — Decode the Base64-encoded string «VGVzdERhdGE=» to get back «TestData» SELECT CAST( CAST(N» AS XML).

Is BTOA deprecated?

If you’re trying to use btoa in Node, you’ll notice that it is deprecated. It’ll suggest you to use the Buffer class instead.

Does Base64 always end in?

A more complete answer is that a base64 encoded string doesn’t always end with a = , it will only end with one or two = if they are required to pad the string out to the proper length.

How is base64 encoding done?

Base64 encoding breaks binary data into 6-bit segments of 3 full bytes and represents those as printable characters in ASCII standard. … Base64 only uses 6 bits (corresponding to 2^6 = 64 characters) to ensure encoded data is printable and humanly readable. None of the special characters available in ASCII are used.

Мне иногда нужно файл закодировать в текстовый вид при помощи кодировки base64, или наоборот раскодировать.
Раньше для этого я использовал утилиту base64.exe или Total Commander
Но проблема в том, что это сторонние инструменты.
Оказывается можно обойтись средствами ОС.
Есть в составе ОС Windows утилита certutil.exe предназначенная для работы с сертификатами.
Так вот, при помощи этой утилиты и можно кодировать/декодировать в/из base64 любые файлы. Для этого используются ключи -encode и -decode соответственно.
Пример:
Имеем текстовый файл file.txt с текстом: «Hello, world!»

certutil.exe -encode file.txt file.b64

на выходе имеем файл file.b64:

-----BEGIN CERTIFICATE-----
SABlAGwAbABvACwAIAB3AG8AcgBsAGQAIQANAAoA
-----END CERTIFICATE-----

ПРИМЕР

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows media player поверх окон
  • Как очистить кэш драйверов windows 7
  • Сетевой принтер ошибка печати windows 10
  • Driverpack solution windows 10 torrent
  • Удаленное управление rdp windows server 2019