To run backend tasks in Rails, Sidekiq, Resque, Delayed Job, Action Job are famous.
Since I mostly build Rails applications on AWS, I often let lambda handle backend tasks.
This time, I will write about how to get the encrypted character string on Rails side with lambda (python) and decrypt it.
It is like this.
The environment is rails 5.0.
Rails MessageEncryptor is now available for ActiveSupport to encrypt strings. There is. ** This cannot be used this time. **(I will explain later)
This time, I will encrypt it by myself and decrypt it.
Encryptable.rb
module Encryptable
SECRET = 'hogehogehogehogehogehogehogehoge'
IV = 'hogehogehogehoge'
CIP_NAME = 'aes-256-cbc'
def encrypt(value)
b64data = Base64::strict_encode64(value)
cip = OpenSSL::Cipher.new(CIP_NAME)
cip.encrypt
cip.key = SECRET
cip.iv = IV
encrypted = cip.update(b64data)
encrypted << cip.final
"#{Base64::strict_encode64(encrypted)}"
end
def decrypt(value)
data = Base64::strict_decode64(value)
cip = OpenSSL::Cipher.new(CIP_NAME)
cip.decrypt
cip.key = SECRET
cip.iv = IV
decrypted = cip.update(data)
decrypted << cip.final
"#{Base64::strict_decode64(decrypted)}".encode('UTF-8','UTF-8')
end
Decryptable.py
import base64
from Crypto.Cipher import AES
SECRET = 'hogehogehogehogehogehogehogehoge'
IV = 'hogehogehogehoge'
def decrypt(encrypted_value):
data = base64.b64decode(encrypted_value)
cip = AES.new(SECRET, AES.MODE_CBC, IV)
b64_decrypted_data = cip.decrypt(data)
decrypted_data = base64.b64decode(b64_decrypted_data)
return decrypted_data
As you can see from the source of MessageEncryptor, Marshal is used for serialization. For this reason, type information etc. is added to the character string encrypted with MessageEncryptor by the marshalling method peculiar to ruby. It cannot be decrypted on the Python side.
Recommended Posts