Linux check md5 sum

Проверка контрольной суммы Linux

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

В этой небольшой статье мы рассмотрим что такое контрольная сумма Linux, а также как выполнять проверку целостности файлов с помощью контрольных сумм md5.

Что такое MD5?

Контрольные суммы Linux с вычисляемые по алгоритму MD5 (Message Digest 5) могут быть использованы для проверки целостности строк или файлов. MD5 сумма — это 128 битная строка, которая состоит из букв и цифр. Суть алгоритма MD5 в том, что для конкретного файла или строки будет генерироваться 128 битный хэш, и он будет одинаковым на всех машинах, если файлы идентичны. Трудно найти два разных файла, которые бы выдали одинаковые хэши.

В Linux для подсчета контрольных сумм по алгоритму md5 используется утилита md5sum. Вы можете применять ее для проверки целостности загруженных из интернета iso образов или других файлов.

Эта утилита позволяет не только подсчитывать контрольные суммы linux, но и проверять соответствие. Она поставляется в качестве стандартной утилиты из набора GNU, поэтому вам не нужно ничего устанавливать.

Проверка контрольных сумм в Linux

Синтаксис команды md5sum очень прост:

$ md5sum опции файл

Опций всего несколько и, учитывая задачи утилиты, их вполне хватает:

  • -c — выполнить проверку по файлу контрольных сумм;
  • -b — работать в двоичном формате;
  • -t — работать в текстовом формате;
  • -w — выводить предупреждения о неверно отформатированном файле сумм;
  • —quiet — не выводить сообщения об успешных проверках.

Сначала скопируйте файл /etc/group в домашнюю папку чтобы на нем немного поэкспериментировать:

Например, давайте подсчитаем контрольную сумму для файла /etc/group:

md5

Или вы можете сохранить сразу эту сумму в файл для последующей проверки:

Затем каким-либо образом измените этот файл, например, удалите первую строчку и снова подсчитайте контрольные суммы:

md51md52

Как видите, теперь значение отличается, а это значит, что содержимое файла тоже изменилось. Дальше верните обратно первую строчку root:x:0: и скопируйте этот файл в groups_list и

Затем опять должна быть выполнена проверка контрольной суммы linux:

Читайте также:  Linux create user sudoers

md53

Сумма соответствует первому варианту, даже несмотря на то, что файл был переименован. Обратите внимание, что md5sum работает только с содержимым файлов, ее не интересует ни его имя, ни его атрибуты. Вы можете убедиться, что оба файла имеют одинаковые суммы:

md5sum groups groups_list

md54

Вы можете перенаправить вывод этой команды в файл, чтобы потом иметь возможность проверить контрольные суммы:

md5sum groups groups_list > groups.md5

Чтобы проверить, не были ли файлы изменены с момента создания контрольной суммы используйте опцию -c или —check. Если все хорошо, то около каждого имени файла появится слово OK или ЦЕЛ:

md55

Но теперь вы не можете переименовывать файлы, потому что при проверке утилита будет пытаться открыть их по имени и, естественно, вы получите ошибку. Точно так же все работает для строк:

echo -n «Losst» | md5sum —
$ echo -n «Losst Q&A» | md5sum —

md56

Выводы

Из этой статьи вы узнали как выполняется получение и проверка контрольной суммы linux для файлов и строк. Хотя в алгоритме MD5 были обнаружены уязвимости, он все еще остается полезным, особенно если вы доверяете инструменту, который будет создавать хэши.

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

На завершение небольшое видео по теме:

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

Linux check md5 sum

NAME

md5sum - compute and check MD5 message digest

SYNOPSIS

DESCRIPTION

Print or check MD5 (128-bit) checksums. With no FILE, or when FILE is -, read standard input. -b, --binary read in binary mode -c, --check read MD5 sums from the FILEs and check them --tag create a BSD-style checksum -t, --text read in text mode (default) The following three 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 -w, --warn warn about improperly formatted checksum lines --strict with --check, exit non-zero for any invalid input --help display this help and exit --version output version information and exit The sums are computed as described in RFC 1321. 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.

BUGS

The MD5 algorithm should not be used any more for security related purposes. Instead, better use an SHA-2 algorithm, implemented in the programs sha224sum(1), sha256sum(1), sha384sum(1), sha512sum(1)

AUTHOR

Written by Ulrich Drepper, Scott Miller, and David Madore.

REPORTING BUGS

Report md5sum bugs to bug-coreutils@gnu.org GNU coreutils home page: http://www.gnu.org/software/coreutils/> General help using GNU software: http://www.gnu.org/gethelp/> Report md5sum translation bugs to http://translationproject.org/team/>
Copyright © 2013 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law.

SEE ALSO

The full documentation for md5sum is maintained as a Texinfo manual. If the info and md5sum programs are properly installed at your site, the command info coreutils 'md5sum invocation' should give you access to the complete manual.

© 2019 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd.

Читайте также:  Hp mfp m428dw драйвер linux

Источник

How to Verify Checksum on Linux [Beginner Guide]

using checksum in Ubuntu Linux

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:

Let’s see how to verify a checksum on Linux.

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.
Читайте также:  Установка файлов rpm linux

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:

sha256sum ubuntu-mate-16.10-desktop-amd64.iso

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.

Источник

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