sql >> Base de Datos >  >> RDS >> Oracle

Cifre la contraseña en R:para conectarse a Oracle DB mediante RODBC

EDITAR:La siguiente funcionalidad ahora está disponible en mi paquete R keyringr. El paquete keyringr también tiene funciones similares para acceder a Gnome Keyring y macOS Keychain.

---

Si está usando Windows, puede usar PowerShell para hacer esto. Vea mi publicación de blog a continuación.

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

Esencialmente...

  1. Asegúrese de haber habilitado la ejecución de PowerShell.

  2. Guarde el siguiente texto en un archivo llamado 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. Ejecute el script anterior (haga clic con el botón derecho> Ejecutar con PowerShell), proporcione un nombre significativo para la contraseña y escriba la contraseña. Ahora puede verificar que la contraseña se haya cifrado consultando el archivo en %PERFIL DE USUARIO%/DPAPI/contraseñas/[NOMBRE DE PC]/[IDENTIFICADOR DE CONTRASEÑA.txt]

  4. Ahora ejecute el siguiente código desde R (tengo esta función guardada en un script de R que obtengo al comienzo de cada script).

    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))
    }
    
  5. Ahora, cuando necesite proporcionar una contraseña en R, puede ejecutar el siguiente comando en lugar de codificar/solicitar la contraseña:

    getEncryptedPassword("[PASSWORD IDENTIFIER]")
    

    Por ejemplo, en lugar de ejecutar el comando ROracle:

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

    Puede ejecutar esto en su lugar (el identificador que proporcioné en el Paso 3 es "MYUSER_MYDB":

    dbConnect(driver, "MYUSER", getEncryptedPassword("MYUSER_MYDB"), dbname="MYDB")
    
  6. Puede repetir el Paso 3 para tantas contraseñas como sea necesario y simplemente llamarlas con el identificador correcto en el Paso 5.