2016-11-23 162 views
2

我要加密使用PKCS5padding 我的红宝石方法如下,如何在这里使用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 

这里AES 256位ECB模式的数据的关键是OpenSSL的使用AES 256 ECB PKCS5Padding加密数据: :PKey :: RSA类型,投掷no implicit conversion of OpenSSL::PKey::RSA into String异常

+1

http://stackoverflow.com/a/36940796/3270427 – McNets

+0

(raw_data)加密之前尝试Base64.encode64,我想你想加密的RSA密钥对不对? –

+0

您可以使用cipher.random_key作为密钥,因为它不会接受字符串以外的其他格式 –

回答

1

我认为你的密钥格式不正确。你试图通过RSA密钥,当钥匙应该只是一个哈希字符串...是这样的:

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

您应该使用

key = cipher.random_key 

代替RSA密钥

我在下面的方式使用它为我的目的

  1. 生成暗号随机密钥
  2. 数据
  3. 待办事项AES加密,这些密钥
  4. 供应之前的按键与RSA公钥

与RSA私钥

  • 解密加密它在接收器端

    1. 解密暗号键带有密码键的数据

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

    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!!' 
    
  • +0

    如何在这个过程中使用PKCS5Padding和什么是默认填充? – CodecPM

    +0

    @CodecPM嘿,我已编辑答案的帮助,现在它是你的时间来摇滚! –