Mergent
Search…
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

1
require "openssl"
2
3
request_body = "The request body to send to Mergent"
4
5
cipher = OpenSSL::Cipher.new("aes-256-cbc")
6
cipher.encrypt
7
key = cipher.random_key
8
iv = cipher.random_iv
9
10
encrypted_request_body = cipher.update(request_body) + cipher.final
11
12
# Send the data to Mergent; see examples on the sidebar
Copied!
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

1
# Receive the data from Mergent; see examples on the sidebar
2
3
decipher = OpenSSL::Cipher.new("aes-256-cbc")
4
decipher.decrypt
5
decipher.key = key
6
decipher.iv = iv
7
8
decrypted_request_body = decipher.update(encrypted_request_body) + decipher.final
Copied!

Full Example:

1
# Great documentation around ciphers, modes, keys, ivs, and more is available
2
# here: https://ruby-doc.org/stdlib-3.0.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html
3
4
require "openssl"
5
6
#####
7
# On Task Creation
8
#####
9
10
request_body = "The request body to send to Mergent"
11
12
cipher = OpenSSL::Cipher.new("aes-256-cbc")
13
cipher.encrypt
14
key = cipher.random_key
15
iv = cipher.random_iv
16
17
encrypted_request_body = cipher.update(request_body) + cipher.final
18
19
#####
20
# On Task Webhook
21
#####
22
23
decipher = OpenSSL::Cipher.new("aes-256-cbc")
24
decipher.decrypt
25
decipher.key = key
26
decipher.iv = iv
27
28
decrypted_request_body = decipher.update(encrypted_request_body) + decipher.final
29
30
puts("Request body: #{request_body}")
31
puts("Encrypted body: #{encrypted_request_body}")
32
puts("Decrypted request body: #{decrypted_request_body}")
33
puts("")
34
puts("Are they equal?: #{request_body == decrypted_request_body}")
Copied!