Retrieve/decrypt Windows 7 product key from Linux

Posted on

Problem :

I accidentally disconnected my hard drive while it was still running and corrupted my Windows 7 installation; I am now completely unable to boot into Windows. I have tried everything to try and repair the installation: Windows Startup Repair, chkdsk /r, SFC /scannow, bootrec /rebuildbcd, etc. and no luck. I want to just perform a fresh install, but my problem is that I do not have my Windows product key written down anywhere, and I am unable to use any scripts or utilities to retrieve it from the registry because I cannot boot into Windows.

Windows 7 product keys are stored, encrypted, in the “DigitalProductId” value of the registry key HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersion. I was able to mount the corrupted Windows partition read-only from an Ubuntu live CD and copy the WindowsSystem32configSOFTWARE registry hive, which contains the key & value in question, to a flash drive, but loading this hive into regedit on a working Windows installation and then trying to use scripts or utilities to decrypt the loaded “DigitalProductId” value only returns the product key of the host Windows installation, no matter how much fiddling I try. I’ve tried contacting Microsoft support and they’ve been rather unhelpful. Would anyone be able to guide me further? Perhaps if there’s a different way to retrieve the product key from Linux?

If someone more familiar with scripting/cryptography would be willing to try and follow the decryption script to decrypt the product key by hand, I could e-mail you the exported “DigitalProductId” value, SOFTWARE registry hive, and decryption script.

Solution :

There is a great tool available for Linux called chntpw. You can get it easily on Debian/Ubuntu via:

sudo apt install chntpw

To look into the relevant registry file mount the Windows disk and open it like so:

chntpw -e /path/to/windisk/Windows/System32/config/software

Now to get the decoded DigitalProductId enter this command:

dpi MicrosoftWindows NTCurrentVersionDigitalProductId

For those who are not shy to do a little bit of coding.

I found an algorithm about 10 years ago and implemented it in C# (See below)

If you just want to run it on Windows

I took the liberty to convert it to a powershell script:

$dpid = Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINESOFTWAREMicrosoftWindows NTCurrentVersion" -Name "DigitalProductId"

# Get the range we are interested in
$id = $dpid.DigitalProductId[52..(52+14)]

# Character table
$chars = "BCDFGHJKMPQRTVWXY2346789"

# Variable for the final product key
$pkey = ""

