How to make your secret information secure?

·

2 min read

While working on creating an access token system, I encountered a problem. That is how to make API key secure. To secure the API, we decided to encrypt API key and send the encrypted token to the other server. To decipher the token, the both two parties have a shared secret key. In this situation, AES can be a good option.

To implement encryption in Ruby on Rails, the openssl library can be used. Here's an example code to encrypt a plaintext API key along with an expiration date using AES-256-GCM encryption:

require 'openssl'
# Set the expiration date to 1 hour from now
expiration_date = Time.now + 3600

# Convert the expiration date to a string and append it to the plaintext API key
plaintext = "api-key.#{expiration_date.to_s}"

# Generate a 256-bit AES key
key = "secure256bitkeyisplacedhere"

# Encrypt the plaintext with AES-256-GCM using the shared key
cipher = OpenSSL::Cipher.new('aes-256-gcm')
cipher.encrypt
cipher.key = key
iv = cipher.random_iv
encrypted_data = cipher.update(plaintext)

To decrypt the encrypted API key on another server, the following code can be used:

cipher = OpenSSL::Cipher.new('aes-256-gcm')
cipher.decrypt
cipher.key = key
cipher.iv = iv
# cipher.auth_tag = tag
plaintext = cipher.update(encrypted_data)
# plaintext = cipher.update(encrypted_data) + cipher.final

# Extract the expiration date from the decrypted plaintext and compare it to the current time
expiration_date = Time.parse(plaintext[-19..-1])
if expiration_date > Time.now
  # The data is still valid
else
  # The data has expired
end

In the above code, iv is a random initialization vector that is used to add an additional layer of security to the encryption. The IV is a unique value that is used to initialize the encryption process, and it needs to be sent along with the encrypted API key to the other server. Without the IV, it would be much easier for an attacker to decrypt the encrypted data.

Using a random IV makes it difficult for attackers to predict the initialization vector, which adds to the overall security of the encryption. The IV can be generated using the random_iv method of the OpenSSL::Cipher class, as shown in the encryption example above.

IV must be kept secret and should not be reused for different encryption operations. The same IV should never be used twice with the same key, as it can make it easier for an attacker to crack the encryption. Therefore, it's essential to generate a new IV for each encryption operation.

Also, it is recommended that IV is sent in the request body or in separate request headers.