如何使用PowerShell中的当前Windows用户的凭据加密KeePass?

问题描述 投票:0回答:1

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

{PASSWORD_ENC} - 加密密码:

{PASSWORD_ENC}占位符由加密形式的当前条目的密码替换。使用当前Windows用户的凭据加密密码。不应存储加密密码,仅适用于当前用户。

(强调我的)

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

.net powershell encryption keepass
1个回答
0
投票

来自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);
© www.soinside.com 2019 - 2024. All rights reserved.