blob: cb7e1a62a7acd892a0e634676ec2dfcb5a684358 [file] [log] [blame]
Sybren A. Stüvel64c5f922011-07-31 19:32:071# -*- coding: utf-8 -*-
2#
3# Copyright 2011 Sybren A. Stüvel <[email protected]>
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17'''Commandline scripts.
18
19'''
20
21import sys
22from optparse import OptionParser
23
24import rsa
25import rsa.bigfile
26
27def keygen():
28 # Parse the CLI options
29 parser = OptionParser(usage='usage: %prog [options] keysize',
30 description='Generates a new RSA keypair of "keysize" bits.')
31
32 parser.add_option('--pubout', type='string',
33 help='Output filename for the public key. The public key is '
34 'not saved if this option is not present. You can use '
35 'pyrsa-priv2pub to create the public key file later.')
36
37 parser.add_option('--privout', type='string',
38 help='Output filename for the private key. The key is '
39 'written to stdout if this option is not present.')
40
41 parser.add_option('--form',
42 help='key format of the private and public keys - default PEM',
43 choices=('PEM', 'DER'), default='PEM')
44
45 (cli, cli_args) = parser.parse_args(sys.argv[1:])
46
47 if len(cli_args) != 1:
48 parser.print_help()
49 raise SystemExit(1)
50
51 try:
52 keysize = int(cli_args[0])
53 except ValueError:
54 parser.print_help()
55 print >>sys.stderr, 'Not a valid number: %s' % cli_args[0]
56 raise SystemExit(1)
57
58 print >>sys.stderr, 'Generating %i-bit key' % keysize
59 (pub_key, priv_key) = rsa.newkeys(keysize)
60
61
62 # Save public key
63 if cli.pubout:
64 print >>sys.stderr, 'Writing public key to %s' % cli.pubout
65 data = pub_key.save_pkcs1(format=cli.form)
66 with open(cli.pubout, 'w') as outfile:
67 outfile.write(data)
68
69 # Save private key
70 data = priv_key.save_pkcs1(format=cli.form)
71
72 if cli.privout:
73 print >>sys.stderr, 'Writing private key to %s' % cli.privout
74 with open(cli.privout, 'w') as outfile:
75 outfile.write(data)
76 else:
77 print >>sys.stderr, 'Writing private key to stdout'
78 sys.stdout.write(data)
79