我试图将一些在 CBC 模式下使用 AES 265 加密数据的 ruby 代码转换为 php,但它不起作用,转换后的 php 代码返回一个空字符串。这是我所拥有的:
红宝石:
require 'openssl'
module AESCrypt
def self.encrypt(message, password)
Base64.encode64(self.encrypt_data(message.to_s.strip, self.key_digest(password), nil, "AES-256-CBC"))
end
def self.decrypt(message, password)
base64_decoded = Base64.decode64(message.to_s.strip)
self.decrypt_data(base64_decoded, self.key_digest(password), nil, "AES-256-CBC")
end
def self.key_digest(password)
OpenSSL::Digest::SHA256.new(password).digest
end
def self.decrypt_data(encrypted_data, key, iv, cipher_type)
aes = OpenSSL::Cipher::Cipher.new(cipher_type)
aes.decrypt
aes.key = key
aes.iv = iv if iv != nil
aes.update(encrypted_data) + aes.final
end
def self.encrypt_data(data, key, iv, cipher_type)
aes = OpenSSL::Cipher::Cipher.new(cipher_type)
aes.encrypt
aes.key = key
aes.iv = iv if iv != nil
aes.update(data) + aes.final
end
end
和PHP代码:
echo base64_encode($encrypted_data = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, hash('sha256', 'p4ssw0rd'), 'hey', MCRYPT_MODE_CBC));