Module: Hoodie::Crypto
Overview
The salt needs to be unique per-use per-encrypted string. Every time a string is encrypted, it should be hashed using a new random salt. Never reuse a salt. The salt also needs to be long, so that there are many possible salts. As a rule of thumb, the salt should be at least 32 random bytes. Hoodie includes a easy helper for you to generate a random binary string, ‘String.random_binary(SIZE)`, where size is the size in bytes.
Crypto uses the AES-256-CBC algorithm by default to encrypt strings securely. It uses both an initialization vector (IV) and a salt to perform this encryption as securely as possible.
Defined Under Namespace
Modules: String Classes: Configuration
Constant Summary collapse
- SALT_BYTE_SIZE =
The default size, iterations and cipher encryption algorithm used.
64- HASH_BYTE_SIZE =
256- CRYPTERATIONS =
4096- CIPHER_TYPE =
'aes-256-cbc'
Instance Method Summary collapse
-
#decrypt(encrypted_text, password = nil, salt = nil) ⇒ String
Decrypt the given string, using the salt and password supplied.
-
#encrypt(plain_text, password = nil, salt = nil) ⇒ String
Encrypt the given string using the AES-256-CBC algorithm.
-
#salted_hash(password) ⇒ Hash
Generates a special hash known as a SPASH, a PBKDF2-HMAC-SHA1 Salted Password Hash for safekeeping.
Instance Method Details
#decrypt(encrypted_text, password = nil, salt = nil) ⇒ String
Decrypt the given string, using the salt and password supplied.
172 173 174 175 176 177 178 179 180 181 182 |
# File 'lib/hoodie/utils/crypto.rb', line 172 def decrypt(encrypted_text, password = nil, salt = nil) password = password.nil? ? Hoodie.crypto.password : password salt = salt.nil? ? Hoodie.crypto.salt : salt iv_ciphertext = Base64.decode64(encrypted_text) cipher = new_cipher(:decrypt, password, salt) cipher.iv, ciphertext = separate_iv_ciphertext(cipher, iv_ciphertext) plain_text = cipher.update(ciphertext) plain_text << cipher.final plain_text end |
#encrypt(plain_text, password = nil, salt = nil) ⇒ String
Encrypt the given string using the AES-256-CBC algorithm.
145 146 147 148 149 150 151 152 153 154 |
# File 'lib/hoodie/utils/crypto.rb', line 145 def encrypt(plain_text, password = nil, salt = nil) password = password.nil? ? Hoodie.crypto.password : password salt = salt.nil? ? Hoodie.crypto.salt : salt cipher = new_cipher(:encrypt, password, salt) cipher.iv = iv = cipher.random_iv ciphertext = cipher.update(plain_text) ciphertext << cipher.final Base64.encode64(combine_iv_ciphertext(iv, ciphertext)) end |
#salted_hash(password) ⇒ Hash
Generates a special hash known as a SPASH, a PBKDF2-HMAC-SHA1 Salted Password Hash for safekeeping.
197 198 199 200 201 202 203 204 205 206 |
# File 'lib/hoodie/utils/crypto.rb', line 197 def salted_hash(password) salt = SecureRandom.random_bytes(SALT_BYTE_SIZE) pbkdf2 = OpenSSL::PKCS5::pbkdf2_hmac_sha1( password, salt, CRYPTERATIONS, HASH_BYTE_SIZE) { salt: salt, pbkdf2: Base64.encode64(pbkdf2) } end |