我需要在我的 Rails 应用程序中进行加密和解密。我正在尝试使用 ezcrypto,但每当我进行解密时,我都会收到此错误。
OpenSSL::Cipher::CipherError in ProfilesController#show
wrong final block length
需要更改什么才能停止此错误。我尝试像这样使用 openssl 的另一个实现(从我的模型中调用的方法)
def encrypt_attr(unencrypted)
c = OpenSSL::Cipher.new("aes-256-cbc")
c.encrypt
c.key = Digest::SHA1.hexdigest('pass')
e = c.update(unencrypted)
e << c.final
return e
end
def decrypt_attr(encrypted_attr)
if encrypted_attr != ""
c = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
c.decrypt
c.key = Digest::SHA1.hexdigest('pass')
d = c.update(encrypted_attr)
d << c.final
return d
end
end
它在解密时抛出完全相同的错误。我应该如何进行加密和解密而不会出现此 openssl 错误。
最佳答案
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
加密
irb(main):007:0> AesEncryptDecrypt.encryption('gurudath')
=> "rUPKObydUJd9cY9agm3Glw==\n"
解密
irb(main):008:0> AesEncryptDecrypt.decryption('rUPKObydUJd9cY9agm3Glw==')
=> "gurudath"
关于ruby-on-rails - rails 加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8556940/