如何在Ruby中使用AES 256 ECB PKCS5Padding加密数据 [英] how to encrypt data with AES 256 ECB PKCS5Padding in ruby
本文介绍了如何在Ruby中使用AES 256 ECB PKCS5Padding加密数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用PKCS5padding以AES 256位ECB模式加密数据 我的红宝石方法如下,如何在此处使用PKCS5Padding
I want encrypt data with AES 256bit ECB mode using PKCS5padding My ruby method is as follows, how to use PKCS5Padding here
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
异常
here key is OpenSSL::PKey::RSA type, throwing no implicit conversion of OpenSSL::PKey::RSA into String
exception
推荐答案
您应该使用
key = cipher.random_key
代替RSA密钥
我已按照以下目的使用它
I have used it in following way for my purpose
- 生成密码随机密钥
- 使用这些密钥对数据进行AES加密
- 在提供密钥之前,先使用RSA公钥对其进行加密
在接收方结束
- 使用RSA私钥解密密码密钥
- 使用生成的密码密钥解密数据
注意:我们无法使用基于RSA私钥/公钥的技术来加密大数据
Note: We can not encrypt large data with RSA private/public key based technique
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!!'
这篇关于如何在Ruby中使用AES 256 ECB PKCS5Padding加密数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文