rails encryption/decryption

后端 未结 3 1780
遇见更好的自我
遇见更好的自我 2021-02-06 06:01

i need to do encryption and decryption in my rails app. Im trying to use ezcrypto, but whenever i do decryption i get this error.

OpenSSL::Cipher::CipherError in         


        
3条回答
  •  一整个雨季
    2021-02-06 06:19

    I know that the documentation is pretty sparse for Ruby's openssl package. However, if you would like to use cipher-block chaining, here is a brief snippet of code that outlines how to use the AES-256-CBC cipher:

    require 'openssl'
    
    # your data
    raw  = 'the data to be encrypted goes here'
    pwd  = 'secret'
    salt = OpenSSL::Random.random_bytes(8)
    
    # prepare cipher for encryption
    e = OpenSSL::Cipher.new('AES-256-CBC')
    e.encrypt
    # next, generate a PKCS5-based string for your key + initialization vector 
    key_iv = OpenSSL::PKCS5.pbkdf2_hmac_sha1(pwd, salt, 2000, e.key_len+e.iv_len)
    key = key_iv[0, e.key_len]
    iv  = key_iv[e.key_len, e.iv_len]
    
    # now set the key and iv for the encrypting cipher
    e.key = key
    e.iv  = iv
    
    # encrypt the data!
    encrypted = '' << e.update(raw) << e.final
    p encrypted
    
    # and now we prepare to decrypt
    d = OpenSSL::Cipher.new('AES-256-CBC')
    d.decrypt
    # now set the key and iv for the decrypting cipher
    # this assumes that the password, salt, and iv are known,
    # so then you would be able to generate the key as per above
    d.key = key
    d.iv  = iv
    
    # decrypt the data!
    decrypted = '' << d.update(encrypted) << d.final
    p decrypted
    

    This snippet is taken pretty much verbatim from the Japanese (original?) version of the Ruby standard library documentation on openssl. However, it does raise a few questions for you and your application design:

    1. You need to save the salt value. This is used along with the password to generate the key (you do not need to save the key).
    2. You need to save the iv initialization vector. This is used to start the very first block in the cipher-block chain. There is no need to encrypt this value, but this value should be generated for each and every message you encrypt.

    Good luck!

提交回复
热议问题