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

Class Method Details

.decrypt(key, data) ⇒ String

Decrypts a string encrypted by ::encrypt

Parameters:

  • key (String)

    The key.

  • data (String)

    The encrypted data.

Returns:

  • (String)

    The unencrypted data.



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.

Parameters:

  • key (String)

    The key.

  • data (String)

    The unencrypted data.

Returns:

  • (String)

    The encrypted data.



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

Parameters:

  • passwd (String)

    The password.

  • salt (String)

    The salt.

Returns:

  • (String)

    The key.



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_saltString

Gets a random salt.

Returns:

  • (String)

    A salt.



36
37
38
# File 'lib/imp/crypto.rb', line 36

def self.rand_salt
  OpenSSL::Random.random_bytes SALTLEN
end