Module: Imp::Crypto
- Defined in:
- lib/imp/crypto.rb
Overview
Contains methods for easily interfacing with ruby’s encryption algorithms. Uses 256 bit AES in CBC mode with keys generated by PBKDF2 using SHA1 and 10 000 iterations.
Constant Summary collapse
- KEYLEN =
The length of the key to use. This module used AES-256, which has a key length of 32 bytes.
32- BLOCK_SIZE =
The block size of the cipher. As this module uses AES, this is 16 bytes.
16- SALTLEN =
The length of the salts to generate. The length is used as that of the key.
KEYLEN- ITER =
The iteration of the PBKDF2 algorim to go through.
10_000- MODE =
The mode of AES to use.
:CBC
Class Method Summary collapse
-
.decrypt(key, data) ⇒ String
Decrypts a string encrypted by ::encrypt.
-
.encrypt(key, data) ⇒ String
Encrypts a string.
-
.get_key(passwd, salt) ⇒ String
Delegates key generation to PBKDF2.
-
.rand_salt ⇒ String
Gets a random salt.
Class Method Details
.decrypt(key, data) ⇒ String
Decrypts a string encrypted by ::encrypt
60 61 62 63 64 65 66 67 |
# File 'lib/imp/crypto.rb', line 60 def self.decrypt(key, data) cipher = OpenSSL::Cipher::AES.new(KEYLEN * 8, MODE) cipher.decrypt cipher.iv = data.byteslice 0...BLOCK_SIZE cipher.key = key cipher.update(data.byteslice BLOCK_SIZE..-1) + cipher.final end |
.encrypt(key, data) ⇒ String
Encrypts a string. The result is the IV, followed by the actual encrypted string.
46 47 48 49 50 51 52 53 |
# File 'lib/imp/crypto.rb', line 46 def self.encrypt(key, data) cipher = OpenSSL::Cipher::AES.new(KEYLEN * 8, MODE) cipher.encrypt iv = cipher.random_iv cipher.key = key iv + cipher.update(data) + cipher.final end |
.get_key(passwd, salt) ⇒ String
Delegates key generation to PBKDF2
29 30 31 |
# File 'lib/imp/crypto.rb', line 29 def self.get_key(passwd, salt) OpenSSL::PKCS5.pbkdf2_hmac_sha1(passwd, salt, ITER, KEYLEN) end |
.rand_salt ⇒ String
Gets a random salt.
36 37 38 |
# File 'lib/imp/crypto.rb', line 36 def self.rand_salt OpenSSL::Random.random_bytes SALTLEN end |