I'm Currently trying to get my Product key of my windows 7 installation from the registry. but for some reason DigitalProductId is coming back null. And I can't figure out why it's doing that.
I can read other values in the "NT\Current Version" just fine. like "productName" but when it comes to the digitalProductId I'm getting nothing.
here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Collections;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
byte[] results = Form1.GetRegistryDigitalProductId(Form1.Key.Windows);
string cdKey = Form1.DecodeProductKey(results);
MessageBox.Show(cdKey, "HWID()", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
public enum Key { Windows };
public static byte[] GetRegistryDigitalProductId(Key key)
{
byte[] digitalProductId = null;
RegistryKey registry = null;
switch (key)
{
case Key.Windows:
registry =
Registry.LocalMachine.
OpenSubKey(
@"SOFTWARE\Microsoft\Windows NT\CurrentVersion",
false);
break;
}
if (registry != null)
{
digitalProductId = registry.GetValue("DigitalProductId")
as byte[];
registry.Close();
}
return digitalProductId;
}
public static string DecodeProductKey(byte[] digitalProductId)
{
const int keyStartIndex = 52;
const int keyEndIndex = keyStartIndex + 15;
char[] digits = new char[]
{
'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R',
'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9',
};
const int decodeLength = 29;
const int decodeStringLength = 15;
char[] decodedChars = new char[decodeLength];
ArrayList hexPid = new ArrayList();
for (int i = keyStartIndex; i <= keyEndIndex; i++)
{
hexPid.Add(digitalProductId[i]);
}
for (int i = decodeLength - 1; i >= 0; i--)
{
if ((i + 1) % 6 == 0)
{
decodedChars[i] = '-';
}
else
{
int digitMapIndex = 0;
for (int j = decodeStringLength - 1; j >= 0; j--)
{
int byteValue = (digitMapIndex << 8) | (byte)hexPid[j];
hexPid[j] = (byte)(byteValue / 24);
digitMapIndex = byteValue % 24;
decodedChars[i] = digits[digitMapIndex];
}
}
}
return new string(decodedChars);
}
}
}
I'm new to c# and I'm trying to follow this guide. http://www.ultimateprogrammingtutorials.info/2013/05/how-to-get-windows-product-key-in-c.html
But I'm having trouble getting to work correctly.
Thanks
You can use your code as-is if you target 64-bit in your build.
Otherwise, you get directed here, and you might not find the key you're looking for:
SOFTWARE\Wow6432Node\...
So use this code if you have to target 32-bit:
var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
var reg = baseKey.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", false);
var digitalProductId = reg.GetValue("DigitalProductId") as byte[];