forked from tleonhardt/practical_cryptography_engineering
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nacl_sign.py
executable file
·55 lines (42 loc) · 1.9 KB
/
nacl_sign.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
#!/usr/bin/env python3
# coding=utf-8
"""
Uses PyNaCl to sign a message using ed25519 digital signature algorithm
"""
import sys
import colorama
from colorama import Fore
from nacl.encoding import HexEncoder, RawEncoder
from nacl.signing import SigningKey
if __name__ == '__main__':
colorama.init(autoreset=True)
expected_args = 3
received_args = len(sys.argv) - 1
if received_args != expected_args:
print(Fore.RED + 'require {} arguments, but received {}'.format(expected_args, received_args))
print(Fore.CYAN + 'USAGE: {} <private_keyfile> <file_to_sign> <signature_file>'.format(sys.argv[0]))
sys.exit(1)
key_filename = sys.argv[1]
input_filename = sys.argv[2]
output_filename = sys.argv[3]
# Open the private key file and read in the signing key bytes
with open(key_filename, 'rb') as key_file:
keydata_bytes = key_file.read()
# Deal with secret keys generated by libsodium C library which also have the public key embedded
KEY_BYTES = 32
if len(keydata_bytes) > KEY_BYTES:
keydata_bytes = keydata_bytes[:KEY_BYTES]
# Reconstruct the SigningKey instance from the serialized form
signing_key = SigningKey(keydata_bytes, encoder=RawEncoder)
# Print out the private Signing key
signing_hex = signing_key.encode(encoder=HexEncoder)
print(Fore.LIGHTBLUE_EX + 'the private key is {}'.format(signing_hex))
# Open the input file and read its data in as a message that we wish to sign
with open(input_filename, 'rb') as msg_file:
msg = msg_file.read()
# Sign a message with the signing key - this also contains the original message at the end
sig = signing_key.sign(msg)
# Save the signature to an output file
with open(output_filename, 'wb') as sig_file:
sig_file.write(sig)
print(Fore.GREEN + 'Saved signature to {!r} for message file {!r}'.format(output_filename, input_filename))