Sometimes you need to create a file checksum to make sure files are not tampered with. Luckily PowerShell offers a standard cmdlet for this: Get-FileHash
. Use this to validate file integrity in Windows (Windows Server).
Identifying changed files and possible attacks on your systems is of create importance. PowerShell offers the Get-FileHash cmdlet which computes a hash value of a file. If a hash value has changed a file has change and might indicate a possible infection or attack. Here is how to use Get-FileHash.
The cmdlet Get-FileHash:
Suppose I have a file cmd.exe
(yeah we all know that one 🙂 ). Its hash value is:
Get-FileHash C:\Windows\System32\cmd.exe | Select-Object Hash
Hash
----
423E0E810A69AACEBA0E5670E58AFF898CF0EBFFAB99CCB46EBB3464C3D2FACB
Or in one command:
(Get-FileHash C:\Windows\System32\cmd.exe).Hash
423E0E810A69AACEBA0E5670E58AFF898CF0EBFFAB99CCB46EBB3464C3D2FACB
If I copy that executable to my local directory, the file hash remains the same:
PS C:\Users\Jan Reilink> copy C:\Windows\System32\cmd.exe .
PS C:\Users\Jan Reilink> (Get-FileHash "C:\Users\Jan Reilink\cmd.exe").Hash
423E0E810A69AACEBA0E5670E58AFF898CF0EBFFAB99CCB46EBB3464C3D2FACB
PS C:\Users\Jan Reilink> echo " " >> "C:\Users\Jan Reilink\cmd.exe"
PS C:\Users\Jan Reilink> (Get-FileHash "C:\Users\Jan Reilink\cmd.exe").Hash
B01356E4439C05727982FDB62D2F49B04A23F39CA63BF2076EEB022E4B914760
If I were to regularly store and check / verify file checksums, I now know the file is tampered with. Such file changes might indicate an attack. File Integrity Monitor (FIM) in Windows Defender for Cloud can also do this for you.
Learn working with file attributes in PowerShell to verify the LastWriteTime (or last modified date) time of files.
Did you know you can also use certutil.exe
for the job? Even for checking an MD5 checksum? See:
PS C:\Users\Jan Reilink> certutil.exe -hashfile C:\Windows\System32\cmd.exe SHA256
SHA256 hash of C:\Windows\System32\cmd.exe:
423e0e810a69aaceba0e5670e58aff898cf0ebffab99ccb46ebb3464c3d2facb
CertUtil: -hashfile command completed successfully.
PS C:\Users\Jan Reilink> certutil.exe -hashfile C:\Windows\System32\cmd.exe MD5
MD5 hash of C:\Windows\System32\cmd.exe:
5a6be4d2519515241d0c133a26cf62c0
CertUtil: -hashfile command completed successfully.