Passwords (and username) in scripts

Hello,

What do people do to manage username and passwords in scripts?
Thoughts on best practices?

To remain secure I’ve been playing with storing them on a password protected encrypted disk image, that if not mounted the script fails with an error gracefully.

So what do you use/do? Thoughts?

Thanks

The best way to store passwords is storing the result of an (un)resolvable algorithm. There are two ways you can use passwords

Using password to grant privileges
For instance when my password is “M@cscr1pt3r” I should never stored it like that in my script but I would use an handler that creates an SHA1 hash like this:

do shell script "/bin/echo -n 'M@cscr1pt3r' | openssl dgst -sha1"

When a user needs to type his password you don’t match his password but you do match the two hashes. This way the password itself is never stored somewhere in the script. The only danger of using a do shell script is that when someone is monitoring the processes the argument of echo is shown, which is the password.

Using a password to store it somewhere, like a keychain
If you want a script/applet that stores password to resolve the best way is to create an algorithm yourself which is resolvable. This way the script itself, again, doesn’t contain a password. Here a simple example using an algorithm using a key. When you vary the key it’s very hard to resolve passwords for others even using an algorithm that is so easy as below.

set encryptedCode to encrypt("thiskey", "Hello World!")
--now store the value encryptedCode to a file or something

--if you want to use it later, you can only decrypt it with the same key as you encrypted it
decrypt("thiskey", encryptedCode)

on encrypt(theKey, theString)
	set keyUCodes to id of theKey
	set strUCodes to id of theString
	set keyOffset to 1
	set keyLen to count theKey
	repeat with i from 1 to count strUCodes
		set item i of strUCodes to (item i of strUCodes) + (item keyOffset of keyUCodes)
		if keyOffset is keyLen then
			set keyOffset to 1
		else
			set keyOffset to keyOffset + 1
		end if
	end repeat
	return string id strUCodes
end encrypt

on decrypt(theKey, theString)
	set keyUCodes to id of theKey
	set strUCodes to id of theString
	set keyOffset to 1
	set keyLen to count theKey
	repeat with i from 1 to count strUCodes
		set item i of strUCodes to (item i of strUCodes) - (item keyOffset of keyUCodes)
		if keyOffset is keyLen then
			set keyOffset to 1
		else
			set keyOffset to keyOffset + 1
		end if
	end repeat
	return string id strUCodes
end decrypt