我希望使用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
异常
答案 0 :(得分:1)
我认为您的密钥格式错误。你正试图传递一个RSA密钥,当密钥应该只是一个哈希字符串......类似于:
key = SecureRandom.hex(32)
=> "b67f7a5bf031aaa730473e5a9612a94b157c43aed5f52a2e70c9573f2d5a4ecd"
答案 1 :(得分:1)
你应该使用
key = cipher.random_key
而不是RSA密钥
为了我的目的,我已按照以下方式使用它
在接收端
注意:我们无法使用基于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!!'