Хэш или контрольная сумма файла — короткое уникальное значение, вычисляемое из содержимого файла и обычно использующееся для проверки целостности и соответствия (совпадения) файлов при загрузке, особенно если речь идет о больших файлах (образы системы и подобные), которые могут быть скачены с ошибками или есть подозрения о том, что файл был подменен вредоносным ПО.
На сайтах загрузок часто бывает представлена контрольная сумма, вычисленная по алгоритмам MD5, SHA256 и другим, позволяющая сверить загруженный файл с файлом, выложенным разработчиком. Для вычисления контрольных сумм файлов можно использовать сторонние программы, но есть способ сделать это и стандартными средствами Windows 10, 8 и Windows 7 (требуется версия PowerShell 4.0 и выше) — с помощью PowerShell или командной строки, что и будет продемонстрировано в инструкции.
Получение контрольной суммы файла средствами Windows
Для начала потребуется запустить Windows PowerShell: проще всего использовать поиск в панели задач Windows 10 или меню Пуск Windows 7 для этого.
Команда, позволяющая вычислить хэш для файла в PowerShell — Get-FileHash, а чтобы использовать ее для вычисления контрольной суммы достаточно ввести ее со следующими параметрами (в примере вычисляется хэш для образа ISO Windows 10 из папки VM на диске C):
Get-FileHash C:\VM\Win10_1607_Russian_x64.iso| Format-List
При использовании команды в таком виде, хэш вычисляется по алгоритму SHA256, но поддерживаются и другие варианты, задать которые можно с помощью параметра -Algorithm, например, для вычисления контрольной суммы MD5 команда будет выглядеть как в примере ниже
Get-FileHash C:\VM\Win10_1607_Russian_x64.iso -Algorithm MD5 | Format-List
При этом поддерживаются следующие значение для алгоритмов вычисления контрольной суммы в Windows PowerShell
- SHA256 (по умолчанию)
- MD5
- SHA1
- SHA384
- SHA512
- MACTripleDES
- RIPEMD160
Подробное описание синтаксиса команды Get-FileHash доступно также на официальном сайте https://technet.microsoft.com/en-us/library/dn520872(v=wps.650).aspx
Получение хэша файла в командной строке с помощью CertUtil
В Windows присутствует встроенная утилита CertUtil для работы с сертификатами, которая, помимо прочего, умеет высчитывать контрольную сумму файлов по алгоритмам:
- MD2, MD4, MD5
- SHA1, SHA256, SHA384, SHA512
Для использования утилиты достаточно запустить командную строку Windows 10, 8 или Windows 7 и ввести команду в формате:
certutil -hashfile путь_к_файлу алгоритм
Пример получения хэша MD5 для файла показан на скриншоте ниже.
Дополнительно: на случай, если вам требуются сторонние программы для вычисления хэшей файлов в Windows, можно обратить внимание на SlavaSoft HashCalc.
Если же требуется вычислить контрольную сумму в Windows XP или в Windows 7 без PowerShell 4 (и возможности его установить), вы можете использовать утилиту командной строки Microsoft File Checksum Integrity Verifier, доступную для загрузки на официальном сайте https://www.microsoft.com/en-us/download/details.aspx?id=11533 (формат команды для использования утилиты: fciv.exe путь_к_файлу — результат будет MD5. Также можно вычислить хэш SHA1: fciv.exe -sha1 путь_к_файлу)
Проверка контрольной суммы скачанного файла позволяет проверить его целостность и убедиться, что содержимое файла не было изменено. Чаще всего администраторы используют процедуру проверки чексуммы для загруженных дистрибутивов ОС и установочных образов ПО.
Идея контрольной суммы заключается в том, что для оригинального файла выполняется расчет некоего значения (хэша) по определенному алгоритму получения хэш-функции (чаще всего это MD5, SHA1 и SHA256), а пользователи потом могут выполнить такую же проверку для файла, который они скачали. Сравнение этих двух значений хэшей позволяет убедиться, что вы получили не модифицированный оригинальный файл. Если хэши файлов отличаются, значит файл был изменен или поврежден.
Для проверки контрольной суммы файла в Windows можно использовать встроенный PowerShell командлет Get-FileHash или утилиту certutil.
Например, чтобы получить значение хэша ISO образа, выполните команду:
Get-FileHash "F:\ISO\en-us_windows_10_enterprise_ltsc_2021_x64_dvd_d289cf96.iso"
Черех некоторое время (расчет может занять некоторое время в зависимости от размера файла), командлет вернет контрольную сумму файла по алгоритму SHA-256 (по умолчанию). С помощью атрибута
-Algorithm
можно задать другой алгоритм вычисления контрольной суммы
-
SHA1
-
SHA256
(по умолчанию) – наиболее популярный алгоритм с наименьшей вероятности возникновения коллизий (когда два разных файла имеют одинаковую контрольную сумму) -
SHA384
-
SHA512
-
MD5
– самый быстрый, но устаревший алгоритм хэширования
Аналогично можно получить хэш сумму файла с помощью certutil.exe:
certutil -hashfile F:\ISO\en-us_windows_10_enterprise_ltsc_2021_x64_dvd_d289cf96.iso SHA256
Где получить контрольные суммы оригинальных ISO файлов образов Windows?
Если у вас есть учетная запись Microsoft, вы можете найти контрольную сумму интересующего вас дистрибутива на сайте https://my.visualstudio.com/Downloads/. Для этого не обязательно иметь активную подписку MSDN. Информация о контрольной сумме образа доступна на вкладке с информацией о продукте.
Также список всех оригинальных образов от Microsoft и их хэшей доступен в следующей сторонней онлайн базе https://files.rg-adguard.net/search. В отличии от сайта Microsoft, здесь можно искать сразу по значению хэша. Выполните поиск по полученному хэшу, чтобы убедиться, что вы скачали оригинальный файл образа.
Регистр символов в хэш сумме не имеет значения.
Для автоматизации проверки хэш сумму скачанного образа с оригинальным значением, можно использовать такой однострочник PowerShell:
((get-filehash .\ en-us_windows_10_enterprise_ltsc_2021_x64_dvd_d289cf96.iso).hash) -eq "c90a6df8997bf49e56b9673982f3e80745058723a707aef8f22998ae6479597d"
Команда вернет
True
, если контрольная сумма файла совпадает с эталонной.
How to Generate MD5 Hash for Files in Windows
MD5 hash helps verify file integrity by creating a unique digital fingerprint. Windows users can generate MD5 hash values using built-in PowerShell commands or third-party tools like HashTab and MD5summer. The PowerShell command “Get-FileHash” with the MD5 parameter provides the quickest method. These hash values confirm if files remain unchanged during transfers or downloads. This guide explains multiple ways to get MD5 hash values for your Windows files.
Prerequisites Before Generating MD5 Hashes on your Windows
Before starting, ensure that you have the file ready for which you need the MD5 hash. This tutorial will demonstrate generating hashes using a sample file called sample-file.zip.
Also, if you want to generate hashes via the command line, make sure you run the command prompt as administrator.
How to Generate MD5 Hash Using CertUtil
CertUtil is a built-in command line program in Windows that can be used to generate MD5 or other cryptographic hashes.
Here are the steps:
certutil -hashfile sample-file.zip MD5
MD5 hash of sample-file.zip:
57b5e70f96d4d855ede523231e8dd4ca
CertUtil: -hashfile command completed successfully.
The long string of alphanumeric characters is the MD5 hash of the file. You can verify hashes from multiple sources using this method.
How to Generate MD5 Hash Using PowerShell
PowerShell has a built-in cmdlet called Get-FileHash that can be used to generate file hashes.
Here are the steps:
Get-FileHash -Algorithm MD5 sample-file.zip
MD5 57B5E70F96D4D855EDE523231E8DD4CA C:\Users\Downloads\sample-file.zip
This is the MD5 hash for sample-file.zip.
$md5Hash = Get-FileHash -Algorithm MD5 sample-file.zip
Write-Output $md5Hash.Hash
This prints out the hash value directly.
The Get-FileHash cmdlet provides a simple way to generate hashes using PowerShell.
How to Generate MD5 Hash Using WinMD5Free
WinMD5Free is a free utility for Windows that can calculate MD5 and other hashes.
Here are the steps to use it:
The benefit of using a tool like WinMD5Free is that it makes it easy to hash multiple files at once and verify their contents. The process is graphical and straightforward.
How to Verifying Downloaded Files
One of the main uses for MD5 hashes is to verify files downloaded over the internet. Software distributions like Linux ISO images come bundled with their MD5 sums.
Here is how to verify downloads using hashes:
Always cross-check important downloads against provided MD5 hashes before using them. This confirms their integrity and protects against tampering.
How to Generate Hashing Text Strings using PowerShell
In addition to files, you can also generate MD5 hashes of text strings using PowerShell.
[System.BitConverter]::ToString($(Get-FileHash -Algorithm MD5 -InputStream ([System.IO.MemoryStream]::new()) -Buffer ([System.Text.Encoding]::UTF8.GetBytes("Hello World!"))).Hash) -replace '-',''
ED076287532E86365E841E92BFC50D8C
You can tweak the text as needed. This can be helpful for generating hashes for passwords, codes, or other textual data.
How to Automating MD5 Generation
For frequent use cases, you can also script the generation of MD5 hashes to avoid retyping the commands.
Here is a sample PowerShell script to output MD5 hashes for all files in a folder:
$files = Get-ChildItem C:\Hashes
foreach ($file in $files) {
$hash = Get-FileHash -Algorithm MD5 $file.FullName
Write-Output "$($file.Name) : $($hash.Hash)"
}
Save this as a .ps1 file and run it whenever necessary. You can customize it according to your needs.
Automation makes repetitive tasks like checking multiple files easier.
Final Thoughts
Generating MD5 checksums on Windows is straightforward, using inbuilt tools like CertUtil, PowerShell, and third-party apps. With these methods, you can verify downloads, check data integrity, and automate hashing.
Remember always to cross-check critical files against provided MD5 sums before use. This ensures the content is original and unaltered.
This step-by-step guide should help you easily calculate MD5 hashes for any file using multiple methods on your Windows machine.
Frequently Asked Questions (FAQs)
What is an MD5 hash used for?
MD5 hashes allow verification of file integrity and detection of changes or tampering. They are commonly used for software downloads and key verification.
Can an MD5 hash be reversed to the original data?
No. The MD5 algorithm is one-way cryptographic hashing, so hashes cannot be converted back to original data.
What is the difference between MD5, SHA1 and SHA256 hashes?
MD5 is the fastest but is now prone to collisions. SHA1 is slower but still vulnerable. SHA256 is currently the most secure against attacks.
Is the MD5 hash unique for each file?
While unlikely, two different files can have the same MD5 hash. This is called a collision. So, more than MD5 is needed to verify files.
Can I generate other hashes like SHA1 using the same methods?
Yes, the techniques above can generate other hashes by passing the algorithm name, such as SHA1, SHA256, etc., instead of MD5.
Last Updated :
14 Aug, 2024
To get the hash of a file using CMD in Windows, you can use the built-in `certutil` tool. This command generates a unique hash value for the file, which helps in verifying its integrity. For example, you can compute SHA-256, MD5, or SHA-1 hashes depending on your needs. This method is convenient as it doesn’t require additional software.
What is Hash Value?
A hash value, also known simply as a hash, is a fixed-size numerical or alphanumeric value generated from input data using a hash function. Hash functions take an input (or «message») and produce a unique output that represents the data. Here’s a detailed look at hash values:
A cryptographic hash is a fixed-size work string (or text) that is used as an identifier/fingerprint of some data. These are particularly useful in determining the integrity of files after they are transferred over a communication channel. Hashes are even utilized by certain OS-level processes for their work. The command processor of Windows OS (cmd.exe) provides the user with the ability to compute hashes on files/Directories via a utility command named Certutil. In this article, we will learn about computing hashes on a command prompt (cmd).
Description of Command
The command Certutil is primarily used for working with digital certificates and not hashes. The ability to hash files is due to the presence of a -hashfile switch in it.
> Certutil -hashfile
-hashfile -- Generate and display cryptographic hash over a file
Where certutil is the command, and -hashfile is a switch provided to it.
Syntax
The -hashfile switch takes in two arguments. Firstly, the path to the file in which we are interested in getting the hash. And then the hash algorithm that we are interested in.
Creating a Syntax
Certutil -hashfile (Path_to_file) [HashAlgo]
Where Path_to_file is mandatory (should be provided) argument and HashAlgo is optional argument (If not provided, defaults to SHA1). If HashAlgo is provided it should either be from SHA (Secure Hash Algorithms) or from MD (Message Digest) Cryptographic Hash families. Some of the hash algorithms allowed in the command are MD4, MD5, SHA1, SHA256, SHA512.
Usage of the Command
To demonstrate the usage of the command, we would be running the command on a file. Our example file will be at the location
C:\Users\Public\spars.txt"
That contains some text data. So to get the MD5 (Message Digest 5) hash of the file, we would have to execute the command.
certutil -hashfile "C:\Users\Public\spars.txt" MD5
The command upon execution would produce an output similar to this.
MD5 hash of spars.txt:
cb21e6741817a2d3020e02bb94301ae4
CertUtil: -hashfile command completed successfully.
To get SHA512 hash of the above file the command and the output would appear as following :
Conclusion
Hash values are essential tools for ensuring data integrity and security in various computing scenarios. A hash value, generated by a hash function, serves as a fixed-size representation of input data, making it easier to verify the authenticity and consistency of that data. Cryptographic hashes, in particular, are used to identify and verify the integrity of files and other data, helping to detect any unauthorized changes or corruption.
The Certutil command in Windows provides a straightforward way to compute hash values for files using different hash algorithms. By leveraging Certutil with the -hashfile switch, users can generate hash values for files and validate their integrity effectively. Understanding how to use this command can be useful for system administrators, developers, and security professionals who need to manage and verify data integrity in their workflows.
In Windows you can make a checksum of a file without installing any additional software.
For this you can use the certUtil
– built-in command-line tool that works both in Windows CMD and PowerShell.
In this note i will show the examples of how to make md5sum
and sha256sum
of a file in Windows from the command line.
Cool Tip: zip
and unzip
from the command line in Windows! Read more →
Checksum a file in Windows using the built-in certUtil
command-line utility:
C:\> certUtil -hashfile <PATH_TO_FILE> <HASH_ALGORITHM>
MD5 checksum example (md5sum
):
C:\> certUtil -hashfile C:\file.img MD5
SHA256 checksum example (sha256sum
):
C:\> certUtil -hashfile C:\file.img SHA256
Get only hash value:
# Windows CMD: C:\> CertUtil -hashfile C:\file.img MD5 | findstr /v "hash" # Windows PowerShell: PS C:\> $(CertUtil -hashfile C:\file.img MD5)[1] -replace " ",""
Available hash algorithms:
MD2 MD4 MD5 SHA1 SHA256 SHA384 SHA512
Hash Algorithms: Note that on Windows 7, the hash algorithms are case-sensitive. Be sure to type, for example, not “md5” but “MD5”. In the subsequent versions of Windows the case doesn’t matter.
Get help:
C:\> certutil -hashfile -?
Was it useful? Share this post with the world!