How to save the password in script R in package ‘encryptr’? - r

I do that:
library(encryptr)
genkeys()
And I created the password: 0)]30l^8
password<-"0)]30l^8"
data(gp)
write.csv(gp, "gp.csv")
encrypt_file("gp.csv")
My problem is: How do I automatically enter the password on the decrypt_file("gp.csv.encryptr.bin", file_name = "gp2.csv")
I need this to decrypt many files in a short time.

Many thanks for the question. Saving a password in a script is not recommended as that defeats the purpose of encrypting a file in most circumstances. You can work around this intentional feature although it is not recommended.
password<-"0)]30l^8"
.crypt = readRDS("gp.csv.encryptr.bin") # in file
zz = file("gp2.csv", "wb") # out file
openssl::decrypt_envelope(.crypt$data, .crypt$iv, .crypt$session, key = "id_rsa", password = password) %>%
writeBin(zz)
close(zz)

Related

Error Decrypting Key in R using rsa_decrypt from openssl

I'm trying to create a JWT claim for Box in R by following these directions: https://developer.box.com/docs/construct-jwt-claim-manually
I've loaded the config file containing the publickey, privatekey, and passphrase. The second step requires decrypting the private key with the passphrase.
I'm using openssl::rsa_decrypt(data = charToRaw(privateKey), password = passphrase) to do this, but I'm getting this error: Error: OpenSSL error in rsa_ossl_private_decrypt: data greater than mod len
I'm pretty sure I'm doing something wrong with the data = charToRaw(privateKey) argument, but I'm not sure what?
I found out I was using the wrong function.
read_key(privateKey, password = passphrase) is what I was looking for.

How to use httr correctly for X-WSSE Authentification?

I´m trying to connect to the API of emarsys. They use X-WSSE as authentification method and i´m stuck and need to figure out what i am doing wrong. I tried to make the header as requested, but i don´t know where it went wrong. I´m very thankful for your comments!
install.packages("httr")
install.packages("digest")
library("httr")
library("digest")
# prepare userdata
username <- "customer001"
secretkey <- "supersecretkey"
timestamp <- format(as.POSIXlt(Sys.time(), "UTC"), "%Y-%m-%dT%H:%M:%SZ")
nonce <- digest(random(8), length=16)
# passworddigest
pwd <- paste0(nonce, timestamp, secretkey)
pwd <- digest::sha1(pwd, algo="sha1", serialize=FALSE)
pwd <- jsonlite::base64_enc(charToRaw(pwd))
URL_base <- "https://api.emarsys.net/api/v2/"
URL_endpoint <- "contact/settings"
URL <- paste0(URL_base,URL_endpoint)
# create header
header <- c(paste0('UsernameToken ',
'Username="', username, '", ',
'PasswordDigest="', pwd,'", ',
'Nonce="', nonce, '", ',
'Created="', timestamp,'"'))
# name header
names(header) <- 'X-WSSE:'
# make httr request
response <- GET(URL, add_headers(.headers = header))
response
The http-header should look like this:
X-WSSE: UsernameToken Username="customer001",
PasswordDigest="ZmI2ZmQ0MDIxYmQwNjcxNDkxY2RjNDNiMWExNjFkZA==",
Nonce="d36e3162829ed4c89851497a717f", Created="2014-03-20T12:51:45Z"
But i don´t know where i can find out, how the request from my httr-code looks and what i do different.
EDIT:
"digest::sha1(pwd, algo="sha1", serialize=FALSE)" has to be digest(pwd, algo="sha1", serialize=FALSE). Then it works.
This is kind of a comment but I can't get formatting the way it needs to be there for clarity so here it is. SO pedants can feel free to downvote this if so moved:
First, add a verbose() parameter to the GET() call to see if what you're passing is what you think it should be. I'm betting the issue is the : in the 'X-WSSEP:' value you are assigning. I also find it much easier to use named parameters to the add_headers() call so perhaps try:
GET(
url = URL,
add_headers(`X-WSSE` = header),
verbose()
)
to see if that clears this up or at least gets you a bit further.
Also: once your issues are solved and you get the access you want, consider making a pkg for the Emarsys API. If you've not made packages before it cld be a ++gd learning experience and either way it may help others.

Using R to connecting to MongoDB password with '#'

This is similar to the question here:
MongoDB password with "#" in it
However, I'm using the R package mongolite to connect so I can't apply that solution. Any recommendations on how to modify it so that it still works for the mongolite package
For example if my username is: user1, and my password is: p#ssword, how would I write:
mongodb://user1:p#ssword#myip
Thank you!
I used this structure and worked for me
newdb <- mongo(collection= "name_collection",
db = "name_db",
url = "mongodb://user:password#your_ip:port_number/name_db",
verbose = TRUE)
I just ran into this problem and solved it by escaping the # in the password by using its corresponding percent-encoding, e.g. use%40 to ecape it. So in your case:
mongodb://user1:p%40ssword#myip
should work.
Edit: I did not see you already had the answer in a comment :) The escape worked in my case so I assume you may have a mistake in either your username or password.
In your p#ssword # character is creating problem so replace it by %40 as suggested by https://stackoverflow.com/users/4455096/rapture

Validate a character as a file path?

