-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.py
221 lines (197 loc) · 7.3 KB
/
generate.py
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
#!/usr/bin/env python
# Copyright (c) 2020 Janky <box@janky.tech>
# All right reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
# THE POSSIBILITY OF SUCH DAMAGE.
# Inspired by https://github.com/rnpgp/rnp/blob/master/src/examples/generate.c
from pyrop.bind import RopBind
from pyrop.error import RopError
# RSA key JSON description. 31536000 = 1 year expiration, 15768000 = half year
RSA_KEY_DESC = "{\
'primary': {\
'type': 'RSA',\
'length': 2048,\
'userid': 'rsa@key',\
'expiration': 31536000,\
'usage': ['sign'],\
'protection': {\
'cipher': 'AES256',\
'hash': 'SHA256'\
}\
},\
'sub': {\
'type': 'RSA',\
'length': 2048,\
'expiration': 15768000,\
'usage': ['encrypt'],\
'protection': {\
'cipher': 'AES256',\
'hash': 'SHA256'\
}\
}\
}"
CURVE_25519_KEY_DESC = "{\
'primary': {\
'type': 'EDDSA',\
'userid': '25519@key',\
'expiration': 0,\
'usage': ['sign'],\
'protection': {\
'cipher': 'AES256',\
'hash': 'SHA256'\
}\
},\
'sub': {\
'type': 'ECDH',\
'curve': 'Curve25519',\
'expiration': 15768000,\
'usage': ['encrypt'],\
'protection': {\
'cipher': 'AES256',\
'hash': 'SHA256'\
}\
}\
}"
# basic pass provider implementation, which always return 'password' for key protection.
# You may ask for password via stdin, or choose password based on key properties, whatever else
def example_pass_provider(session, app_ctx, key, pgp_context, buf_len):
if pgp_context == 'protect':
return True, 'password'
return False, None
# this simple helper function just prints armored key, searched by userid, to stdout
def print_key(rop, ses, uid, secret):
# you may search for the key via userid, keyid, fingerprint, grip
key = ses.locate_key("userid", uid)
# create in-memory output structure to later use buffer
keydata = rop.create_output(max_alloc=0)
try:
key.export(keydata, public=not secret, secret=secret, subkey=True, armored=True)
# get key's contents from the output structure
buf = keydata.memory_get_str(False)
print(buf)
finally:
rop.drop(object_=keydata)
def export_key(rop, ses, uid, secret):
# you may search for the key via userid, keyid, fingerprint, grip
key = ses.locate_key("userid", uid)
# get key's id and build filename
filename = "key-{}-{}.asc".format(key.keyid, "sec" if secret else "pub")
keyfile = rop.create_output(to_path=filename)
try:
key.export(keyfile, public=not secret, secret=secret, subkey=True, armored=True)
finally:
rop.drop(object_=keyfile)
# this example function generates RSA/RSA and Eddsa/X25519 keypairs
def generate_keys(rop):
alt = rop.tagging()
try:
# initialize
ses = rop.create_session(rop.KEYSTORE_GPG, rop.KEYSTORE_GPG)
try:
# set password provider
ses.set_pass_provider(example_pass_provider, None)
# generate EDDSA/X25519 keypair
key_grips = ses.generate_key_json(CURVE_25519_KEY_DESC)
# generate RSA keypair
key_grips = ses.generate_key_json(RSA_KEY_DESC)
print("Generated RSA key/subkey:\n%s\n" % key_grips)
except RopError:
print("Failed to generate keys")
raise
keyfile = None
try:
# create file output object and save public keyring with generated keys, overwriting
# previous file if any. You may use max_alloc here as well.
keyfile = rop.create_output(to_path="pubring.pgp")
ses.save_keys(rop.KEYSTORE_GPG, keyfile, public=True)
except RopError:
print("Failed to save pubring")
raise
finally:
rop.drop(object_=keyfile)
keyfile = None
try:
# create file output object and save secret keyring with generated keys
keyfile = rop.create_output(to_path="secring.pgp")
ses.save_keys(rop.KEYSTORE_GPG, keyfile, secret=True)
except RopError:
print("Failed to save secring")
raise
finally:
rop.drop(object_=keyfile)
finally:
rop.drop(from_=alt)
def output_keys(rop):
alt = rop.tagging()
try:
# initialize
ses = rop.create_session(rop.KEYSTORE_GPG, rop.KEYSTORE_GPG)
keyfile = None
try:
# load keyrings
keyfile = rop.create_input(path="pubring.pgp")
# actually, we may exclude the public to not check key types
ses.load_keys(rop.KEYSTORE_GPG, keyfile, public=True)
except RopError:
print("Failed to read pubring")
raise
finally:
rop.drop(object_=keyfile)
keyfile = None
try:
keyfile = rop.create_input(path="secring.pgp")
ses.load_keys(rop.KEYSTORE_GPG, keyfile, secret=True)
except RopError:
print("Failed to read secring")
raise
finally:
rop.drop(object_=keyfile)
try:
# print armored keys to the stdout
print_key(rop, ses, "rsa@key", False)
print_key(rop, ses, "rsa@key", True)
print_key(rop, ses, "25519@key", False)
print_key(rop, ses, "25519@key", True)
except:
print("Failed to print armored key(s)")
raise
try:
# write armored keys to the files, named key-<keyid>-pub.asc/named key-<keyid>-sec.asc
export_key(rop, ses, "rsa@key", False)
export_key(rop, ses, "rsa@key", True)
export_key(rop, ses, "25519@key", False)
export_key(rop, ses, "25519@key", True)
except:
print("Failed to write armored key(s) to file")
raise
finally:
rop.drop(from_=alt)
def execute():
rop = RopBind()
try:
generate_keys(rop)
output_keys(rop)
finally:
rop.close()
if __name__ == '__main__':
execute()