Visual Studio License Key Management


  1. 說明

筆記如何從 regedit 檢視與管理 Visual Studio 使用的 License Key。

logo

說明

Visual Studio 的 License Key 是以機碼的方式儲存在 Registry。

路徑規則如下:

HKEY_CLASSES_ROOT\Licenses\product.GUID\product.MPC
Product GUID MPC
Visual Studio 2017 Enterprise 5C505A59-E312-4B89-9508-E162F8150517 08860
Visual Studio 2017 Professional 5C505A59-E312-4B89-9508-E162F8150517 08862
Visual Studio 2019 Enterprise 41717607-F34E-432C-A138-A3CFD7E25CDA 09260
Visual Studio 2019 Professional 41717607-F34E-432C-A138-A3CFD7E25CDA 09262
Visual Studio 2022 Enterprise 1299B4B9-DFCC-476D-98F0-F65A2B46C96D 09660
Visual Studio 2022 Professional 1299B4B9-DFCC-476D-98F0-F65A2B46C96D 09662

而儲存在 Registry 的 License Key 會加密為 Binary,必須搭配 System.Security.Cryptography 使用 ProtectedData.Unprotect 的方式解密 Licence Key。

以下節錄 terjew VSKeyExtractor | GitHub 的處理 Sample Code:

var product = new Product("Visual Studio 2022 Professional", "1299B4B9-DFCC-476D-98F0-F65A2B46C96D", "09662");

var encrypted = Registry.GetValue($"HKEY_CLASSES_ROOT\\Licenses\\{product.GUID}\\{product.MPC}", "", null);
if (encrypted == null) return;
try
{
    var secret = ProtectedData.Unprotect((byte[])encrypted, null, DataProtectionScope.CurrentUser);
    var unicode = new UnicodeEncoding();
    var str = unicode.GetString(secret);
    foreach (var sub in str.Split('\0'))
    {
        var match = Regex.Match(sub, @"\w{5}-\w{5}-\w{5}-\w{5}-\w{5}");
        if (match.Success)
        {
            Console.WriteLine($"{product.Name} key: {match.Captures[0]}");
        }
    }
}
catch (Exception) { }

相同的操作改為 PowerShell Script

# Accessing the registry value
$regPath = "Registry::HKCR\Licenses\$($product.GUID)\$($product.MPC)"

$productName = "Visual Studio 2022 Professional"
$productGUID = "1299B4B9-DFCC-476D-98F0-F65A2B46C96D"
$productMPC = "09662"

# Retrieve encrypted data from registry
$registryPath = "Registry::HKCR\Licenses\$productGUID\$productMPC"
$encrypted = Get-ItemPropertyValue -Path $registryPath -Name '(default)'


# Decrypt the data
Add-Type -AssemblyName System.Security
$secret = [System.Security.Cryptography.ProtectedData]::Unprotect(
    $encrypted, $null, 
    [System.Security.Cryptography.DataProtectionScope]::CurrentUser)

# Convert to Unicode string
$unicode = New-Object System.Text.UnicodeEncoding
$str = $unicode.GetString($secret)

# Search for product key pattern
$str -split '\0' | ForEach-Object {
    if ($_ -match "\w{5}-\w{5}-\w{5}-\w{5}-\w{5}") {
        Write-Output "$($productName) key: $($matches[0])"
    }
}

如果想要更改所使用的 License Key 也可以透過 Registry 的操作來達成,而不需要重新安裝 Visual Studio 😀

而如果是 Visual Studio 的試用期,可以參考 beatracker 所分享的 VSCELicense | GitHub 的 PowerShell Script。