0

I have a question about Encrypt Decrypt in Rails and Laravel 5

Case: I want to encrypt some data in Rails and data will be decrypted sometimes in Laravel. I've already read how Laravel encrypts flow with HMAC sha256, SAE-256-CBC and do the flow in Rails. But unfortunately, Laravel can not decrypt

Here my code:

@cipher = OpenSSL::Cipher.new('aes-256-cbc')
@key = ENV['LARAVEL_APP_KEY']

...

@cipher.encrypt
@cipher.key = Base64.decode64(@key)
iv = @cipher.random_iv
@cipher.iv = iv
encrypted = @cipher.update(PHP.serialize(string)) + @cipher.final

iv = base64_encode(iv)
encrypted = base64_encode(encrypted)
mac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), iv + encrypted, Base64.decode64(@key))

hash = { iv: iv, value: encrypted, mac: mac }
base64_encode(hash.to_json)
  • The APP_KEY has already bee same between Rails and Laravel
  • Expected result: Rails Encrypt 1000, Laravel will get 1000 too
  • Real result: Rails Encrypt 1000, Laravel get the encryption (ex: eyfasffksffadsfreqw)

Please help! Many thanks!

Gufran Hasan
  • 8,910
  • 7
  • 38
  • 51

1 Answers1

0

I know this is an old question but still answering as it might help future readers just like me, Here is the working function, I only fixed the minor issue that you had in your code like sequence was wrong in OpenSSL::HMAC.hexdigest and changed base64 encode function that is not adding '/n' like Base64.encode64 (Your code helped me a lot to archive this faster).

def encrypt(value, key)
    @cipher = OpenSSL::Cipher.new('aes-256-cbc')
    @cipher.encrypt
    @cipher.key = @key
    iv = @cipher.random_iv
    @cipher.iv = iv
    encrypted = @cipher.update(PHP.serialize(value)) + @cipher.final

    iv = Base64.strict_encode64(iv)
    encrypted = Base64.strict_encode64(encrypted)
    mac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), @key, iv + encrypted)

    hash = { iv: iv, value: encrypted, mac: mac }
    return Base64.strict_encode64(hash.to_json)
end

Please note that here I am using the key that is not encoded and so I did not decode the key, so it's depends's on your implementation.

Prashant
  • 164
  • 1
  • 8