如何在 KeePass 的 powershell 中使用当前 Windows 用户的凭据进行加密?

How to encrypt using credentials of the current Windows user in powershell for KeePass?

我需要编写一个脚本来加密字符串,就像 {PASSWORD_ENC}placeholder 在 KeePass 中加密一样:

{PASSWORD_ENC} – Encrypting Passwords:

The {PASSWORD_ENC} placeholder is replaced by the password of the current entry in encrypted form. The password is encrypted using credentials of the current Windows user. The encrypted password should not be stored and only works for the current user.

(强调我的)

如何以编程方式加密字符串以获得与我在 KeePass 中获得的密码相同的加密密码?

来自 KeePass 源代码 (\KeePassLib\Utility\StrUtil.cs)

private static readonly byte[] m_pbOptEnt = { 0xA5, 0x74, 0x2E, 0xEC };

public static string EncryptString(string strPlainText)
{
    if(string.IsNullOrEmpty(strPlainText)) return string.Empty;

    try
    {
        byte[] pbPlain = StrUtil.Utf8.GetBytes(strPlainText);
        byte[] pbEnc = ProtectedData.Protect(pbPlain, m_pbOptEnt,
            DataProtectionScope.CurrentUser);

#if (!KeePassLibSD && !KeePassRT)
        return Convert.ToBase64String(pbEnc, Base64FormattingOptions.None);
#else
        return Convert.ToBase64String(pbEnc);
#endif
    }
    catch(Exception) { Debug.Assert(false); }

    return strPlainText;
}

幸运的是,我们可以在 PowerShell 中使用 .NET 成员并做同样的事情:

[System.Reflection.Assembly]::LoadWithPartialName('System.Security') | Out-Null;
[byte[]] $m_pbOptEnt = @(0xA5,0x74,0x2E,0xEC);
$plainBytes = [System.Text.Encoding]::UTF8.GetBytes( "my super strong password is 123456" );
$cipherBytes = [System.Security.Cryptography.ProtectedData]::Protect($plainBytes, $m_pbOptEnt, [System.Security.Cryptography.DataProtectionScope]::CurrentUser);
$cipherPw = [System.Convert]::ToBase64String($cipherBytes);