编辑:以下功能现在可以在我的R包
keyringr中使用.Keyringr包也具有类似的功能来访问Gnome Keyring和macOS Keychain.
—
如果您使用的是Windows,则可以使用PowerShell执行此操作.请参阅下面的博文.
从本质上讲…
>确保你有enabled PowerShell execution.
>将以下文本保存到名为EncryptPassword.ps1的文件中:
# Create directory user profile if it doesn't already exist.
$passwordDir = "$($env:USERPROFILE)\DPAPI\passwords\$($env:computername)"
New-Item -ItemType Directory -Force -Path $passwordDir
# Prompt for password to encrypt
$account = Read-Host "Please enter a label for the text to encrypt. This will be how you refer to the password in R. eg. MYDB_MYUSER
$SecurePassword = Read-Host -AsSecureString "Enter password" | convertfrom-securestring | out-file "$($passwordDir)\$($account).txt"
# Check output and press any key to exit
Write-Host "Press any key to continue..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
>执行上面的脚本(右键单击>使用PowerShell运行),为密码提供有意义的名称,然后输入密码.您现在可以通过检查%USERPROFILE%/ DPAPI / passwords / [PC NAME] / [PASSWORD IDENTIFIER.txt]中的文件来验证密码是否已加密
>现在从R中运行以下代码(我将此函数保存在每个脚本开头的I source的R脚本中.
getEncryptedPassword
# if path not supplied,use %USER_PROFILE%\DPAPI\passwords\computername\credential_label.txt as default
if (missing(credential_path)) {
credential_path
}
# construct command
command
# execute powershell and return command
return(system(command,intern=TRUE))
}
>现在,当您需要在R中提供密码时,可以运行以下命令,而不是硬编码/提示输入密码:
getEncryptedPassword("[PASSWORD IDENTIFIER]")
例如,而不是运行ROracle命令:
dbConnect(driver,"MYUSER","MY PASSWORD",dbname="MYDB")
你可以改为运行它(我在步骤3中提供的标识符是“MYUSER_MYDB”:
dbConnect(driver,getEncryptedPassword("MYUSER_MYDB"),dbname="MYDB")
>您可以根据需要重复步骤3以获取尽可能多的密码,并在步骤5中使用正确的标识符进行呼叫.