class Encryption::Symmetric

Constants

AES_BLOCKSIZE

Public Instance Methods

decrypt(key, encrypted) click to toggle source
# File lib/symmetric/encryption.rb, line 19
def decrypt(key, encrypted)
  cipher = OpenSSL::Cipher::AES128.new(:CBC)
  cipher.padding = 0
  cipher.decrypt
  cipher.key = get_encryption_key(key)
  cipher.iv = encrypted[0..AES_BLOCKSIZE-1]

  unpad_buffer(cipher.update(encrypted[AES_BLOCKSIZE..encrypted.length]) + cipher.final)
end
digest(value) click to toggle source
# File lib/symmetric/encryption.rb, line 29
def digest(value)
  Digest::SHA256.digest(value)
end
encrypt(key, message) click to toggle source
# File lib/symmetric/encryption.rb, line 9
def encrypt(key, message)
  cipher = OpenSSL::Cipher::AES128.new(:CBC)
  cipher.encrypt
  cipher.key = get_encryption_key(key)
  cipher.padding = 0
  iv = cipher.random_iv

  iv + cipher.update(pad_buffer(message)) + cipher.final
end

Private Instance Methods

get_encryption_key(key) click to toggle source
# File lib/symmetric/encryption.rb, line 35
def get_encryption_key(key)
  digest(key)[0..AES_BLOCKSIZE-1]
end
pad_buffer(message) click to toggle source
# File lib/symmetric/encryption.rb, line 39
def pad_buffer(message)
  bytes_to_pad = AES_BLOCKSIZE - message.length % AES_BLOCKSIZE

  message + "\x80" + "\x00" * (bytes_to_pad - 1)
end
unpad_buffer(message) click to toggle source
# File lib/symmetric/encryption.rb, line 45
def unpad_buffer(message)
  raise OpenSSL::Cipher::CipherError unless message.match(/\x80\x00*$/)

  message.gsub(/\x80\x00*$/, '')
end