]>
gitweb.pimeys.fr Git - NK2015_Client_Python_Alpha.git/blob - rsa_source/rsa/util.py
1 # -*- coding: utf-8 -*-
3 # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 '''Utility functions.'''
20 from optparse
import OptionParser
24 def private_to_public():
25 '''Reads a private key and outputs the corresponding public key.'''
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')
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')
38 parser
.add_option('--inform', dest
='inform',
39 help='key format of input - default PEM',
40 choices
=('PEM', 'DER'), default
='PEM')
42 parser
.add_option('--outform', dest
='outform',
43 help='key format of output - default PEM',
44 choices
=('PEM', 'DER'), default
='PEM')
46 (cli
, cli_args
) = parser
.parse_args(sys
.argv
)
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()
55 print >>sys
.stderr
, 'Reading private key from stdin in %s format' % \
57 in_data
= sys
.stdin
.read()
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
)
64 # Save to the output file
65 out_data
= pub_key
.save_pkcs1(cli
.outform
)
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
)
73 print >>sys
.stderr
, 'Writing public key to stdout in %s format' % \
75 sys
.stdout
.write(out_data
)