Посчитать sha256 файла linux

Как проверить контрольную сумму в 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 », который мы использовали ранее.

Читайте также:  Linux команда проверка наличия папки

Генерация и проверка контрольной суммы SHA256 с помощью суммы sha256

Сначала перейдите в каталог, где хранится образ .iso :

Теперь для генерации контрольной суммы SHA256 введите следующую команду:

Вы получите контрольную сумму SHA256 в окне своего терминала! Легко, не правда ли?

Генерация контрольной суммы SHA256 для UbuntuMATE iso

Если сгенерированная контрольная сумма совпадает с контрольной суммой, представленной на странице загрузки UbuntuMATE, это будет означать — никакие данные не были изменены во время загрузки файла или установки другого значения, загруженный файл не поврежден.

Другие упомянутые инструменты работают аналогично.

Насколько точно это работает?

Если вам интересно, насколько точно эта контрольная сумма обнаруживает поврежденные файлы — если вы удаляете или изменяете хотя бы один символ из любого из текстовых файлов внутри iso-изображения, алгоритм контрольной суммы создаст совершенно другое значение контрольной суммы для этого измененного iso-изображения. И это точно не будет совпадать с контрольной суммой, указанной на странице загрузки.

Вы контрольную сумму?

Одним из предлагаемых шагов при установке Linux является проверка контрольной суммы Linux ISO. Вы всегда выполняете этот шаг или делаете это только тогда, когда что-то не так с установкой?

Было ли это руководство полезным? Если у вас есть какие-либо вопросы, дайте нам знать! А также, если вам нужно подобное руководство для чего-то другого, свяжитесь с нами, мы здесь, чтобы помочь.

Источник

Ubuntu Documentation

The program sha256sum is designed to verify data integrity using the SHA-256 (SHA-2 family with a digest length of 256 bits). SHA-256 hashes used properly can confirm both file integrity and authenticity. SHA-256 serves a similar purpose to a prior algorithm recommended by Ubuntu, MD5, but is less vulnerable to attack.

Comparing hashes makes it possible to detect changes in files that would cause errors. The possibility of changes (errors) is proportional to the size of the file; the possibility of errors increase as the file becomes larger. It is a very good idea to run an SHA-256 hash comparison check when you have a file like an operating system install CD that has to be 100% correct.

In terms of security, cryptographic hashes such as SHA-256 allow for authentication of data obtained from insecure mirrors. The SHA-256 hash must be signed or come from a secure source (such as a HTTPS page or a GPG-signed file) of an organization you trust. See the SHA-256 checksum file for the release you’re using under http://releases.ubuntu.com, such as http://cdimage.ubuntu.com/daily-live/current/SHA256SUMS . You should verify this file using the PGP signature, SHA256SUMS.gpg (such as http://cdimage.ubuntu.com/daily-live/current/SHA256SUMS.gpg ) as described in VerifyIsoHowto.

sha256

sha256sum on Linux

Most Linux distributions come with the sha256sum utility (on Ubuntu it is part of the coreutils package). We are going to use the Ubuntu 9.10 LiveDVD for the following example:

Check the iso file

Ubuntu distributes the SHA-256 checksum hashes in a file called SHA256SUMS in the same directory listing as the download page for your release http://releases.ubuntu.com.

Manual method

First open a terminal and go to the correct directory to check a downloaded iso file:

Then run the following command from within the download directory.

sha256sum should then print out a single line after calculating the hash:

Compare the hash (the alphanumeric string on left) that your machine calculated with the corresponding hash in the SHA256SUMS file.

When both hashes match exactly then the downloaded file is almost certainly intact. If the hashes do not match, then there was a problem with either the download or a problem with the server. You should download the file again from either the same mirror, or from a different mirror if you suspect a server error. If you continuously receive an erroneous file from a server, please be kind and notify the web-master of that mirror so they can investigate the issue.

Читайте также:  Сетевые настройки сканирования windows 10

Semi-automatic method

First download the SHA256SUMS and SHA256SUMS.gpg files to the same directory as the iso. Then run the following commands in a terminal.

The sha256sum line should output a line such as:

If the OK for your file appears, that indicates the hash matches.

Success

Once you have verified the sha256 hash, go ahead and burn the CD. You may want to refer to the BurningIsoHowto page.

Check the CD

So far so good, you have downloaded an iso and verified its integrity. When you boot from the CD you will be given the option to test its integrity. Great, but if the CD is corrupt then you have already wasted time rebooting. You can check the integrity of the CD without rebooting as follows.

Manual method

Check the calculated hash against UbuntuHashes as shown for the iso file above. Depending on your system, you may need to change cdrom to cdrom0 (or even cdrom1 if you have two CD drives).

Success?