# Calculate the product key
for ($i=0; $i -le 24; $i++) {
    $c = 0

    for($j=14; $j -ge 0; $j--) {
        $c = ($c -shl 8) -bxor $id[$j]

        $id[$j] = [Math]::Floor($c / 24) -band 255

        $c = $c % 24
    $pkey = $chars[$c] + $pkey
# Insert some dashes
for($i = 4; $i -gt 0; $i--) {
    $pkey = $pkey.Insert($i * 5, "-")

Run this and you get your product key. (So no coding for you after all)

Original post

So this is the actual C# code I dug up and commented.

public static string ConvertDigitalProductID(string regPath, string searchKey = "DigitalProductID") {
    // Open the sub key i.E.: "SoftwareMicrosoftWindows NTCurrentVersion"
    var regkey = Registry.LocalMachine.OpenSubKey(regPath, false);
    // Retreive the value of "DigitalProductId"
    var dpid = (byte[])regkey.GetValue(searchKey);
    // Prepare an array for the relevant parts
    var idpart = new byte[15];

    // Copy the relevant parts of the array
    Array.Copy(dpid, 52, idpart, 0, 15);

    // Prepare the chars that will make up the key
    var charStore = "BCDFGHJKMPQRTVWXY2346789";

    // Prepare a string for the result
    string productkey = "";

    // We need 24 iterations (one for each character)
    for(int i = 0; i < 25; i++) {

        int c = 0;
        // Go through each of the 15 bytes of our dpid
        for(int j = 14; j >= 0; j--) {
            // Shift the current byte to the left and xor in the next byte
            c = (c << 8) ^ idpart[j];

            // Leave the result of the division in the current position
            idpart[j] = (byte)(c / 24);

            // Take the rest of the division forward to the next round
            c %= 24;
        // After each round, add a character from the charStore to our key
        productkey = charStore[c] + productkey;

    // Insert the dashes
    for(int i = 4; i > 0; i--) {
        productkey = productkey.Insert(i * 5, "-");

    return productkey;

You’ll have to pass it SoftwareMicrosoftWindows NTCurrentVersion as a Key, where it’ll find the DigitalProductId

At that time MS Office Products used the same algorithm, so by providing the function with the relevant registry key it could calculate those product keys as well.

You can of course refactor the function so that it takes a byte array as input.

As for today. I just tested it on my Windows 10 Machine, and it still works.

Here is a Python port of the other answer (adapted for Windows 8.1). The advantage of this over chntpw is that it will work even with drives in read-only state.


pip install python-registry


#!/usr/bin/env python
import sys
from Registry import Registry
reg = Registry.Registry("/path/to/drive/Windows/System32/config/RegBack/SOFTWARE")
# Uncomment for registry location for Windows 7 and below:
#reg = Registry.Registry("/path/to/drive/Windows/system32/config/software")
key ="MicrosoftWindows NTCurrentVersion")
did = bytearray([v.value() for v in key.values() if == "DigitalProductId"][0])
idpart = did[52:52+15]
charStore = "BCDFGHJKMPQRTVWXY2346789";
productkey = "";
for i in range(25):
  c = 0
  for j in range(14, -1, -1):
    c = (c << 8) ^ idpart[j]
    idpart[j] = c // 24
    c %= 24
  productkey = charStore[c] + productkey
print('-'.join([productkey[i * 5:i * 5 + 5] for i in range(5)]))

Here is my bash implementation. I call it works good from clonezilla. I originally posted it here

# written by Jeff Sadowski
# credit
# Pavel Hruška, Scott Skahht, and Philip M for writting
# that I got my conversion code from
# I used the comments on the sudo code from
# from-ubuntu
# by MrPaulch
# and the creator of chntpw
# Petter Nordahl-Hagen
# without which I would not be able to get the key in linux
# also the creators of ntfs-3g, linux and bash

parted -l 2>/dev/null |grep -e ntfs -e fat -e Disk|grep -v Flags
#get the first mac address that isn't a loopback address
# loopback will have all zeros
MAC=$(cat /sys/class/net/*/address|grep -v 00:00:00:00:00:00|head -n 1|sed "s/:/-/g")
if [ "$1" = "" ];then
 echo "mount the Windows share then give this script the path where you mounted it"
cd $1
# This way will work no matter what the capitalization is
next=$(find ./ -maxdepth 1 -iname windows);cd ${next}
next=$(find ./ -maxdepth 1 -iname system32);cd ${next}
next=$(find ./ -maxdepth 1 -iname config);cd ${next}
file=$(find ./ -maxdepth 1 -iname software)
#echo $(pwd)${file:1}
#Get the necissary keys
#get the version key
VERSION=$((16#$(echo -e "cat \Microsoft\Windows NT\CurrentVersion\CurrentMajorVersionNumbernqn" | chntpw -e ${file}|grep "^0x"|cut -dx -f2)))
hexPid_csv_full=$(echo $(echo -e "hex \Microsoft\Windows NT\CurrentVersion\DigitalProductIdnqn" | chntpw -e ${file}|grep "^:"|cut -b 9-55)|sed 's/ /,/g' | tr '[:u>
# get the subset 53 to 68 of the registry entry
hexPid_csv=$(echo $(echo -e "hex \Microsoft\Windows NT\CurrentVersion\DigitalProductIdnqn" | chntpw -e ${file}|grep "^:"|cut -b 9-55)|sed 's/ /,/g' | tr '[:upper:>
echo "${hexPid_csv_full}" > /custom/DigitalProductId_${MAC}.txt
#formatted output
 echo ${key:0:5}-${key:5:5}-${key:10:5}-${key:15:5}-${key:20:5}
# almost a direct conversion of c# code from
# however most of this looks similar to sudo code I found
digits=(B C D F G H J K M P Q R T V W X Y 2 3 4 6 7 8 9)
for j in {0..15};do
#Populate the Pid array from the values found in the registry
 Pid[$j]=$((16#$(echo ${hexPid_csv}|cut -d, -f $(($j+1)))))
if [ "$1" = "8+" ];then
# modifications needed for getting the windows 8+ key
 Pid[14]=$(( $(( ${Pid[14]}&247 )) | $(( $(( ${isWin8} & 2 )) * 4 )) ))
for i in {24..0};do
 for j in {14..0};do
  # Shift the current contents of c to the left by 1 byte 
  # and add it with the next byte of our id
  current=$((${Pid[$j]} + current))
  # Put the result of the divison back into the array
  # Calculate remainder of c
 # Take character at position c and prepend it to the ProductKey
if [ "$1" = "8+" ];then
# another modification needed for a windows 8+ key
 echo -n "Windows 8+ key: "
 echo -n "Windows 7- key: "
spread "${key}"
if [ "$VERSION" -gt "7" ];then
 DecodeProductKey 8+

Leave a Reply

Your email address will not be published. Required fields are marked *