Проверка хэш суммы powershell
Computes the hash value for a file by using a specified hash algorithm.
Inputs
You can pipe a string to the Get-FileHash cmdlet that contains a path to one or more files.
Example 4: Compute the hash of a string
PowerShell does not provide a cmdlet to compute the hash of a string. However, you can write a string to a stream and use the InputStream parameter of Get-FileHash to get the hash value.
Description
The Get-FileHash cmdlet computes the hash value for a file by using a specified hash algorithm. A hash value is a unique value that corresponds to the content of the file. Rather than identifying the contents of a file by its file name, extension, or other designation, a hash assigns a unique value to the contents of a file. File names and extensions can be changed without altering the content of the file, and without changing the hash value. Similarly, the file's content can be changed without changing the name or extension. However, changing even a single character in the contents of a file changes the hash value of the file.
The purpose of hash values is to provide a cryptographically-secure way to verify that the contents of a file have not been changed. While some hash algorithms, including MD5 and SHA1, are no longer considered secure against attack, the goal of a secure hash algorithm is to render it impossible to change the contents of a file -- either by accident, or by malicious or unauthorized attempt -- and maintain the same hash value. You can also use hash values to determine if two different files have exactly the same content. If the hash values of two files are identical, the contents of the files are also identical.
By default, the Get-FileHash cmdlet uses the SHA256 algorithm, although any hash algorithm that is supported by the target operating system can be used.
Inputs
You can pipe a string to the Get-FileHash cmdlet that contains a path to one or more files.
Example 3: Compute the hash value of a stream
Получение хэша файла в командной строке с помощью CertUtil
В Windows присутствует встроенная утилита CertUtil для работы с сертификатами, которая, помимо прочего, умеет высчитывать контрольную сумму файлов по алгоритмам:
- MD2, MD4, MD5
- SHA1, SHA256, SHA384, SHA512
Для использования утилиты достаточно запустить командную строку Windows 10, 8 или Windows 7 и ввести команду в формате:
Пример получения хэша MD5 для файла показан на скриншоте ниже.
Дополнительно: на случай, если вам требуются сторонние программы для вычисления хэшей файлов в Windows, можно обратить внимание на SlavaSoft HashCalc.
Computes the hash value for a file by using a specified hash algorithm.
Example 1: Compute the hash value for a file
This example uses the Get-FileHash cmdlet to compute the hash value for the /etc/apt/sources.list file. The hash algorithm used is the default, SHA256. The output is piped to the Format-List cmdlet to format the output as a list.
Example 2: Compute the hash value for an ISO file
This example uses the Get-FileHash cmdlet and the SHA384 algorithm to compute the hash value for an ISO file that an administrator has downloaded from the internet. The output is piped to the Format-List cmdlet to format the output as a list.
Outputs
Microsoft.Powershell.Utility.FileHash
Get-FileHash returns an object that represents the path to the specified file, the value of the computed hash, and the algorithm used to compute the hash.
Summary: Learn how to use Windows PowerShell to compute MD5 hashes and find files changed in a folder.
Hey, Scripting Guy! I have a folder and I would like to detect if files within it have changed. I do not want to write a script to parse file sizes and dates modified because that seems to be a lot of work. Is there a way I can use an MD 5 hash to do this? Oh, by the way, I do have a reference folder that I can use.
Hello RS,
Microsoft Scripting Guy, Ed Wilson, is here. Things are certainly beginning to get crazy. In addition to all of the normal end-of-the-year things going on around here, in addition to the middle of a product ship cycle, we are entering “conference season.” This morning, the Scripting Wife and I (along with a hitchhiker from the Charlotte Windows PowerShell User Group) load up the car and head to Atlanta, Georgia for TechStravaganza. We have the speaker’s dinner this evening, and tomorrow we will be flat out all day as the event kicks off. It will be a great day with one entire track devoted to Windows PowerShell. The following week, we head to Florida for a SQL Saturday, Microsoft TechEd, and IT Pro Camp. In fact, our Florida road trip begins with the monthly meeting of the Charlotte Windows PowerShell User Group (we actually leave for our trip from the group meeting). If you find all this a bit confusing, I do too. That is why I am glad we have the Scripting Community page, so I can keep track of everything.
Note This is the fourth in a series of four Hey, Scripting Guy! blogs about using Windows PowerShell to facilitate security forensic analysis of a compromised computer system. The intent of the series is not to teach security forensics, but rather to illustrate how Windows PowerShell could be utilized to assist in such an inquiry. The first blog discussed using Windows PowerShell to capture and to analyze process and service information. The second blog talked about using Windows PowerShell to save event logs in XML format and perform offline analysis. The third blog talked about computing MD5 hashes for files in a folder.
It is extremely easy to spot a changed file in a folder by making a simple addition to the technique discussed yesterday. In fact, it does not require writing a script. The trick is to use the Compare-Object cmdlet. In the image that follows, two folders reside beside one another. The Ref folder contains all original files and folders. The Changed folder contains the same content, with a minor addition made to the a.txt file.
After you import the PSCX, use the Compare-Object cmdlet to compare the hashes of the c:\ref folder with the hashes of the c:\changed folder. The basic command to compute the hashes of the files in each folder was discussed in yesterday’s blog. The chief difference here is the addition of the Compare-Object cmdlet. The command (a single logical command) is shown here.
PS C:\> Compare-Object -ReferenceObject (dir c:\ref -Recurse | Where-Object
container > | get-hash) -differenceObject (dir c:\changed -Recurse | Where-Object
The command and the associated output are shown here.
The command works because the Compare-Object cmdlet knows how to compare objects, and because the two Get-Hash commands return objects. The arrows indicate which object contains the changed objects. The first one exists only in the Difference object, and the second one only exists in the Reference object.
Example 3: Compute the hash value of a stream
Вычисление Контрольных Сумм
Вычислить контрольную сумму файла(ов) можно с помощью командлета Get-FileHash .
Для одного файла, полная команда будет выглядеть так:
Параметр -Algorithm задает алгоритм вычисляемого хеша. В данном случае выбран алгоритм MD5 (список всех возможных алгоритмов см. выше). Если выполнить команду не указывая данный параметр, то по умолчанию будет выбран алгоритм SHA256.
Для вычисления контрольных сумм нескольких файлов, достаточно указать соответствующую файловую маску. К примеру, вычислим контрольные суммы для всех файлов *.jpg:
Если файлы разных расширений, или вовсе без них, то можно просто перечислить их через запятую.
В данном примере, выполнено вычисление контрольной суммы для файлов 1.jpg и text.txt.
Через запятую, можно перечислять не только конкретные файлы, но и маски файлов.
И последнее, вычислить контрольные суммы всех файлов в текущем каталоге можно указав в качестве файловой маски знак звездочки "*".
Содержание
Получение контрольной суммы файла средствами Windows
Для начала потребуется запустить Windows PowerShell: проще всего использовать поиск в панели задач Windows 10 или меню Пуск Windows 7 для этого.
Команда, позволяющая вычислить хэш для файла в PowerShell — Get-FileHash, а чтобы использовать ее для вычисления контрольной суммы достаточно ввести ее со следующими параметрами (в примере вычисляется хэш для образа ISO Windows 10 из папки VM на диске C):
При использовании команды в таком виде, хэш вычисляется по алгоритму SHA256, но поддерживаются и другие варианты, задать которые можно с помощью параметра -Algorithm, например, для вычисления контрольной суммы MD5 команда будет выглядеть как в примере ниже
При этом поддерживаются следующие значение для алгоритмов вычисления контрольной суммы в Windows PowerShell
- SHA256 (по умолчанию)
- MD5
- SHA1
- SHA384
- SHA512
- MACTripleDES
- RIPEMD160
Syntax
Syntax
Example 2: Compute the hash value for an ISO file
This example uses the Get-FileHash cmdlet and the SHA384 algorithm to compute the hash value for an ISO file that an administrator has downloaded from the internet. The output is piped to the Format-List cmdlet to format the output as a list.
PowerShell
PowerShell позволяет вычислить контрольные суммы для одного файла, или для группы файлов. Поддерживает алгоритмы MACTripleDES, MD5, RIPEMD160, SHA1, SHA256, SHA384, SHA512 . Может вывести полученные данные в удобном отчете в текстовом виде или в форматах html, xml, csv, json .
Find the changed file
Using the information from the previous command, I create a simple filter to return more information about the changed file. The easy way to do this is to highlight the hash, and place it in a Where-Object command (the ? is an alias for Where-Object). I know from yesterday’s blog, that the property containing the MD5 hash is called hashstring, and therefore, that is the property I look for. The command is shown here.
PS C:\> dir c:\changed -Recurse | Where-Object | get-hash | ?
$_.hashstring -match ‘DE1278022BF9A1A6CB6AAC0E5BEE1C5B’>
The command and the output from the command are shown in the image that follows.
Example 4: Compute the hash of a string
PowerShell does not provide a cmdlet to compute the hash of a string. However, you can write a string to a stream and use the InputStream parameter of Get-FileHash to get the hash value.
Вывод Полученных Данных в Указанном Формате
По умолчанию, вывод информации в PowerShell выполняется в окно консоли в виде таблицы. Полученный результат, при необходимости, можно преобразовать в указанный формат, а именно html, xml, csv, json .
Делается это с помощью передачи результатов выполнения командлетов предыдущего раздела, через конвейер, командлетам ConvertTo-Html , ConvertTo-Xml , ConvertTo-Csv , ConvertTo-Json .
Преобразование вывода к формату HTML.
Полученный файл, можно просмотреть в веб-браузере.
Преобразование вывода к формату XML.
Преобразование вывода к формату CSV.
Преобразование вывода к формату JSON.
Examples
Сравнение Хешей
Сравнить полученный хеш с эталонным, PowerShell так же может. Реализация такой возможности будет осуществлять с помощью командлета Where-Object .
К примеру имеется хеш " 1C9C3339AB5E58E392588A15CD2FC174 ". Попробуем определить есть ли файл с подобным хешем в тестовой папке.
Файлы с таким же хешем будут присутствовать в выводе команды.
Использовать PowerShell для вычисления контрольных сумм файлов, не так сложно как кажется. Учитывая возможность проверки групп файлов, или всех файлов в указанной директории, с последующим сохранением полученного вывода в необходимом формате, мы получаем более привлекательный инструмент, по сравнению с тем же HashTab. И самое главное, не нужно ничего скачивать. Все необходимое уже находится в операционной системе Windows.
В статье было рассмотрено: Как вычислить контрольные суммы файлов с помощью PowerShell? Как вычислить контрольную сумму MD5 в PowerShell? Как вычислить контрольную сумму SHA1 в PowerShell? Как вычислить контрольную сумму SHA256 в PowerShell? Как сравнить хеши в PowerShell?
Parameters
If no value is specified, or if the parameter is omitted, the default value is SHA256.
For security reasons, MD5 and SHA1, which are no longer considered secure, should only be used for simple change validation, and should not be used to generate hash values for files that require protection from attack or tampering.
Type: | String |
Accepted values: | SHA1, SHA256, SHA384, SHA512, MD5 |
Position: | 1 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the input stream.
Type: | Stream |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the path to a file. Unlike the Path parameter, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose the path in single quotation marks. Single quotation marks instruct PowerShell not to interpret characters as escape sequences.
Type: | String [ ] |
Aliases: | PSPath, LP |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the path to one or more files as an array. Wildcard characters are permitted.
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
Outputs
Microsoft.Powershell.Utility.FileHash
Get-FileHash returns an object that represents the path to the specified file, the value of the computed hash, and the algorithm used to compute the hash.
Хэш или контрольная сумма файла — короткое уникальное значение, вычисляемое из содержимого файла и обычно использующееся для проверки целостности и соответствия (совпадения) файлов при загрузке, особенно если речь идет о больших файлах (образы системы и подобные), которые могут быть скачены с ошибками или есть подозрения о том, что файл был подменен вредоносным ПО.
На сайтах загрузок часто бывает представлена контрольная сумма, вычисленная по алгоритмам MD5, SHA256 и другим, позволяющая сверить загруженный файл с файлом, выложенным разработчиком. Для вычисления контрольных сумм файлов можно использовать сторонние программы, но есть способ сделать это и стандартными средствами Windows 10, 8 и Windows 7 (требуется версия PowerShell 4.0 и выше) — с помощью PowerShell или командной строки, что и будет продемонстрировано в инструкции.
Parameters
If no value is specified, or if the parameter is omitted, the default value is SHA256.
For security reasons, MD5 and SHA1, which are no longer considered secure, should only be used for simple change validation, and should not be used to generate hash values for files that require protection from attack or tampering.
Type: | String |
Accepted values: | SHA1, SHA256, SHA384, SHA512, MD5 |
Position: | 1 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the input stream.
Type: | Stream |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the path to a file. Unlike the Path parameter, the value of the LiteralPath parameter is used exactly as it is typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose the path in single quotation marks. Single quotation marks instruct PowerShell not to interpret characters as escape sequences.
Type: | String [ ] |
Aliases: | PSPath, LP |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the path to one or more files as an array. Wildcard characters are permitted.
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | True |
Finding the differences in the files
I use essentially the same commands to find the differences between the two files. First, I make sure that I know the reference file that changed. Here is the command that I use for that:
PS C:\> dir c:\ref -Recurse | Where-Object | get-hash | ? < $_.h
ashstring -match ’32B72AF6C2FF057E7C63C715449BFB6A’>
When I have ensured that it is, in fact, the a.txt file that has changed between the reference folder and the changed folder, I again use the Compare-Object cmdlet to compare the content of the two files. Here is the command I use to compare the two files:
PS C:\> Compare-Object -ReferenceObject (Get-Content C:\Ref\a.txt) -DifferenceObjec
The image that follows illustrates the commands and the output associated with these commands.
RS, that is all there is to using finding modifications to files in folders when you have a reference folder. Join me tomorrow for more cool stuff in the world of Windows PowerShell.
Example 1: Compute the hash value for a file
This example uses the Get-FileHash cmdlet to compute the hash value for the /etc/apt/sources.list file. The hash algorithm used is the default, SHA256. The output is piped to the Format-List cmdlet to format the output as a list.
Examples
Description
The Get-FileHash cmdlet computes the hash value for a file by using a specified hash algorithm. A hash value is a unique value that corresponds to the content of the file. Rather than identifying the contents of a file by its file name, extension, or other designation, a hash assigns a unique value to the contents of a file. File names and extensions can be changed without altering the content of the file, and without changing the hash value. Similarly, the file's content can be changed without changing the name or extension. However, changing even a single character in the contents of a file changes the hash value of the file.
The purpose of hash values is to provide a cryptographically-secure way to verify that the contents of a file have not been changed. While some hash algorithms, including MD5 and SHA1, are no longer considered secure against attack, the goal of a secure hash algorithm is to render it impossible to change the contents of a file -- either by accident, or by malicious or unauthorized attempt -- and maintain the same hash value. You can also use hash values to determine if two different files have exactly the same content. If the hash values of two files are identical, the contents of the files are also identical.
By default, the Get-FileHash cmdlet uses the SHA256 algorithm, although any hash algorithm that is supported by the target operating system can be used.
Читайте также: