.net - 如何在 Powershell 中为 KeePass 使用当前 Windows 用户的凭据进行加密?
问题描述
我需要编写一个脚本来加密字符串,就像在 KeePass 中加密{PASSWORD_ENC}
占位符一样:
{PASSWORD_ENC} - 加密密码:
{PASSWORD_ENC} 占位符被当前条目的密码替换为加密形式。 密码使用当前 Windows 用户的凭据加密。不应存储加密的密码,仅适用于当前用户。
(强调我的)
如何以编程方式加密字符串以获得与在 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);
推荐阅读
- django - Django 测试显示 Assertion:Error 即使断言为真
- javascript - 如何使用 testcafe CLI 选择浏览器版本
- excel - Excel VBA 对话框
- excel - 根据另一个工作表单元格值的值更改工作表中的单元格值
- shell - shell 脚本模式在数组值周围加上双引号,忽略组件中的空格分隔符
- node.js - 在 Nodejs/Postgres 中使用 AWS X-ray 跟踪 Sequelize
- spring-boot - 从 DB 读取数据后,将数据从一个写入器传递给另一个写入器
- r - mojave 上的 R studio 包具有“非零退出状态”
- html - 谷歌翻译器将文本框中的文本转换为西班牙语
- git - 我将如何创建一个 git stash 并继续使用我隐藏的文件?