how to encrypt data with AES 256 ECB PKCS5Padding in ruby

喜欢而已 提交于 2020-01-15 07:48:47

问题


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

here key is OpenSSL::PKey::RSA type, throwing no implicit conversion of OpenSSL::PKey::RSA into String exception


回答1:


I think your key is in the wrong format. You're trying to pass an RSA key, when the key should just be a hash string ... something like:

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



回答2:


You should use

key = cipher.random_key

instead of RSA key

I have used it in following way for my purpose

  1. Generate cypher random keys
  2. Do AES encryption of data with these keys
  3. Before supply the keys encrypt it with RSA public key

At receiver end

  1. Decrypt the cypher keys with RSA private key
  2. Decrypt the data with resultant cypher keys

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!!'


来源:https://stackoverflow.com/questions/40760184/how-to-encrypt-data-with-aes-256-ecb-pkcs5padding-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!