使用ARGV进行Ruby Encrypt-Decrypt练习

时间:2018-04-18 10:21:38

标签: ruby encryption openssl base64

我最近开始学习Ruby,我得到了如下所述的作业:

Assignment

到目前为止,这是我的代码,编码正在运行,但解码并没有。 我尝试在谷歌上搜索答案,并没有找到答案,很可能我没有足够的经验来理解我发现的一些事情。 我唯一知道的是,输入编码输出后的密钥太大,就像错误信息所说的那样。

我希望有人能帮助我理解错误。

 #!/usr/bin/ruby

require "openssl"
require "base64"
include Base64

# check if argv is empty or if argv contains more than two values. if so, print error message and exit program
if ARGV.empty? || ARGV.length > 2
  puts "Error: invalid input, please try again."
  exit(2)
end

# check which method need - encrypt (ARGV contains only one value) of decrypt (ARGV contains two values)
if ARGV.length == 1

   # create the cipher for encrypting
  cipher = OpenSSL::Cipher::AES128.new(:CBC)
  cipher.encrypt

  text = ARGV[0].to_s
  key = cipher.random_key
  iv = cipher.random_iv

  # Encrypt the data, print it and exit program
  cipher_text = cipher.update(text) + cipher.final
  puts "\"" + urlsafe_encode64(cipher_text) + "\"  \"" + urlsafe_encode64(key) + "\""
  exit(2)
end

# check which method need - encrypt (ARGV contains only one value) of decrypt (ARGV contains two values)
if ARGV.length == 2                                                   

  # create the cipher decrypt
  decipher = OpenSSL::Cipher::AES128.new(:CBC)
  decipher.decrypt

  decrypt_text = ARGV[0].to_s
  decipher.key = ARGV[1].to_s
  decipher.iv = decipher.random_iv

  # Decrypt the data, print it and exit program
  decrypted_text = decipher.update(decrypt_text) + decipher.final
  puts "\"" + decrypted_text + "\""
  exit(2)
end 

1 个答案:

答案 0 :(得分:0)

我注意到的最明显的问题是,在加密时,您对base64中的密文和密钥进行编码,但是在解密步骤中,您不会将它们解码回文本/二进制数据。

尝试修复它,然后看看它是否有效:)

我注意到的另一个奇怪的事情是iv = cipher.random_iv行。我想你的意思类似于decipher.iv = decipher.random_iv下面几行。

为了避免像这样的简单错误,请始终运行ruby -wc <your_program.rb>让ruby检查文件的语法。在上面的例子中,它会告诉你变量iv已声明但从未使用过。 (-c =仅检查语法; -w =显示警告以及错误)