【问题标题】:How to encrypt using credentials of the current Windows user in powershell for KeePass?如何在 Powershell 中为 KeePass 使用当前 Windows 用户的凭据进行加密?
【发布时间】:2018-06-07 14:15:08
【问题描述】:

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

{PASSWORD_ENC} - 加密密码:

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

(强调我的)

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

【问题讨论】:

    标签: .net powershell encryption keepass


    【解决方案1】:

    来自 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);
    

    【讨论】:

    • 如果我错了,请纠正我,因为我不是密码学专家,但这听起来像是 PowerShell SecureStrings 已经工作的方式。它只对生成它的用户和机器有益。继续做就是像$Credentials.Password | ConvertFrom-SecureString 这样的事情,其中​​$credential 是一个[PSCredential] 对象。
    • @Matt 是的,当您在没有密钥或 SecureKey 的情况下使用 ConvertTo-SecureString 和 ConvertFrom-SecureString 时,Powershell 将使用 Windows 数据保护 API (DPAPI) 来加密/解密您的字符串。这将使用与我在答案中使用的功能相同的功能,但与 KeePass 解密所需的参数不同(例如熵)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多