- Generating a SHA-256 hash from the Linux command line
- Example
- Output
- Command
- Output
- Linux sha256sum command
- Description
- Syntax
- Options
- Examples
- Related commands
- How to Verify Checksum on Linux [Beginner Guide]
- What is a Checksum?
- How is a Checksum generated?
- How to use checksum to verify file integrity [GUI way]
- Installing GtkHash on Ubuntu
- Using GtkHash
- Verify checksums via Linux command line
- Generating and Verifying SHA256 Checksum with sha256sum
- How accurately does this work?
- Как проверить контрольную сумму в Linux
- Что такое контрольная сумма?
- Как создается контрольная сумма?
- Как использовать контрольную сумму для проверки целостности файла [GUI way]
- Установка GtkHash в Ubuntu
- Использование GtkHash
- Проверьте контрольную сумму в командной строке Linux
- Генерация и проверка контрольной суммы SHA256 с помощью суммы sha256
- Насколько точно это работает?
Generating a SHA-256 hash from the Linux command line
There are plenty of ways to generate a hash on any operating system, but when we talk about generating an almost-unique and fixed size bit hash, then nothing can replace the SHA algorithm.
Before making use of the Linux command to generate a SHA-256 hash, we must know what SHA actually is and what it is good for.
SHA-256 in very simple terms is a cryptographic hash function that has a digest length of 256 bits. It is an algorithm on its own that is able to generate an almostunique and fixed size 256-bit(32-byte) hash. It is also good to know that this algorithm was actually developed by the NSA (National Security Agency).
Now that we know a little bit about what SHA256 means, let’s explore a simple case where we will print a random hash function that is generated using the SHA256 algorithm against a string value.
Example
Consider the example shown below −
If we use the SHA256 algorithm on the above string and convert it into a hash we will get the following output −
This might look very interesting at first, and it surely is.
Now, let’s explore two examples where we will learn how we can generate a SHA256 hash on the linux command line.
In the first case, we will make use of the command shown below −
Output
In the second example, we can remove the openssl and the dgst command and just write the sha256sum command and we will have our hash function generated like above.
Consider the example shown below −
Command
Output
We can use either of these approaches as they more or less have the same effect on your operating system.
Источник
Linux sha256sum command
On Unix-like operating systems, the sha256sum command computes and checks a SHA256 encrypted message digest.
This page describes the GNU/Linux version of sha256sum.
Description
The sha256sum command displays or checks SHA256 (256-bit) checksums. With no FILE, or when FILE is — (a dash), it reads the digest from standard input.
Syntax
Options
-b, —binary | Read in binary mode. |
-c, —check | Read SHA256 sums from the FILEs and check them. |
—tag | Create a BSD-style checksum. |
-t, —text | Read in text mode (default). |
There is no difference between binary and text mode option on GNU system.
The following four options are useful only when verifying checksums:
—quiet | Don’t print OK for each successfully verified file. |
—status | Don’t output anything, status code shows success. |
—strict | Exit non-zero for improperly formatted checksum lines. |
-w, —warn | Warn about improperly formatted checksum lines. |
—help | Display this help and exit. |
—version | Output version information and exit. |
The sums are computed as described in FIPS-180-2. When checking, the input should be a former output of this program. The default mode is to print a line with checksum, a character indicating input mode (‘*’ for binary, space for text), and name for each FILE.
Examples
Running the above command would give the SHA256 checksum of the example.iso file in the current directory. Below is an example of how the output may appear with the full SHA256 checksum followed by the file name.
Related commands
md5sum — Checks the MD5 message digest.
sha224sum — Checks the SHA224 message digest.
sha384sum — Checks the SHA384 message digest.
sha512sum — Checks the SHA512 message digest.
Источник
How to Verify Checksum on Linux [Beginner Guide]
Last updated April 10, 2020 By Munif Tanjim 35 Comments
Brief: This beginner’s guide tells you what a checksum checks, what MD5, SHA-256 and SHA-1 checksums are, why checksums are used and how to verify checksums on Linux.
You’ll learn the following in this tutorial:
What is a Checksum?
A checksum is like the digital fingerprint of a file. In technical terms,
A checksum is a small-sized datum from a block of digital data for the purpose of detecting errors which may have been introduced during its transmission or storage.
So a checksum is a long string of data containing various letters and numbers. You’ll generally find them when downloading files from the web, e.g. Linux distribution images, software packages, etc.
The most common use of checksums is for checking if a downloaded file is corrupted.
For instance, the Ubuntu MATE download page includes an SHA-256 checksum for every image it makes available. So after you’ve downloaded an image, you can generate an SHA-256 checksum for it and verify that the checksum value matches the one listed on the site.
If it doesn’t, that means your downloaded image’s integrity is compromised (maybe it was corrupted during the download process). We will use an Ubuntu MATE “ubuntu-mate-16.10-desktop-amd64.iso” image file for this guide.
How is a Checksum generated?
Each checksum is generated by a checksum algorithm. Without going into the technical details let’s just say it takes a file as input and outputs the checksum value of that file. There are various algorithms for generating checksums. The most popular checksum algorithms are:
- Secure Hash Algorithms and variants (SHA-1, SHA-2 etc.)
- MD5 algorithm
Let’s see how to verify a checksum on Linux.
How to use checksum to verify file integrity [GUI way]
If you’re looking for a graphical solution, you can use GtkHash.
GtkHash is a nifty tool for generating and verifying various checksums. It supports a wide range of checksum algorithms, including SHA, MD5 and others. Here’s a list of supported algorithms:
GtkHash supported Checksum Algorithms
Installing GtkHash on Ubuntu
To install GtkHash on your Ubuntu system, simply run the following command:
That’s it. Then select the checksum algorithms to use:
- Go to Edit >Preferences in the menu.
- Select the ones you’d like to use.
- Hit the Close button.
By default, MD5, SHA-1 and SHA256 are selected.
Using GtkHash
Using it is quite straight-forward.
- Select the file you want to check.
- Get the Checksum value from the website and put it in the Check box.
- Click the Hash button.
- This will generate the checksum values with the algorithms you selected.
- If any one of them matches with the Check box, it will show a small tick sign beside it.
Here’s an example showing GtkHash generating a checksum for the Ubuntu MATE iso image (ubuntu-mate-16.10-desktop-amd64.iso):
GtkHash with UbuntuMATE iso
Verify checksums via Linux command line
Every Linux distribution comes with tools for various checksum algorithms. You can generate and verify checksums with them. The command-line checksum tools are the following:
- MD5 checksum tool is called md5sum
- SHA-1 checksum tool is called sha1sum
- SHA-256 checksum tool is called sha256sum
There are some more available, e.g. sha224sum, sha384sum, etc. All of them use similar command formats. Let’s see an example using sha256sum. We’ll use the same “ubuntu-mate-16.10-desktop-amd64.iso” image file that we used before.
Generating and Verifying SHA256 Checksum with sha256sum
First go to the directory where the .iso image is stored:
Now, to generate the SHA-256 checksum, enter the following command:
You’ll see the SHA-256 checksum in your terminal window! Easy, isn’t it?
Generating SHA256 Checksum for UbuntuMATE iso
If the generated checksum matches the one provided on the Ubuntu MATE download page, that will mean no data was changed while you downloaded the file – in other words, your downloaded file is not corrupted.
The other tools mentioned work similarly.
How accurately does this work?
If you’re wondering how accurately these checksums detect corrupted files – if you delete or change even one character from any one of the text files inside the iso image, the checksum algorithm will generate a totally different value for that changed image. And that will definitely not match the checksum provided on the download page.
Do you checksum?
One of the suggested steps while installing Linux is to verify the checksum of your Linux ISO. Do you always follow this step or do you do it only when something goes wrong with the installation?
Was this guide helpful? If you have any questions, let us know! And if you need a similar guide for something else, reach out to us, we’re here to help.
Like what you read? Please share it with others.
Источник
Как проверить контрольную сумму в Linux
Краткое описание : В этом руководстве для начинающих рассказывается, что такое контрольная сумма, что такое контрольная сумма md5, sha256 или sha-1, почему используется контрольная сумма и как проверить контрольную сумму в Linux.
Что такое контрольная сумма?
Контрольная сумма похожа на цифровой отпечаток файла. В техническом плане
Контрольная сумма представляет собой элемент данных небольшого размера из блока цифровых данных с целью обнаружения ошибок, которые могли быть внесены во время его передачи или хранения.
Ну, контрольная сумма — это длинная строка данных, содержащая различные буквы и цифры. Обычно вы найдете их при загрузке файлов из Интернета, например, дистрибутивного образа Linux, пакетов программного обеспечения и т. Д.
Чаще всего контрольная сумма используется для проверки поврежденного загруженного файла.
Например, страница загрузки Ubuntu MATE содержит контрольную сумму SHA256 для каждого изображения, доступного там. Таким образом, после загрузки изображения вы можете сгенерировать для него контрольную сумму SHA256 и проверить, соответствует ли значение контрольной суммы значению, указанному на сайте.
Если этого не произойдет, это будет означать, что целостность вашего загруженного изображения нарушена (возможно, он был поврежден в процессе загрузки). Для этого руководства мы будем использовать файл образа Ubuntu Mate « ubuntu-mate-16.10-desktop-amd64.iso ».
Как создается контрольная сумма?
Контрольная сумма генерируется алгоритмом контрольной суммы . Не вдаваясь в технические подробности, скажем, что он принимает файл в качестве входных данных и выводит значение контрольной суммы этого файла. Существуют различные алгоритмы генерации контрольной суммы. Наиболее популярные алгоритмы контрольной суммы:
- Безопасные алгоритмы хэширования и варианты (SHA-1, SHA-2 и т. Д.)
- Алгоритм MD5
Давайте посмотрим, как проверить контрольную сумму в Linux.
Подпишитесь на наш канал на YouTube, чтобы узнать больше о Linux видео
Как использовать контрольную сумму для проверки целостности файла [GUI way]
Если вы ищете графическое решение, вы можете использовать GtkHash .
GtkHash — отличный инструмент для генерации и проверки различных контрольных сумм. Он поддерживает широкий спектр алгоритмов контрольной суммы — включая SHA, MD5 и другие. Вот список поддерживаемых алгоритмов:
GtkHash поддерживает алгоритмы контрольной суммы
Установка GtkHash в Ubuntu
Для установки GtkHash в вашей системе Ubuntu просто выполните следующую команду:
Для выбора алгоритмов контрольной суммы использовать :
- Перейдите в меню « Правка» > « Настройки» .
- Выберите те, которые вы хотели бы использовать.
- Нажмите кнопку Закрыть .
По умолчанию — MD5, SHA-1 и SHA256.
Использование GtkHash
Использовать его довольно просто.
- Выберите файл, который вы хотите проверить
- Получите значение контрольной суммы с веб-сайта и установите его в поле «флажок».
- Нажмите кнопку Hash .
- Это сгенерирует значения контрольной суммы с выбранными вами алгоритмами.
- Если какой-либо из них совпадет с флажком, рядом с ним будет отображаться небольшой флажок.
Вот пример, показывающий, как GtkHash генерирует контрольную сумму для ISO-образа UbuntuMATE ( ubuntu-mate-16.10-desktop-amd64.iso ):
GtkHash с UbuntuMATE iso
Проверьте контрольную сумму в командной строке Linux
Каждый дистрибутив Linux поставляется с инструментами для различных алгоритмов контрольной суммы. Вы можете создать и проверить контрольную сумму с ними. Инструменты контрольной суммы командной строки:
- Инструмент контрольной суммы MD5 называется: md5sum
- Инструмент контрольной суммы SHA-1 называется: sha1sum
- Инструмент контрольной суммы SHA-256 называется: sha256sum
Есть еще несколько доступных, например: sha224sum, sha384sum и т. Д. Все они используют похожие форматы команд. Давайте посмотрим пример использования sha256sum . Мы будем использовать тот же файл изображения « ubuntu-mate-16.10-desktop-amd64.iso », который мы использовали ранее.
Генерация и проверка контрольной суммы SHA256 с помощью суммы sha256
Сначала перейдите в каталог, где хранится образ .iso :
Теперь для генерации контрольной суммы SHA256 введите следующую команду:
Вы получите контрольную сумму SHA256 в окне своего терминала! Легко, не правда ли?
Генерация контрольной суммы SHA256 для UbuntuMATE iso
Если сгенерированная контрольная сумма совпадает с контрольной суммой, представленной на странице загрузки UbuntuMATE, это будет означать — никакие данные не были изменены во время загрузки файла или установки другого значения, загруженный файл не поврежден.
Другие упомянутые инструменты работают аналогично.
Насколько точно это работает?
Если вам интересно, насколько точно эта контрольная сумма обнаруживает поврежденные файлы — если вы удаляете или изменяете хотя бы один символ из любого из текстовых файлов внутри iso-изображения, алгоритм контрольной суммы создаст совершенно другое значение контрольной суммы для этого измененного iso-изображения. И это точно не будет совпадать с контрольной суммой, указанной на странице загрузки.
Вы контрольную сумму?
Одним из предлагаемых шагов при установке Linux является проверка контрольной суммы Linux ISO. Вы всегда выполняете этот шаг или делаете это только тогда, когда что-то не так с установкой?
Было ли это руководство полезным? Если у вас есть какие-либо вопросы, дайте нам знать! А также, если вам нужно подобное руководство для чего-то другого, свяжитесь с нами, мы здесь, чтобы помочь.
Источник