Module: RailsPipeline::SymmetricEncryptor::ClassMethods

Defined in:
lib/rails-pipeline/symmetric_encryptor.rb

Instance Method Summary collapse

Instance Method Details

#_api_keyObject



103
104
105
# File 'lib/rails-pipeline/symmetric_encryptor.rb', line 103

def _api_key
  RailsPipeline::SymmetricEncryptor._api_key
end

#_event_type_value(event_type) ⇒ Object



114
115
116
117
118
119
120
121
122
123
# File 'lib/rails-pipeline/symmetric_encryptor.rb', line 114

def _event_type_value(event_type)
  case event_type
  when :create
    RailsPipeline::EncryptedMessage::EventType::CREATED
  when :update
    RailsPipeline::EncryptedMessage::EventType::UPDATED
  when :destroy
    RailsPipeline::EncryptedMessage::EventType::DELETED
  end
end

#_key(salt) ⇒ Object



107
108
109
110
111
112
# File 'lib/rails-pipeline/symmetric_encryptor.rb', line 107

def _key(salt)
  iter = 10000
  key_len = 32
  key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(_secret, salt, iter, key_len)
  return key
end

#_secretObject



99
100
101
# File 'lib/rails-pipeline/symmetric_encryptor.rb', line 99

def _secret
  RailsPipeline::SymmetricEncryptor._secret
end

#decrypt(message) ⇒ Object

Message is an instance of EncryptedMessage



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/rails-pipeline/symmetric_encryptor.rb', line 81

def decrypt(message)
  salt = Base64.decode64(message.salt)
  key = _key(salt)
  cipher = OpenSSL::Cipher::AES256.new(:CBC)
  # Initialize for decryption
  cipher.decrypt

  # Set up key and iv
  cipher.key = key
  cipher.iv = Base64.decode64(message.iv)

  # Decrypt
  decoded = Base64.decode64(message.ciphertext)
  plaintext = cipher.update(decoded) + cipher.final

  return plaintext
end

#encrypt(plaintext, owner_info: nil, type_info: nil, topic: nil, event_type: nil) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/rails-pipeline/symmetric_encryptor.rb', line 47

def encrypt(plaintext, owner_info: nil, type_info: nil, topic: nil, event_type: nil)
  # Inititalize a symmetric cipher for encryption
  cipher = OpenSSL::Cipher::AES256.new(:CBC)
  cipher.encrypt

  # Create a random salt
  salt = OpenSSL::Random.random_bytes(16)

  # Create a PKCS5 key from the rails password
  # NOTE: suggested way of doing this is by cipher.random_key
  # and then we would store the key on the user.
  key = _key(salt)

  # Set the key and get a random initialization vector
  cipher.key = key
  iv = cipher.random_iv

  # Do the encryption
  ciphertext = cipher.update(plaintext) + cipher.final
  uuid = SecureRandom.uuid
  return RailsPipeline::EncryptedMessage.new(
    uuid: uuid,
    salt: Base64.encode64(salt),
    iv: Base64.encode64(iv),
    ciphertext: Base64.encode64(ciphertext),
    owner_info: owner_info,
    type_info: type_info,
    topic: topic,
    event_type: _event_type_value(event_type),
    api_key: _api_key,
  )
end