Mergent
Search
⌃K
Links

Encrypting Data

Sending sensitive data that Mergent should not have access to? This is a short guide on how to encrypt your Tasks using AES-256-CBC. This same process applies to Schedules, too.
Though the example code below is in Ruby, you can apply the same concepts and best practices in any language to encrypt the request body before sending it to Mergent.

Choosing an encryption algorithm

AES is the most popular and broadly used symmetric encryption standard today, so that's what we're going to use in this guide. Specifically, we'll be using AES-256-CBC.

Encrypt the request body

require "openssl"
request_body = "The request body to send to Mergent"
cipher = OpenSSL::Cipher.new("aes-256-cbc")
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv
encrypted_request_body = cipher.update(request_body) + cipher.final
# Send the data to Mergent; see examples on the sidebar
Don't forget to store your key+ iv so that you can decrypt the request body later. Some quick rules of thumb:
  • Store the key somewhere safe and use the same key for every request
  • Create a new iv before every request and store it where you deem fit (often in your database)

Decrypt the webhook body

# Receive the data from Mergent; see examples on the sidebar
decipher = OpenSSL::Cipher.new("aes-256-cbc")
decipher.decrypt
decipher.key = key
decipher.iv = iv
decrypted_request_body = decipher.update(encrypted_request_body) + decipher.final

Full Example:

# Great documentation around ciphers, modes, keys, ivs, and more is available
# here: https://ruby-doc.org/stdlib-3.0.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html
require "openssl"
#####
# On Task Creation
#####
request_body = "The request body to send to Mergent"
cipher = OpenSSL::Cipher.new("aes-256-cbc")
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv
encrypted_request_body = cipher.update(request_body) + cipher.final
#####
# On Task Webhook
#####
decipher = OpenSSL::Cipher.new("aes-256-cbc")
decipher.decrypt
decipher.key = key
decipher.iv = iv
decrypted_request_body = decipher.update(encrypted_request_body) + decipher.final
puts("Request body: #{request_body}")
puts("Encrypted body: #{encrypted_request_body}")
puts("Decrypted request body: #{decrypted_request_body}")
puts("")
puts("Are they equal?: #{request_body == decrypted_request_body}")