]> gitweb.pimeys.fr Git - NK2015_Client_Python_Alpha.git/blob - rsa_source/rsa/util.py
on ajoute le module rsa car le client aussi en a besoin
[NK2015_Client_Python_Alpha.git] / rsa_source / rsa / util.py
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
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 '''Utility functions.'''
18
19 import sys
20 from optparse import OptionParser
21
22 import rsa.key
23
24 def private_to_public():
25 '''Reads a private key and outputs the corresponding public key.'''
26
27 # Parse the CLI options
28 parser = OptionParser(usage='usage: %prog [options]',
29 description='Reads a private key and outputs the '
30 'corresponding public key. Both private and public keys use '
31 'the format described in PKCS#1 v1.5')
32
33 parser.add_option('-i', '--input', dest='infilename', type='string',
34 help='Input filename. Reads from stdin if not specified')
35 parser.add_option('-o', '--output', dest='outfilename', type='string',
36 help='Output filename. Writes to stdout of not specified')
37
38 parser.add_option('--inform', dest='inform',
39 help='key format of input - default PEM',
40 choices=('PEM', 'DER'), default='PEM')
41
42 parser.add_option('--outform', dest='outform',
43 help='key format of output - default PEM',
44 choices=('PEM', 'DER'), default='PEM')
45
46 (cli, cli_args) = parser.parse_args(sys.argv)
47
48 # Read the input data
49 if cli.infilename:
50 print >>sys.stderr, 'Reading private key from %s in %s format' % \
51 (cli.infilename, cli.inform)
52 with open(cli.infilename) as infile:
53 in_data = infile.read()
54 else:
55 print >>sys.stderr, 'Reading private key from stdin in %s format' % \
56 cli.inform
57 in_data = sys.stdin.read()
58
59
60 # Take the public fields and create a public key
61 priv_key = rsa.key.PrivateKey.load_pkcs1(in_data, cli.inform)
62 pub_key = rsa.key.PublicKey(priv_key.n, priv_key.e)
63
64 # Save to the output file
65 out_data = pub_key.save_pkcs1(cli.outform)
66
67 if cli.outfilename:
68 print >>sys.stderr, 'Writing public key to %s in %s format' % \
69 (cli.outfilename, cli.outform)
70 with open(cli.outfilename, 'w') as outfile:
71 outfile.write(out_data)
72 else:
73 print >>sys.stderr, 'Writing public key to stdout in %s format' % \
74 cli.outform
75 sys.stdout.write(out_data)
76
77