Skip to content

Instantly share code, notes, and snippets.

@alkavan
Created October 4, 2024 08:47
Show Gist options
  • Save alkavan/d8f43d8f02f4e4457aecec2a3c87f03b to your computer and use it in GitHub Desktop.
Save alkavan/d8f43d8f02f4e4457aecec2a3c87f03b to your computer and use it in GitHub Desktop.
A script to fetch Windows key from system
# Function to retrieve the product key from the registry
function Get-WindowsKey {
try {
$path = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SoftwareProtectionPlatform'
$key = (Get-ItemProperty -Path $path -Name BackupProductKeyDefault -ErrorAction Stop).BackupProductKeyDefault
return $key
} catch {
return $null
}
}
# Function to get the key using WMI
function Get-WindowsKeyWMI {
try {
$key = (Get-WmiObject -query 'select * from SoftwareLicensingService').OA3xOriginalProductKey
return $key
} catch {
return $null
}
}
# Function to decode the binary key
function ConvertTo-Key($Key) {
$keyOffset = 52
$isWin8 = [int]($Key[66] / 6) -band 1
$HexDigits = "BCDFGHJKMPQRTVWXY2346789"
$i = 24
[string]$result = ""
# Decoding the key
while ($i -ge 0) {
$r = 0
for ($j = 14; $j -ge 0; $j--) {
$r = ($r * 256) -bxor $Key[$j + $keyOffset]
}
for ($j = 24; $j -ge 0; $j -= 4) {
$result = $HexDigits[$r -band 0x0f] + $result
$r = $r -shr 4
}
$i--
}
if ($isWin8 -eq 1) {
$result = $result.Substring(1)
$result = $result.Insert(0, "N")
}
return $result.Insert(5, "-").Insert(11, "-").Insert(17, "-").Insert(23, "-")
}
# Main script
$registryKey = Get-WindowsKey
$wmiKey = Get-WindowsKeyWMI
Write-Host "Attempting to retrieve Windows product key..."
if ($registryKey) {
Write-Host "Product Key (from Registry): $registryKey"
} elseif ($wmiKey) {
Write-Host "Product Key (from WMI): $wmiKey"
} else {
Write-Host "Unable to retrieve product key using standard methods. Attempting advanced method..."
try {
$map = "BCDFGHJKMPQRTVWXY2346789"
$value = (Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion").DigitalProductId[0x34..0x42]
$productKey = ConvertTo-Key $value
Write-Host "Product Key (Decoded): $productKey"
} catch {
Write-Host "Error: Unable to retrieve or decode product key."
}
}
# Display license information
$license = Get-CimInstance -ClassName SoftwareLicensingProduct | Where-Object { $_.PartialProductKey } | Select-Object Description, LicenseStatus
Write-Host "`nLicense Information:"
Write-Host "Description: $($license.Description)"
Write-Host "Status: $($license.LicenseStatus)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment