How to hide/asterisk a part of the code in R? - r

I have put in a password inside my code in Rstudio and I just want to somehow make it unclear so when I show my code to someone they don't see the password. Any suggestions for how to do this?
Thanks much

you should make a new R script (let's call it login_credentials.R) and store your password there
username <- "username_here"
password <- "password_here"
Once you save that, you can then load that script using source()
This will load the username and password variables.
source(login_credentials.R)
> username
[1] "username_here"
> password
[1] "password_here"
login_function(username,password)

You can obscure your password in the source file.
You can run something like
dput(charToRaw("Password"))
# as.raw(c(0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64))
to get numeric dump of your password. Then you can include in your script
pwd <- as.raw(c(0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64))
login("username", rawToChar(pwd))
That will at least make it less-human-readable and there won't be a variable in the environment browser with the text value (at least I think, i'm not sure how RStudio displays raw data).

You could create a .Renviron file in either your home directory or your project directory, where you store info like this in an environmental variable for use in your R scripts.
If this is the content of ~/.Renviron or /path/to/my/project/.Renviron:
YO=secretsecret
Then you can retrieve secretsecret via Sys.getenv("YO"). I wrote up how to do this for API authentication here.
Note: It can be very important to make sure your .Renviron file ends with a line break! Also, you'll need to restart R or Rstudio before this takes effect. Read up on R startup for more general info.

getPass package would be helpful in your case. This package has a function getPass() which is similar to readline(), the only differnce is that user's text is not printed as it is typed.
For example, consider that the following command creates connection to a database where you normally type the username and password.
Connection <- dbConnect(driver, connection_parameters, UserName, Password)
Try replacing the password with getPass() function:
library(getPass)
Connection <- dbConnect(driver, connection_parameters, UserName, getPass())
So whenever you run this line of code, you would see a popup window asking you to enter ur password. The password would not displayed as you type, but it would be masked as dots (or asterisk).
Password PopUp window
Though this requires you to enter the password every time you run, it at least gives you the ability to mask passwords.
Arguments for the function would be:
getPass(msg = "PASSWORD: ", noblank = FALSE, forcemask = FALSE)

A slightly more secure solution would be to store a hash of your password. This can be achieved with the digest function:
> digest::digest("password")
[1] "380796939c86c55d6aa8ea8c941f7652"
This implements the MD5 hash which is a one way cryptographic function and the original password can't be retrieved from this hash, i.e. there is no inverse function.
You will then need to modify the part of your code where you enter the password, hashing the entered password:
# Username and password part of code
username <- "username_here"
password_hash <- "380796939c86c55d6aa8ea8c941f7652"
...
# Password testing part of code
if (digest::digest(user_password_input) == password_hash){
"password_correct"
}else{
"password_incorrect"}
where user_password_input is a variable containing the entered password. The hashed password is secure because even if someone has your hashed password, they can't use it to get past the password verification. If they do enter the hash of you password it will be re-hashed and different to the password_hash variable.
Using hashes is good practice as your actual passwords are never stored in the code and the hashes by themselves are no use.

Related

Password decryption with known salt and dictionary

We are migrating a company we acquired a lot of kiosk hardware assets from that are in the field. Since the company was suffering, we are stuck with some issues in migrating the locations fingerprints, usernames and passwords without any implementation docs. Luckily, most of the passwords used are numeric 4-6 PIN or a common used word. I'm stuck with trying to figure out what format the password is hashed in and hopefully can decipher it from there using a dictionary for the majority of the passwords. I have the following format:
"password": "ce62f0002776890507c4050a3b76c064d3d24328aea52a08633b726d352532dc",
"salt": "JUQLSPOYGFURMGSDRYWIWBIWP",
The password above is "password". Hopefully this helps in finding the format.
If it is a hash, looks like a hash, possibly HMAC-SHA256 from the length, you need to run a password cracking program. You should be able to recover well over 90% but most likely not all.
On my laptop I can run a 20 byte password through SHA-512 and compare in under 1us so with just a SHA-512 hash I can try 1,000,000 passwords a second.
You can make a list to check but there are already good lists, see below.
For more information see:
Password list at SecLists.
Infosec password-cracking-tools
Arstechnica How I became a password cracker.
You can implement the old hashing method in your new code. When the password matches (i.e. the one the partner sends) you can then store it in your new format (essentually accepting both). This saves you the need to crack the existing passwords.
For this to work you do need to know how the passwords are hashed and what formatis used, lucikly this seems to be fairly easy (Java sample):
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write("password".getBytes(StandardCharsets.US_ASCII));
bos.write("JUQLSPOYGFURMGSDRYWIWBIWP".getBytes(StandardCharsets.US_ASCII));
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] out = md.digest(bos.toByteArray());
System.out.println("hex = " + new HexBinaryAdapter().marshal(out).toLowerCase());
Produces (i.e. concatenate password bytes and salt bytes, non-iteratively calculate SHA256 and convert to hex) the expected hash:
hex = ce62f0002776890507c4050a3b76c064d3d24328aea52a08633b726d352532dc

get a value from ini file and decrypt it in powerbuilder script

Iam working in powerbuilder and i made two functions the first function called of_enc() for encrypt a string and the second function called of_dec() for decrypt, i encrypet a value in inifile by using the encryption function, the value is encrypted succssfully by using SetProfileString (ls_inifile, "Database", "DBPass", of_enc("password"))
now after that i need to decrypt the value in another window by usingof_dec() but i can't access the ecrypted value in the inifile . any idea on how to implement that?
password = ProfileString(ls_inifile, "Database", "DBPass", "")
password = of_enc(password)
*** Note that this function can only return a string which has a maximum length of 4096 characters.
i think i found what i am looking for . this statement is accessing the stored value in the inifile and working fine with the decryption function:
of_dec(ProfileString(ls_inifile, "Database", "DBPass",""))

Password Digest authentication in WSE3

I was able to implement the method AuthenticateToken and authenticate the user when the given password is in plain text.
Is it possible to authenticate the user when the given password is hashed (Passworddigest)? If so, please shed some light. Thanks in advance.
I found the solution. Yes, it is possible to authenticate the user when the password in SOAP header is PasswordDigest.
No change in the AuthenticateToken implementation; implementation is same (returning the original password string) for both plain text and hashed password.
During debugging, I learnt that the following line in "ComputePasswordDigest(byte[] nonce, DateTime created, string secret)" method from the "Microsoft.Web.Services3.Security.Tokens.UsernameToken" object, was causing the issue to not compute the correct password digest.
byte[] bytes = Encoding.UTF8.GetBytes(XmlConvert.ToString(created.ToUniversalTime(), "yyyy-MM-ddTHH:mm:ssZ"));
I have defined the same method locally and changed the above line as follows to change the format to include milliseconds "yyyy-MM-ddTHH:mm:ss.fffZ".
And implement the "VerifyHashedPassword(UsernameToken token, string authenticatedPassword)" method from the object "Microsoft.Web.Services3.Security.Tokens.UsernameTokenManager" to call my local method instead of "ComputePasswordDigest(byte[] nonce, DateTime created, string secret)" method from "Microsoft.Web.Services3.Security.Tokens.UsernameToken" object. Now, it works like a charm.
byte[] bytes = Encoding.UTF8.GetBytes(XmlConvert.ToString(created.ToUniversalTime(), "yyyy-MM-ddTHH:mm:ss.fffZ"));

TCL code that can encrypt and decrypt a string

