Carsten
Carsten

Reputation: 2207

How to calculate the CRC32 of a string in Powershell?

I could not find any simple Powershell-function to calculate the CRC32 of a given string. Therefore I decided to write my own function which I would like to share in my answer.

Upvotes: 2

Views: 3664

Answers (3)

Carsten
Carsten

Reputation: 2207

Here the full CRC32 function in pure PS for educational purpose:

function CRC32($str) {
    $crc   = [uint32]::MaxValue
    $poly  = [uint32]0xEDB88320L
    $bytes = [System.Text.Encoding]::UTF8.GetBytes($str)
    foreach ($byte in $bytes) {
        $crc = ($crc -bxor $byte)
        foreach ($bit in 0..7) {
            $crc = ($crc -shr 1) -bxor ($poly * ($crc -band 1))
        }
     }
    return [uint32]::MaxValue - $crc
}

$str = "123456789"
$crc32 = CRC32 $str
Write-Host "CRC32 of '$str' is: 0x$($crc32.ToString("X8"))"

I decided skipping the creation of a lookup-table which means I have to do a bitwise-loop for each byte. Therefore it should only be used mainly for shorter strings (calculation time of a string with a length of 1MB is still below 1sec).

Upvotes: 0

Cem Polat
Cem Polat

Reputation: 701

Alternatively, you can call Win32 API RtlComputeCrc32. Save the below in a ps1 file like crc32.ps1

param (
    [Parameter(Mandatory=$true)]
    [string]$InputFile
)

Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;

public class Win32Api {
    [DllImport("ntdll.dll")]
    public static extern uint RtlComputeCrc32(uint dwInitial, byte[] pData, int iLen);
}
"@

# Read the file as bytes
$fileBytes = [System.IO.File]::ReadAllBytes($InputFile)

# Calculate the CRC32 checksum using the Win32 API
$crc32 = [Win32Api]::RtlComputeCrc32(0, $fileBytes, $fileBytes.Length)

# Convert the CRC32 value to hexadecimal string
$crc32String = $crc32.ToString("X8")

# Display the CRC32 checksum
Write-Output "CRC32: 0x$crc32String" 
# Just to keep Powershell window open. Remove this line for non-interactive usage.
pause

Call it in powershell like

Powershell -ExecutionPolicy Bypass -File crc32.ps1 -InputFile SomeFile.txt

Upvotes: 1

Carsten
Carsten

Reputation: 2207

Based on the good input from @Cem Polat here a more elegant solution with embededd code:

$crc32 = add-type '
[DllImport("ntdll.dll")]
public static extern uint RtlComputeCrc32(uint dwInitial, byte[] pData, int iLen);
' -Name crc32 -PassThru

$str = "123456789"
$arr = [System.Text.Encoding]::UTF8.GetBytes($str)
$crc = $crc32::RtlComputeCrc32(0, $arr, $arr.Count)
$crc.ToString("X8")

Upvotes: 3

Related Questions