无法使用另一个密码实例解密加密邮件

时间:2017-10-05 13:11:41

标签: ruby aes-gcm

我正在使用ruby版本2.4.0和openssl版本" OpenSSL 1.0.1f 2014年1月6日",我正在尝试为安全层实现加密/解密。

如果我使用相同的密码对象按如下方式编写代码,则代码可以正常工作。

# Example 1

require 'openssl'
require 'base64'

data = "Hello1"

cipher = OpenSSL::Cipher::AES128.new :GCM
cipher.encrypt
iv  = cipher.random_iv # random iv
key = cipher.random_key # 128 byte key
cipher.key = key
cipher.iv = iv
enc_data  = cipher.update(data) + cipher.final

cipher.decrypt
cipher.key = key
cipher.iv = iv
original_data = cipher.update(enc_data) + cipher.final

if data == original_data
  puts "Yes"
end

但是在第二个例子中我实例化了第二个用于解密的密码对象,我得到了一个CipherError。

# Example 1

require 'openssl'
require 'base64'

def encrypt(data)
  cipher = OpenSSL::Cipher::AES128.new :GCM
  cipher.encrypt
  key = cipher.random_key
  iv  = cipher.random_iv
  cipher.key = key
  cipher.iv = iv
  enc_data = cipher.update(data) + cipher.final
  return enc_data, key, iv
end

def decrypt(data, key, iv)
  cipher = OpenSSL::Cipher::AES128.new :GCM
  cipher.decrypt
  cipher.key = key
  cipher.iv  = iv
  cipher.update(data) + cipher.final
end

data = 'Hello2'
enc_data, key, iv = encrypt(data)
original_data = decrypt(enc_data, key, iv)

if data == original_data
  puts "Yes"
end


OpenSSL::Cipher::CipherError:
from (irb):93:in `final'
from (irb):93:in `decrypt'
from (irb):98

1 个答案:

答案 0 :(得分:3)

与CBC模式相比,GCM模式需要更多设置。

文档:https://ruby-doc.org/stdlib-2.4.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html#class-OpenSSL::Cipher-label-Authenticated+Encryption+and+Associated+Data+-28AEAD-29

  

使用GCM(伽罗瓦/计数器模式)的示例。您有16个字节import pandas as pd import numpy as np file = 'C:\\Users\\Jerry\\Downloads\\nyc-rolling-sales.csv' sales = pd.read_csv(file,sep = ',',encoding = 'latin-1') dropcols = ["BOROUGH","NEIGHBORHOOD","BLOCK","ADDRESS","APARTMENT NUMBER"] sales = sales.drop(dropcols,axis=1) #boolean indexing mask = sales['SALE PRICE'] == "-" #mask = sales['SALE PRICE'].str.strip() == "-" #use this for spaces sales[~mask] ,12个字节(96位)url = "http://www1.nyc.gov/assets/finance/downloads/pdf/rolling_sales/rollingsales_manhattan.xls" sales = pd.read_excel(url,skiprows=4) 以及相关数据 key 。 ......现在你是接收者。您知道nonce已通过不受信任的网络收到auth_datakeynonce auth_data

这是更新后的代码:

encrypted