I need a piece of code that defines functions which can encrypt and decrypt a piece of string. What I basically want is that the string should not be visible to third-party users, so that when the string originates in one file, it is converted to, say, an integer value using the encrypt function and then it is passed as parameter to another file. There the decrpyt function then decrypts it back and uses the string to perform actions on it.
Any suggestions or already available codes will be just fine!
Please help me out. Thanks!
Install tcllib. There are several standard encryption algorithms implemented in tcllib.
The following encryption algorithms are available:
blowfish: http://tcllib.sourceforge.net/doc/blowfish.html
aes: http://tcllib.sourceforge.net/doc/aes.html
des (including triple des): http://tcllib.sourceforge.net/doc/des.html
rc4: http://tcllib.sourceforge.net/doc/rc4.html
The des package in Tcllib should do what you want. It's pretty easy to use:
package require des
set key "12345678"; # Must be 8 bytes long
set msg "abcde"
##### ENCRYPTION
set encryptedMsg [DES::des -dir encrypt -key $key $msg]
# $encryptedMsg is a bunch of bytes; you'll want to send this around...
##### DECRYPTION
set decryptedMsg [DES::des -dir decrypt -key $key $encryptedMsg]
puts "I got '$decryptedMsg'"
Note that DES will pad the message out to a multiple of 8 bytes long.
Please visit the TCL/TK homepage e.g
here:http://wiki.tcl.tk/900
That's just one way of doing it. There will be much more, I'm sure.

Sending encrypted text in Url

I have a very simple (rather stupid) question, I hope someone can clear my mind on this :)
I want to send an email to my site user once he clicks a button. This email will contain a link with the userID of a user in the link URL (as query param of a link).
Once the user clicks this email link, my server side code will parse and decrypt the userID query string key to get the user ID and perform some action on it.
I cannot use base64 encoding as it can be reversed and 'hackers' can get to know the real userID. I have to encrypt the ID but when I am using AES alogrithms for encryption, the encrypted text is not "understandable" by the browser, ie I cannot pass the encrypted userId text as a part of the URL because it contains un-encoded characters like "/" which the browser cannot by pass. One option I can think of is to base64 encode the encrypted text once I send it across via URL. Then I can bease64 decode and decyrpt it.
Is this approach better than using Uri.EscapeDataString() on the encyrpted text?
You should continue to base64 encode the AES data, as at that point it is likely binary rather than a string that can be escaped. You should also check that you are using url safe base64 encoding.
Use a one-way hash like SHA1 or MD5, and use JavaScript to send the values as encrypted. Then, if a hacker intercepts the request, they would only have the hashes and not the actual values. They could still send the hashes to login, though; one solution is to include a JavaScript parameter (generated via your server-side language) based on IP (but not possible for a hacker to find the formula for), and use it to salt the username and password hashes.
Then on server-side you would do (in PHP, in this case):
$ipHash = sha1("random" . $_SERVER['REMOTE_ADDR'] . "salt_here10381") // place this as a hidden element in the form and use it in the JavaScript to calculate the hash
$userHash = $_POST['userHash'];
$passwordHash = $_POST['passwordHash']
// TODO: Escape $ipHash, $userHash, $passwordHash
$results = mysqli->query("SELECT * FROM `users` WHERE SHA1(CONCAT('" . $ipHash . "', `user`)) ='$userHash' AND SHA1(CONCAT('" . $ipHash . "', `password`)) = " '$passwordHash'");
Then, if a hacker wanted to login with the hash and username they found, they would need the same IP of the user originally logging in whose credentials were intercepted.
Note that this assumes you have passwords stored in your database as plain-text, which you should never do.
For hashing with SHA1, on client-side, take a look at this.
To answer your specific question (I see I got a bit off topic, oops,) it would be acceptable to base64encode the hashes when you send them to the server. If possible, try to send it as POST data and save it in a cookie or session variable.
I think of a simple solution you try to generate a random number(make it as a key) and for the encryption use some simple technique of yourself like XOR 'ing the ASCII value of the characters in the user name with the key that you have generated .so the long random key results in a greater result.
When creating the email you need to encrypt the user ID, then base64 encode it, then URL encode it. Put this as the userID param in the link.
When decrypting the email you do the same in reverse; get the userID param, URL decode it, base64 decode it then decrypt it.
Remember to use a different intitialisation vector every time you encode a user ID. You will need to put the initialisation vector in the emailed link as a URL parameter too in order to decrypt it.

Resources