Monday, September 2, 2013

How to store encrypted passwords in a YAML file Ruby

YAML works great for storing config information for ruby scripts. First, if you are writing ruby scripts I highly recommend storing your authentication information in an external file. Checking in auth info is a bad idea. If for whatever reason your source control system is compromised the attacker can have access to all your user names and password.

If you've tried to store any sort of non-UTF-8 password in YAML you know how painful it is to retrieve it. In fact I haven't found a way to retrieve it at all. YAML reads only UTF-8.

Encryption
The first thing you need to make sure is that you are storing the password in the correct encoding. If you use gems like 'encryptor' check the encoding of the encrypted password first:
encrypted_pass = Encryptor.encrypt(blah blah).encoding

If it is not UTF-8 you can force encoding by doing
encrypted_pass = Encryptor.encrypt(blah blah).force_encoding('UTF-8')

I like to Base64 encode and then UTF-8 encode the password out of shuber's encryptor gem. The gem by default spits out a ASCII-BIT string.

# To encrypt a fresh password to store in a file run:
Base64.encode64(Encryptor.encrypt(passwd,:key => secret_key, :algorithm => 'aes-256-ecb')).force_encoding('UTF-8')


Copy and paste the above password in the YAML file.


Decryption
# To decrypt the password from the YAML file
account_config = YAML.load_file(name_of_file.yml)
account_password = Encryptor.decrypt(Base64.decode64(account_config['password'].force_encoding('ASCII-8BIT')), :key => secret_key, :algorithm => 'aes-256-ecb')

No comments:

Post a Comment