SAS PWENCODE有类似的R功能吗?

时间:2012-07-13 21:31:36

标签: r password-encryption

我正在尝试将当前在R代码中硬编码的密码移动到磁盘上的“加密”/编码文件中。

我想以与SAS PWENCODE程序类似的方式(http://support.sas.com/documentation/cdl/en/proc/63079/HTML/default/viewer.htm#n0ii0upf9h4a67n1bcwcesmo4zms.htmODBC Password Security in SAS)这样做。

R中有类似的东西吗?您使用什么方法将密码存储在R中,以便需要定期运行而无需人为干预的密码输入?

编辑:忘记提及:唯一与我类似的是RCurl :: base64()。

1 个答案:

答案 0 :(得分:2)

我在下面的博客文章中概述了在Windows上实现此目标的方法:

http://www.gilfillan.space/2016/04/21/Using-PowerShell-and-DPAPI-to-securely-mask-passwords-in-R-scripts/

...基本上

  1. 确保您拥有enabled PowerShell execution

  2. 将以下文本保存到名为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")
    
  3. 执行上面的脚本(右键单击>使用PowerShell运行),为密码提供有意义的名称,然后输入密码。您现在可以通过检查%USERPROFILE%/ DPAPI / passwords / [PC NAME] / [PASSWORD IDENTIFIER.txt]

  4. 中的文件来验证密码是否已加密
  5. 现在从R中运行以下代码(我将此函数保存在每个脚本开头的source的R脚本中。

    getEncryptedPassword <- function(credential_label, credential_path) {
      # if path not supplied, use %USER_PROFILE%\DPAPI\passwords\computername\credential_label.txt as default
      if (missing(credential_path)) {
        credential_path <- paste(Sys.getenv("USERPROFILE"), '\\DPAPI\\passwords\\', Sys.info()["nodename"], '\\', credential_label, '.txt', sep="")
      }
      # construct command
      command <- paste('powershell -command "$PlainPassword = Get-Content ', credential_path, '; $SecurePassword = ConvertTo-SecureString $PlainPassword; $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecurePassword); $UnsecurePassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR); echo $UnsecurePassword"', sep='')
      # execute powershell and return command
      return(system(command, intern=TRUE))
    }
    
  6. 现在,当您需要在R中提供密码时,您可以运行以下命令,而不是硬编码/提示输入密码:

    getEncryptedPassword("[PASSWORD IDENTIFIER]")
    

    例如,而不是运行ROracle命令:

    dbConnect(driver, "MYUSER", "MY PASSWORD", dbname="MYDB")
    

    您可以改为运行(我在步骤3中提供的标识符是“MYUSER_MYDB”:

    dbConnect(driver, "MYUSER", getEncryptedPassword("MYUSER_MYDB"), dbname="MYDB")
    
  7. 您可以根据需要重复步骤3以获取尽可能多的密码,并在步骤5中使用正确的标识符进行呼叫。