-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-jwk.rb
More file actions
executable file
·123 lines (98 loc) · 2.33 KB
/
generate-jwk.rb
File metadata and controls
executable file
·123 lines (98 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/env ruby
#
# INSTALL
# -------
#
# Make sure the script is executable
# chmod +x generate-jwk.rb
#
# USAGE
# -----
#
# generate-jwk.rb
# --output={PRIVATE_KEY_IN_JWK_FORMAT}
#
# AUTHORS
# -------
#
# Jan Vereecken <ciao@janvereecken.com>
#
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'json-jwt'
gem 'optparse'
end
require 'openssl'
require 'securerandom'
require 'time'
#------------------------------------------------------------
# main
#------------------------------------------------------------
def main(args)
# Process the command line options.
options = Options.process(args)
# Generate the JWK
jwk = generate_jwk(options)
# Write the jwk to the standard output.
puts jwk
end
#------------------------------------------------------------
# Generate the JWK.
#------------------------------------------------------------
def generate_jwk(options)
case options.alg
when 'ES256'
ec = OpenSSL::PKey::EC.generate('prime256v1')
jwk = JSON::JWK.new(ec, { alg: options.alg })
when 'RS256'
rsa = OpenSSL::PKey::RSA.new(2048)
jwk = JSON::JWK.new(rsa, { alg: options.alg })
else
raise "Unsupported algorithm: #{options.alg}"
end
if options.out
File.open(options.out, 'w') do |f|
f.write(jwk.to_json)
end
end
jwk
end
#------------------------------------------------------------
# Command line options
#------------------------------------------------------------
class Options < OptionParser
DESC_ALG = "The algorithm to use for the JWK (ES256, or RS256, default: ES256)."
DESC_OUT = "A file containing a private key in the JWK format."
attr_reader :out, :alg
def initialize
super
@out = nil
@alg = 'ES256'
self.on('-a ALG', '--alg=ALG', DESC_ALG) do |alg|
@alg = alg
end
self.on('-o FILE', '--out=FILE', DESC_OUT) do |file|
@out = file
end
end
private
def error_if_missing(value, option)
if value.nil?
raise OptionParser::ParseError.new "'#{option}' is missing."
end
end
public
def verify
end
def self.process(args)
options = Options.new
options.parse(args)
options.verify()
return options
end
end
#------------------------------------------------------------
# Entry Point
#------------------------------------------------------------
main(ARGV)