Reputation: 505
I am using 'crypto-js' package in front-end to encrypt values like this:
import CryptoJS from 'crypto-js';
var value_to_encrypt = '1-2345-689'
var encrypted_value = CryptoJS.AES.encrypt(value_to_encrypt, 'my_secret_key').toString()
==> 'U2FsdGVkX1/JWm47UWAgxMKyf2qC6EukAtk0pZbW3pk='
For backend that i am using Rails OpenSSL like this:
cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
cipher.encrypt
cipher.key = 'my_secret_key'
text = cipher.update("1-2345-689") + cipher.final
encrypted_value = Base64.strict_encode64(text)
==> 'pBTaRw/fZTRkrw4THDCGLQ=='
I found few solutions but they all suggested to use 128bit key and iv for encryption in the front-end which is not possible at this stage because i already have a lot of records saved using the same encryption method.
Can anyone please suggest what would be rails equivalent to that method?
Upvotes: 1
Views: 2243
Reputation: 505
It is not possible to encrypt using key & iv and decrypt it without using them (and vice versa). I had to decrypt the old encrypted data and encrypt that again using iv and key.
In Front-end (reactJs):
import CryptoJS from 'crypto-js';
const iv = CryptoJS.enc.Base64.parse(INITIALIZATION_VECTOR)
const key = CryptoJS.enc.Hex.parse(ENCRYPTION_KEY)
encrypted_value = CryptoJS.AES.encrypt(input, key, {mode: CryptoJS.mode.CBC, iv : iv}).toString()
decrypted_value = CryptoJS.AES.decrypt(input, key, {mode: CryptoJS.mode.CBC, iv : iv}).toString(CryptoJS.enc.Utf8)
In Back-end (Ruby on Rails):
iv = Base64.decode64(INITIALIZATION_VECTOR)
key = [ENCRYPTION_KEY].pack("H*")
cipher = OpenSSL::Cipher::Cipher.new('aes-128-cbc')
cipher.encrypt
cipher.key = key
cipher.iv = iv
text = cipher.update(plain_text) + cipher.final
encrypted_text = Base64.strict_encode64(text)
Upvotes: 2