Ruby中没有外部宝石的简单加密

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

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

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

菲利普

解决方法

你可以使用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"
原文链接:https://www.f2er.com/ruby/273978.html

猜你在找的Ruby相关文章