Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 1st, 2012  |  syntax: None  |  size: 1.78 KB  |  hits: 16  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. #!/usr/bin/env ruby
  2. require "openssl"
  3. require 'digest/sha2'
  4. require 'base64'
  5.  
  6. # We use the AES 256 bit cipher-block chaining symetric encryption
  7. alg = "AES-256-CBC"
  8.  
  9. # We want a 256 bit key symetric key based on some passphrase
  10. digest = Digest::SHA256.new
  11. digest.update("symetric key")
  12. key = digest.digest
  13. # We could also have just created a random key
  14. # key = OpenSSL::Cipher::Cipher.new(alg).random_key
  15.  
  16. # For security as part of the encryption algorithm, we create a random
  17. # initialization vector.
  18. iv = OpenSSL::Cipher::Cipher.new(alg).random_iv
  19.  
  20. # Example, we debug output our key in various formats
  21. puts "Our key"
  22. p key
  23. # Base64 the key
  24. puts "Our key base 64"
  25. key64 = [key].pack('m')
  26. puts key64
  27. # Base64 decode the key
  28. puts "Our key retrieved from base64"
  29. p key64.unpack('m')[0]
  30. raise 'Key Error' if(key.nil? or key.size != 32)
  31.  
  32. # Now we do the actual setup of the cipher
  33. aes = OpenSSL::Cipher::Cipher.new(alg)
  34. aes.encrypt
  35. aes.key = key
  36. aes.iv = iv
  37.  
  38. # Now we go ahead and encrypt our plain text.
  39. cipher = aes.update("This is line 1\n")
  40. cipher << aes.update("This is some other string without linebreak.")
  41. cipher << aes.update("This follows immediately after period.")
  42. cipher << aes.update("Same with this final sentence")
  43. cipher << aes.final
  44.  
  45. puts "Our Encrypted data in base64"
  46. cipher64 = [cipher].pack('m')
  47. puts cipher64
  48.  
  49. decode_cipher = OpenSSL::Cipher::Cipher.new(alg)
  50. decode_cipher.decrypt
  51. decode_cipher.key = key
  52. decode_cipher.iv = iv
  53. plain = decode_cipher.update(cipher64.unpack('m')[0])
  54. plain << decode_cipher.final
  55. puts "Decrypted Text"
  56. puts plain
  57.  
  58. '
  59. # aes encode a file into another file.
  60. File.open("foo.enc","w") do |enc|
  61.    File.open("foo") do |f|
  62.      loop do
  63.        r = f.read(4096)
  64.        break unless r
  65.        cipher = aes.update(r)
  66.        enc << cipher
  67.      end
  68.    end
  69.  
  70.    enc << aes.final
  71. end
  72. '