Simple Encryption in Ruby without external gems

前端 未结 9 945
庸人自扰
庸人自扰 2020-12-08 07:43

I need a simple encryption for some text strings. I want to create coupon codes and make them look cool so subsequently created code should look very different. (And besides

9条回答
  •  被撕碎了的回忆
    2020-12-08 08:10

    You could use 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"
    

    But the intermediate form doesn't lend itself well to printing


    Given your thought that it would be nice if the intermediate form was the same length, you might just use a simple map of one char to another.

    PLEASE UNDERSTAND THAT THIS IS NOT SECURE

    You can easily brute force the key, but it seems to be congruent with your requirements.

    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"
    

提交回复
热议问题