- Ubuntu Documentation
- sha256
- sha256sum on Linux
- Check the iso file
- Manual method
- Semi-automatic method
- Success
- Check the CD
- Manual method
- Success?
- MD5SUM on Mac OS X
- digest(1) on Solaris
- SHA256SUM on Windows
- MD5SUM with «Checksums calculator»
- SHA256SUM on CD
- SHA256SUM of burnt media
- External Links
- Проверка контрольных сумм файлов в Linux
- Зачем нужно выполнять проверку файлов?
- Каким образом это работает?
- Что для этого нужно?
- Как проверить файл в Linux?
- Заключение
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.
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:
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.
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.
External Links
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
Источник
Проверка контрольных сумм файлов в Linux
Очень часто при загрузке файлов с Интернет-ресурсов можно встретить прилагаемую информацию о контрольных суммах этих файлов. Многие пользователи просто не обращают на это внимания, скачивают файл и используют его «как есть». Однако контрольные суммы к соответствующим загружаемым файлам прилагаются не просто так. Это напрямую связано с корректной работой программ (если это исполняемые файлы), а также с безопасностью. В данной статье будет более подробно изложено, почему так важно пользоваться контрольными суммами, а также рассмотрены способы проверки файлов в Linux.
Зачем нужно выполнять проверку файлов?
Контрольные суммы загружаемых файлов позволяют определить, что файл — точная копия того, что хранится на сервере, с которого он был загружен. Структура файлов, особенно таких больших и сложных, как например, ISO-образы может быть повреждена в процессе загрузки (могут удаляться TCP-пакеты из-за некачественной связи и т. п.) и таким образом, загруженные файлы нельзя будет полноценно использовать. Например, не откроется или не распакуется архив.
Есть и другой важный аспект в использовании контрольный сумм — это безопасность. Удалённый сервер, с которого происходит загрузка файлов может быть взломан, а сами загружаемые файлы на нём — изменены. Изменения могут быть не самыми безобидными, как можно понимать. Проверка контрольных сумм может выявить «подлог» ещё до того как загруженный файл будет обработан пользователем, конечно, если эта проверка будет своевременной.
Конечно же злоумышленник, может подменить и сами контрольные суммы, соответственно «испорченным» файлам. Но «лишняя» посторонняя активность на сервере легко может быть замечена и, соответственно, пресечена. Да и для того, чтобы злоумышленнику отредактировать соответствующие публикации на сайтах, предоставляющих загрузки, ему нужно, возможно, преодолевать защиту ещё и самих сайтов, а значит, неоправданно рисковать. Поэтому в подавляющем большинстве случаев такие действия ограничиваются быстрой подменой оригинальных файлов на «контрафактные». Но независимо от того, каким образом были модифицированы загружаемые файлы, всегда следует их проверять, когда предоставляются их контрольные суммы.
Каким образом это работает?
Создание контрольных сумм файлов называется хешированием. Сама же контрольная сумма — это некоторая строка определённой длины, состоящая из последовательности букв и цифр. Нужно заметить, хеширование никоим образом не зашифровывает файл, а контрольная сумма ничего не расшифровывает. Контрольная сумма называется суммой потому, что это результат однонаправленного криптографического «суммирования» — специального алгоритма. А контрольной она называется потому, что её значение (как и длина контрольной строки — обычно 32 символа) будет всегда одним и тем же, если файл никак не изменялся, независимо от того, сколько раз и при каких условиях вычисляется его контрольная сумма. Но стоит над файлом произвести даже самые незначительные изменения (например, вставить один лишний пробел в текстовом файле), как значение контрольной суммы изменится. Таким образом, значение контрольной суммы меняется, если хотя бы один бит файла изменился.
Для создания и проверки контрольный сумм существует два основных метода: MD5 и SHA. Первый считается устаревшим, поскольку для задач шифрования может быть относительно нетрудно взломан. Однако, на работу с контрольными суммами файлов это никак не влияет. Главным же плюсом MD5 является его скорость — она быстрее, чем у SHA, да и вообще других методов шифрования.
Но нельзя не упомянуть также и о том, что в настоящее время всё-таки популярность SHA быстро растёт. В большинстве случаев именно его контрольные суммы публикуются для выкладываемых для загрузки файлов.
SHA имеет несколько версий. Обычно, при публикации это указывается, например: SHA1, SHA2. Это подсказывает пользователю, каким именно инструментом, реализующим одну из версий SHA нужно воспользоваться при проверке. Если же контрольная сумма указана без номера, то это SHA1. Вообще, для проверки целостности файлов оба метода одинаково хороши, выбор зависит от того, контрольная сумма какого метода опубликована для загружаемых файлов.
Что для этого нужно?
Для проверки файлов в системах Linux используются утилиты, которые практически всегда предустановлены в системе. Для этого достаточно вызвать соответствующие команды в командной оболочке.
В качестве проверяемых файлов используются любые файлы, для которых публикуются исходные контрольные суммы, например образы дистрибутивов Ubuntu или Rosa Linux. Далее в примерах будет использоваться образ ROSA.FRESH.PLASMA5.R11.x86_64.uefi.iso.
Как проверить файл в Linux?
Для начала скачаем сам файл, т. е. ISO-образ. На странице загрузки в списке рядом со ссылкой на образ есть также и ссылки на текстовые файлы
содержащие значения соответствующих (как видно из расширений этих файлов) контрольных сумм. Их тоже нужно скачать.
Итак, загрузка образа, используя утилиту wget:
Загрузка файла с контрольной суммой SHA1:
Просмотр содержащегося в файле ROSA.FRESH.PLASMA5.R11.x86_64.uefi.iso.sha1sum значения контрольной суммы SHA1 с помощью команды cat:
Как можно видеть, представлены контрольная сумма и имя образа, для которого она была вычислена. Теперь можно, собственно, проверить сам образ, используя для этого команду sha1sum;
Зрительно сопоставив значения контрольных сумм из вывода команды sha1sum и из содержимого файла PLASMA5.R11.x86_64.uefi.iso.sha1sum, можно убедиться, что они полностью совпадают. Таким образом, загруженный образ идентичен тому, что находится на сервере и его можно смело использовать.
Следует отметить, что версии SHA отличаются количеством следующих друг за другом запусков SHA – 256, 384 и 512. Для всех этих версий существуют соответствующие команды: sha256sum, sha384sum и sha512sum. Аналогичным образом можно использовать и команду md5sum для проверки контрольных сумм MD5.
Заключение
Итак, были рассмотрены самые распространённые способы проверки файлов. Как можно видеть, это совсем не сложно и выполняется стандартными средствами в любой системе Linux буквально одной командой.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник