Encrypt, decrypt using Rails

前端 未结 3 1836
刺人心
刺人心 2021-01-30 10:37

I saw a while ago the possibility to decrypt and encrypt strings in rails without including any library, but I can\'t find the blog post.

I want to be able to encrypt an

相关标签:
3条回答
  • 2021-01-30 11:00

    You mean this one?: ActiveSupport::MessageEncryptor. Here is the way to reuse Rails 4 application's secret:

    crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base)
    encrypted_data = crypt.encrypt_and_sign('my confidental data')
    

    And encrypted data can be decrypted with:

    decrypted_back = crypt.decrypt_and_verify(encrypted_data)
    

    Previously Rails 3 was using secret_token configuration option and encryptor methods were encrypt decrypt.

    0 讨论(0)
  • 2021-01-30 11:11

    Rails 5 update:

    crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base[0..31])
    encrypted_data = crypt.encrypt_and_sign('my confidental data')
    

    Rails 5.x Needs a key of exactly 32 bytes.

    To verify a previously signed message with a longer key:

    crypt = ActiveSupport::MessageEncryptor.new(Rails.application.secrets.secret_key_base[0..31], Rails.application.secrets.secret_key_base)
    encrypted_data = crypt.encrypt_and_sign('my confidental data')
    

    as described in the docu

    and the discussion on this change

    0 讨论(0)
  • 2021-01-30 11:20

    Rails 5 requires that the key be 32 bytes.

    Edit to Rails 4 answer that works for Rails 5:

     key = SecureRandom.random_bytes(32)
     crypt = ActiveSupport::MessageEncryptor.new(key) 
     encrypted_data = crypt.encrypt_and_sign('my confidental data')
    

    Decrypt:

     decrypted_back = crypt.decrypt_and_verify(encrypted_data)
    
    0 讨论(0)
提交回复
热议问题