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

时间:2016-11-23 09:13:35

标签: ruby-on-rails ruby encryption openssl aes

我希望使用PKCS5padding以AES 256bit ECB模式加密数据 我的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异常

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

你应该使用

key = cipher.random_key

而不是RSA密钥

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

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

    1. 使用RSA私钥解密密码密钥
    2. 使用生成的密钥解密数据
    3. 注意:我们无法使用基于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!!'