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

# 1. Define function for VNC encryption (DES with fixed key)
function Get-VncEncryptedPassword {
    param (
        [Parameter(Mandatory=$true)]
        [string]$Password
    )
    
    # TightVNC/VNC uses this fixed key for DES encryption
    $keyBytes = [byte[]]@(232, 74, 214, 96, 196, 114, 26, 224)
    
    # Truncate password to 8 characters (VNC limit) and pad with null bytes
    $passBytes = [System.Text.Encoding]::ASCII.GetBytes($Password)
    if ($passBytes.Length -gt 8) { $passBytes = $passBytes[0..7] }
    $paddedBytes = New-Object byte[] 8
    [Array]::Copy($passBytes, $paddedBytes, $passBytes.Length)
    
    # Set up DES encryption
    $des = [System.Security.Cryptography.DES]::Create()
    $des.Mode = [System.Security.Cryptography.CipherMode]::ECB
    $des.Padding = [System.Security.Cryptography.PaddingMode]::None
    $des.Key = $keyBytes
    $des.IV = $keyBytes # IV is not used in ECB, but initialize for safety
    
    $encryptor = $des.CreateEncryptor()
    return $encryptor.TransformFinalBlock($paddedBytes, 0, 8)
}

try {
    $encryptedBytes = Get-VncEncryptedPassword -Password $NewPassword
    Write-Host "Password encrypted successfully." -ForegroundColor Green
}
catch {
    Write-Error "Error encrypting password: $_"
    exit
}

# 3. Write to registry (for service running under Local System)
$regPath = "HKLM:\SOFTWARE\TightVNC\Server"

if (-not (Test-Path $regPath)) {
    Write-Warning "Registry path not found. Is TightVNC installed?"
    # Try alternative path for older versions or specific installations
    $regPath = "HKLM:\SOFTWARE\ORL\WinVNC3"
    if (-not (Test-Path $regPath)) {
        Write-Error "Cannot find TightVNC registry key."
        exit
    }
}

try {
    # Set the main password (Password) and the control password (ControlPassword)
    Set-ItemProperty -Path $regPath -Name "Password" -Value $encryptedBytes -Type Binary -ErrorAction Stop
    
    # Optional: You can set the administrative password to the same value
    # Set-ItemProperty -Path $regPath -Name "ControlPassword" -Value $encryptedBytes -Type Binary
    
    Write-Host "Registry password has been changed." -ForegroundColor Green
}
catch {
    Write-Error "Failed to write to registry. Are you running as Administrator?"
    exit
}

# 4. Restart the service for changes to take effect
$serviceName = "tvnserver" # TightVNC service name
if (Get-Service $serviceName -ErrorAction SilentlyContinue) {
    Write-Host "Restarting TightVNC service..."
    Restart-Service -Name $serviceName -Force
    Write-Host "Done. New password is now active." -ForegroundColor Cyan
} else {
    Write-Warning "Service '$serviceName' not found. It might be running as an application, not a service."
    Write-Host "If it's running as an application, you need to restart it manually."
}