Congratulations, you now have a verified Ubuntu CD. Go ahead and use it (or play frisbee with it if you want).

MD5SUM on Mac OS X

This should be updated by someone with access to a Mac.

There are three methods of using md5sumsum on an OS X machine.

Method 1 — The easiest (if MD5 is available) is using the Disk Utility program (Applications > Utilities, or by choosing «Utilities» from the Finder’s «Go» menu). Open Disk Utility and wait for it to gather information about your disks. Go to the directory where you downloaded the Ubuntu disk image, and drag it to Disk Utility’s dock icon (displays on the left-hand side of Disk Utility, underneath your physical drives). Select the iso file. Go to the «Images» menu and select Checksum > MD5. Be sure to choose «MD5» and NOT «MD5 image checksum» or «CRC-32 image checksum», as they are not the same and will give you different results.

Method 2 — If MD5 is not available in the Images > Checksum menu, open a terminal window (Applications > Utilities > Terminal.app). Type «md5», type a space, drag the iso file into the terminal window (appends command with iso file path), and press Enter. The command line returns the hash number.

Method 3 — You can use the Terminal.app and follow the instructions for SHA256SUM on Linux, except use the command «openssl md5» instead of «sha256sum».

Each method returns a hash number. Compare the hash number with the corresponding hash on the UbuntuHashes page. When both hashes match exactly, then the downloaded file is almost certainly intact.

If the hashes do not match, then there was a problem with either the download or a problem with the server. You should download the file again from either the same mirror, or from a different mirror if you suspect a server error. If you continuously receive an erroneous file from a server, please notify the web-master of that mirror so they can investigate the issue.

digest(1) on Solaris

Use the Solaris digest(1) command, specifying the sha256 algorithm with the -a flag. For instance:

Читайте также:  Windows media player 90 градусов

SHA256SUM on Windows

This section also needs to be updated. Is there a sha256sum.exe file distributed by a reliable source? Is there a good GUI?

Windows does not come with sha256sum. You must download one from another location, preferably one that you trust. There are command line utilities that work similarly to the Unix utility; one public domain version with source is available from Fourmilab, but the version available from Cygwin is probably easier to install and update, and Cygwin is also recommended and trusted as the source for many more Unixy utilities. Once installed, Cygwin’s sha256sum behaves exactly as described in SHA256SUM on Linux above.

There are also graphical tools such as the one used in the walk-through provided below.

Download and install winSha256sum, a free and open source hash verification program.
Right-click the ISO file.

Click Send To, then winSha256sum.

Wait for winSha256sum to load and finish the checksum (this may take a significant amount of time depending on your computer’s performance).

Copy the corresponding hash from UbuntuHashes into the bottom text box.

  • Click «Compare»
  • A message box will say «MD5 Check Sums are the same» if the hashes are equal.
  • MD5SUM with «Checksums calculator»

    «Checksums calculator” is an open source GUI application that has been developed to run on Windows, MacOS X and Linux operating systems on 32bit and 64bit architectures while is translated into 19 languages. It gives you the ability to calculate checksums of functions: md5, sha1, sha256, sha384 and sha512. It is very simple to use, after downloaded the zip file with the version that fits on your computer, doesn’t require any installation, just unzip it to any folder of your choice. Once you run it, select the file you want to calculate the checksum, then select the function and click the «Calculate» button. If you want to compare the result, in the field «Original checksum» give the checksum that you downloaded and click the «Compare» button. You can download the application here.

    The program while is running under Windows 7 64bit.

    The program while is running under Snow Leopard 10.6 32bit.

    The program while is running under Ubuntu 10.04 64bit.

    SHA256SUM on CD

    I don’t know if there is now a sha256sum.txt file on the CD.

    To see if your Ubuntu CD was corrupted when burned to the disk, see the CDIntegrityCheck page, or follow the instructions below.

    First mount the CD, if not already mounted:

    Then use the supplied sha256sum file on the CD:

    Be patient, it takes some time. If the command outputs any errors, you’ll know that either the burn was bad or the .iso is corrupt. Please note that this method does not verify authenticity unless the hash of the iso file is compared to the hash at the secure UbuntuHashes page.

    Finally, you can unmount the CD after leaving the folder:

    SHA256SUM of burnt media

    Depending on how you burn your ISOs you can check the burnt media directly. Start by checking that the ISO file is correct:

    Now burn it from Nautilus (right-click, «Write to Disc . «). To check the media directly:

    where «/dev/cdrom» is typically a soft-link to your CD/DVD reader/burner. Note that the checksum matches.

    HowToSHA256SUM (последним исправлял пользователь anthony-geoghegan 2015-12-14 23:05:24)

    The material on this wiki is available under a free license, see Copyright / License for details
    You can contribute to this wiki, see Wiki Guide for details

    Источник

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