Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Ruby中没有外部宝石的简单加密大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要一些文本字符串的简单加密.我想创建优惠券代码,使它们看起来很酷,所以随后创建的代码应该看起来非常不同. (除了看起来很酷,不应该很容易猜到一个代码.)但是我想要能够再次解密它们.所以算法必须是可逆的.

我试过一些东西,移动位,所以他们看起来是随机的.但是后来的两个代码(只有一点不同)当然看起来很相似.

有什么建议么?我想这样做,而不使用外部宝石.

菲利普

@H_675_9@解决方法
你可以使用OpenSSL :: Cypher
# for more info,see http://ruby-doc.org/stdlib-1.9.3/libdoc/openssl/rdoc/OpenSSL/Cipher.html

require 'openssl'
require 'digest/sha1'

# create the cipher for encrypTing
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.encrypt

# you will need to store these for later,in order to decrypt your data
key = Digest::SHA1.hexdigest("yourpass")
iv = cipher.random_iv

# load them into the cipher
cipher.key = key
cipher.iv = iv

# encrypt the message
encrypted = cipher.update('This is a secure message,meet at the clock-tower at dawn.')
encrypted << cipher.final
puts "encrypted: #{encrypteD}\n"

# now we create a sipher for decrypTing
cipher = OpenSSL::Cipher::Cipher.new("aes-256-cbc")
cipher.decrypt
cipher.key = key
cipher.iv = iv

# and decrypt it
decrypted = cipher.update(encrypted)
decrypted << cipher.final
puts "decrypted: #{decrypteD}\n"

但中间形式不适合打印

鉴于您的想法,如果中间形式的长度相同,则可能会使用简单的一个字符映射到另一个字符.

请谅解这不是安全的

你可以很容易地强制关键,但它似乎与你的要求一致.

class Cipher

  def initialize(shuffled)
    normal = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a + [' ']
    @map = normal.zip(shuffled).inject(:encrypt => {},:decrypt => {}) do |hash,(a,b)|
      hash[:encrypt][a] = b
      hash[:decrypt][b] = a
      hash
    end
  end

  def encrypt(str)
    str.split(//).map { |char| @map[:encrypt][char] }.join
  end

  def decrypt(str)
    str.split(//).map { |char| @map[:decrypt][char] }.join
  end

end

# pass the shuffled version to the cipher
cipher = Cipher.new ["K","D","w","X","H","3","e","1","S","B","g","a","y","v","I","6","u","W","C","0","9","b","z","T","A","q","U","4","O","o","E","N","r","n","m","d","k","x","P","t","R","s","J","L","f","h","Z","j","Y","5","7","l","p","c","2","8","M","V","G","i"," ","Q","F"]

msg = "howdy pardner"

crypted = cipher.encrypt msg
crypted # => "1IzXAF6KWXvHW"

decrypted = cipher.decrypt crypted
decrypted # => "howdy pardner"

大佬总结

以上是大佬教程为你收集整理的Ruby中没有外部宝石的简单加密全部内容,希望文章能够帮你解决Ruby中没有外部宝石的简单加密所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。