rails encryption/decryption

后端 未结 3 1789
遇见更好的自我
遇见更好的自我 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:12

    require 'openssl'
    require 'base64'
    
    class AesEncryptDecrypt
    
      KEY = "EncryptDecryptGurudathBN"
      ALGORITHM = 'AES-128-ECB'
    
      def self.encryption(msg)
        begin
          cipher = OpenSSL::Cipher.new(ALGORITHM)
          cipher.encrypt()
          cipher.key = KEY
          crypt = cipher.update(msg) + cipher.final()
          crypt_string = (Base64.encode64(crypt))
          return crypt_string
        rescue Exception => exc
          puts ("Message for the encryption log file for message #{msg} = #{exc.message}")
        end
      end
    
      def self.decryption(msg)
        begin
          cipher = OpenSSL::Cipher.new(ALGORITHM)
          cipher.decrypt()
          cipher.key = KEY
          tempkey = Base64.decode64(msg)
          crypt = cipher.update(tempkey)
          crypt << cipher.final()
          return crypt
        rescue Exception => exc
          puts ("Message for the decryption log file for message #{msg} = #{exc.message}")
        end
      end
    end
    

    Encryption

    irb(main):007:0> AesEncryptDecrypt.encryption('gurudath')
    => "rUPKObydUJd9cY9agm3Glw==\n"
    

    Decryption

    irb(main):008:0> AesEncryptDecrypt.decryption('rUPKObydUJd9cY9agm3Glw==')
    => "gurudath"
    

提交回复
热议问题