如何使用AES 256 ECB PKCS5Padding在ruby中加密数据

我希望用AES 256bit ECB模式加密数据使用PKCS5padding我的ruby方法如下,如何在这里使用PKCS5Padding

def encrypt(raw_data,key) cipher = OpenSSL::Cipher::AES.new(256, :ECB) cipher.encrypt cipher.key = key encrypted_data = cipher.update(raw_data) + cipher.final end 

这里的密钥是OpenSSL :: PKey :: RSA类型, no implicit conversion of OpenSSL::PKey::RSA into String抛出no implicit conversion of OpenSSL::PKey::RSA into Stringexception的no implicit conversion of OpenSSL::PKey::RSA into String

我认为你的密钥格式错误。 您正在尝试传递RSA密钥,当密钥应该只是一个哈希字符串…类似于:

 key = SecureRandom.hex(32) => "b67f7a5bf031aaa730473e5a9612a94b157c43aed5f52a2e70c9573f2d5a4ecd" 

你应该用

 key = cipher.random_key 

而不是RSA密钥

为了我的目的,我已经按照以下方式使用它

  1. 生成密码随机密钥
  2. 使用这些密钥对数据进行AES加密
  3. 在提供之前,密钥使用RSA公钥加密

在接收器端

  1. 使用RSA私钥解密密码密钥
  2. 使用生成的密钥解密数据

注意:我们无法使用基于RSA私钥/公钥的技术加密大数据

 Super secured Example # At sender side public_key_file = 'public.pem' message = 'Hey vishh you are awesome!!' cipher = OpenSSL::Cipher::AES.new(128, :CBC) cipher.encrypt aes_key = cipher.random_key encrypted_data = cipher.update(message) + cipher.final # encrypted_data is ready to travel rsa = OpenSSL::PKey::RSA.new(File.read(public_key_file)) rsa_cypher_key = rsa.public_encrypt(aes_key) # rsa_cypher_key is ready to travel # sending these data in encoded format is good idea encrypted_data = Base64.encode64(encrypted_data) rsa_cypher_key = Base64.encode64(rsa_cypher_key) ====> encrypted_data + rsa_cypher_key =====> Travelling encrypted_data = Base64.decode64(encrypted_data) rsa_cypher_key = Base64.decode64(rsa_cypher_key) # decode the data # At recevier side private_key_file = 'private.pem' # Decrypt the cypher key with private key rsp = OpenSSL::PKey::RSA.new(File.read('./config/private.pem')) aes_key = private_key.private_decrypt(rsa_cypher_key) decipher = OpenSSL::Cipher::AES.new(128, :CBC) decipher.decrypt decipher.key = aes_key message = decipher.update(encrypted_data) + decipher.final p message 'Hey vishh you are awesome!!'