OSDN Git Service

ruby-1.9.1-rc1
[splhack/AndroidRuby.git] / lib / ruby-1.9.1-rc1 / sample / openssl / cipher.rb
1 #!/usr/bin/env ruby
2 require 'openssl'
3
4 def crypt_by_password(alg, pass, salt, text)
5   puts "--Setup--"
6   puts %(cipher alg:    "#{alg}")
7   puts %(plain text:    "#{text}")
8   puts %(password:      "#{pass}")
9   puts %(salt:          "#{salt}")
10   puts
11
12   puts "--Encrypting--"
13   enc = OpenSSL::Cipher::Cipher.new(alg)
14   enc.encrypt
15   enc.pkcs5_keyivgen(pass, salt)
16   cipher =  enc.update(text)
17   cipher << enc.final
18   puts %(encrypted text: #{cipher.inspect})
19   puts
20
21   puts "--Decrypting--"
22   dec = OpenSSL::Cipher::Cipher.new(alg)
23   dec.decrypt
24   dec.pkcs5_keyivgen(pass, salt)
25   plain =  dec.update(cipher)
26   plain << dec.final
27   puts %(decrypted text: "#{plain}")
28   puts
29 end
30
31 def ciphers
32   ciphers = OpenSSL::Cipher.ciphers.sort
33   ciphers.each{|i|
34     if i.upcase != i && ciphers.include?(i.upcase)
35       ciphers.delete(i)
36     end
37   }
38   return ciphers
39 end
40
41 puts "Supported ciphers in #{OpenSSL::OPENSSL_VERSION}:"
42 ciphers.each_with_index{|name, i|
43   printf("%-15s", name)
44   puts if (i + 1) % 5 == 0
45 }
46 puts
47 puts
48
49 alg  = ARGV.shift || ciphers.first
50 pass = "secret password"
51 salt = "8 octets"        # or nil
52 text = "abcdefghijklmnopqrstuvwxyz"
53
54 crypt_by_password(alg, pass, salt, text)