2016-11-23 163 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嘿,我已編輯答案的幫助,現在它是你的時間來搖滾! –