Fonction de hachage sous Windows avec l'invite de commande et PowerShell

Terminal

La commande suivante permet d'obtenir les algorithmes disponibles :

CertUtil -hashfile -?

Le terminal nous renvoie : MD2 MD4 MD5 SHA1 SHA256 SHA384 SHA512

Les plus utilisés sont le MD5, SHA1, SHA256 et SHA512. SHA512 étant le plus long, c'est celui où une collision est moins probable.

Vous pouvez exécuter la commande suivante pour obtenir le hash :

CertUtil -hashfile "fichier.txt" SHA512

PowerShell

Le code suivant permet d'obtenir le hash avec les informations du fichier.

Get-FileHash -Algorithm SHA512 "fichier.txt"

Pour obtenir seulement le hash on peut utiliser Hash

$hash1 = Get-FileHash -Algorithm SHA512 "fichier.txt"
$hash1.Hash

Vous pouvez comparer deux hashes comme ceci :

$hash1 = Get-FileHash -Algorithm SHA512 "fichier1.txt"
$hash2 = Get-FileHash -Algorithm SHA512 "fichier2.txt"
$hash1.Hash -eq $hash2.Hash

Vous pouvez aussi comparer directement avec le hash comme ça :

$hash1.Hash -eq "50E44CB2B7BD37F10C7A22A90F9409209869BA9475E8724FCDDE9E0BFDA776FA1301F9A39792D619DB58D0ED384C18B000F814F2F3321CAA57F79BD156F3CDD3"

Commentaires