* io.c (rb_open_file): encoding in mode string was ignored if perm is
[ruby-svn.git] / sample / openssl / gen_csr.rb
blob4228707fdb2b242b159976cd597b02b1b9f3f1a5
1 #!/usr/bin/env ruby
3 require 'optparse'
4 require 'openssl'
6 include OpenSSL
8 def usage
9   myname = File::basename($0)
10   $stderr.puts <<EOS
11 Usage: #{myname} [--key keypair_file] name
12   name ... ex. /C=JP/O=RRR/OU=CA/CN=NaHi/emailAddress=nahi@example.org
13 EOS
14   exit
15 end
17 options = ARGV.getopts(nil, "key:", "csrout:", "keyout:")
18 keypair_file = options["key"]
19 csrout = options["csrout"] || "csr.pem"
20 keyout = options["keyout"] || "keypair.pem"
22 $stdout.sync = true
23 name_str = ARGV.shift or usage()
24 name = X509::Name.parse(name_str)
26 keypair = nil
27 if keypair_file
28   keypair = PKey::RSA.new(File.open(keypair_file).read)
29 else
30   keypair = PKey::RSA.new(1024) { putc "." }
31   puts
32   puts "Writing #{keyout}..."
33   File.open(keyout, "w", 0400) do |f|
34     f << keypair.to_pem
35   end
36 end
38 puts "Generating CSR for #{name_str}"
40 req = X509::Request.new
41 req.version = 0
42 req.subject = name
43 req.public_key = keypair.public_key
44 req.sign(keypair, Digest::MD5.new)
46 puts "Writing #{csrout}..."
47 File.open(csrout, "w") do |f|
48   f << req.to_pem
49 end
50 puts req.to_text
51 puts req.to_pem