What's the best way to determine if a character is a valid file path? So CheckFilePath( "my*file.csv") would return FALSE (on windows * is invalid character), whereas CheckFilePath( "c:\\users\\blabla\\desktop\\myfile.csv" ) would return TRUE.
Note that a file path can be valid but not exist on disk.
This is the code that save is using to perform that function:
....
else file(file, "wb")
on.exit(close(con))
}
else if (inherits(file, "connection"))
con <- file
else stop("bad file argument")
......
Perhaps file.exists() is what you're after? From the help page:
file.exists returns a logical vector indicating whether the files named by its argument exist.
(Here ‘exists’ is in the sense of the system's stat call: a file will be reported as existing only
if you have the permissions needed by stat. Existence can also be checked by file.access, which
might use different permissions and so obtain a different result.
Several other functions to tap into the computers file system are available as well, also referenced on the help page.
No, there's no way to do this (reliably). I don't see an operating system interface in neither Windows nor Linux to test this. You would normally try and create the file and get a fail message, or try and read the file and get a 'does not exist' kind of message.
So you should rely on the operating system to let you know if you can do what you want to do to the file (which will usually be read and/or write).
I can't think of a reason other than a quiz ("Enter a valid fully-qualified Windows file path:") to want to know this.
I would suggest trying checkPathForOutput function offered by the checkmate package. As stated in the linked documentation, the function:
Check[s] if a file path can be safely be used to create a file and write to it.
Example
checkmate::checkPathForOutput(x = tempfile(pattern = "sample_test_file", fileext = ".tmp"))
# [1] TRUE
checkmate::checkPathForOutput(x = "c:\\users\\blabla\\desktop\\myfile.csv")
# [1] TRUE
Invalid path
\0 character should not be used in Linux1 file names:
checkmate::check_path_for_output("my\0file.csv")
# Error: nul character not allowed (line 1)
1 Not tested on Windows, but looking at the code of checkmate::check_path_for_output indicates that function should work correctly on MS Windows system as well.

How do I prevent exposure of my password when using RGoogleDocs?

I love RGoogleDocs and use it a lot. However, I don't like entering my password all the time. Obviously I could just type the password into the R script and would never have to enter it again. But thats not viable since it means that my password would be left unencrypted on my harddrive. Furthermore I share my scripts with colleagues.
To get around the problem I came up with this.
if(exists("ps")){
print("got password, keep going")
} else {
ps <-readline(prompt="get the password in ")
}
options(RCurlOptions = list(
capath = system.file("CurlSSL", "cacert.pem",
package = "RCurl"), ssl.verifypeer = FALSE)
)
sheets.con = getGoogleDocsConnection(
getGoogleAuth("notreal#gmail.com", ps, service ="wise"))
#WARNING: this would prevent curl from detecting a 'man in the middle' attack
ts2=getWorksheets("hpv type",sheets.con)
I love using RStudio. I feel uncomfortable that it is displaying my password for any colleague in my office at the time to see. I used a fake password but look at the image. . Furthermore, if I saved a workspace my password would be saved with it and I am afraid that I would be giving it to someone else if, a few months later, when I had long forgotten about what was in it, I sent my .RData file to a colleague.
I read something general about passwords in R in an earlier post. It did not give me enough information to be able to conceal my password when using RGoogleDocs.
My approach is to set the login-name & password in the R options list
within the R startup file .Rprofile. Then my code gets the value
with getOption() and then the value is never visible or stored
in a top-level variable in globalenv(). (It could be save if
one does post-mortem debugging via dump.frames).
It is vital that the .Rprofile cannot be read by anybody other than you.
So
options(GoogleDocsPassword = c(login = 'password'))
in the .Rprofile and then
auth = getGoogleAuth()
just works as the default value for the first parameter is to look for the GoogleDocsPassword option.
D.
I had the same problem, and no real solution. The workaround I use is, I create a google account just for this purpose, with a password that I do not care about. I then share the documents that I want R to access with that account.
But if someone has an answer to the initial question I am interested as well.
Seems like uou could store the password in your options and the instead of "ps" directly use "getOption". LIkely there are better solutions though.
You could store the password in a file on you computer, encoded and all and call it with somthing like
getPassword <- function(file = location of password file){unencode(readLines(file))}
set this in your .Rprofile and use in the code
getPassword().
This doesn't store your password in any R files and you can build in checks in the file.
If you really don't want to store it anywhere, then one solution to this is not to use a variable for the password, maybe even for the google account address! Building on the linked answer, why not try
library(tcltk)
library(RGoogleDocs)
getHiddenText <- function(label = "Enter text:", symbol = "*", defaultText = ""){
wnd <- tktoplevel()
entryVar <- tclVar(defaultText)
tkgrid(tklabel(wnd, text = label))
#Entry box
tkgrid(entryBox <- tkentry(wnd, textvariable = entryVar, show = symbol))
#Hitting return will also submit text
tkbind(entryBox, "<Return>", function() tkdestroy(wnd))
#OK button
tkgrid(tkbutton(wnd, text="OK", command=function() tkdestroy(wnd)))
#Wait for user to submit
tkwait.window(wnd)
return(tclvalue(entryVar))
}
repeat {
con <- try(getGoogleDocsConnection(getGoogleAuth(
getHiddenText(
label = "Enter google account:",
symbol = "", # or set to "*" to obscure email entry
defaultText = "#gmail.com"), # a little timesaver
getHiddenText(
label = "Enter password:",
symbol = "*",
defaultText = ""),
service = "wise")))
if (inherits(con, "try-error")) {
userResponse <- tkmessageBox(
title = "Error",
message = "Couldn't connect to Google Docs. Try again?",
icon = "error", type = "yesno")
if (tclvalue(userResponse) == "no") {
stop("Unable to connect to Google Docs, user cancelled.")
}
} else { # connection successfully authenticated
break() # so escape the repeat loop
}
}
For things like this I share the google doc with a made up email address, create a google account and then use it for sharing and authorization. Thus, seperating my personal login details from what's necessasry for the script to run.
what about 2 step authentication with application specific password ?
you can use the application specific password without revealing your real one.
and you can revoke it if you want !

Resources