blob: 6ed3656af51117eadd3acb785b137053d539ca52 [file] [log] [blame]
Fabio Utzig8101d1f2019-05-09 15:03:22 -03001"""
2Tests for ECDSA keys
3"""
4
5import io
6import os.path
7import sys
8import tempfile
9import unittest
10
11from cryptography.exceptions import InvalidSignature
12from cryptography.hazmat.primitives.asymmetric import ed25519
13
14sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
15
16from imgtool.keys import load, Ed25519, Ed25519UsageError
17
18
19class Ed25519KeyGeneration(unittest.TestCase):
20
21 def setUp(self):
22 self.test_dir = tempfile.TemporaryDirectory()
23
24 def tname(self, base):
25 return os.path.join(self.test_dir.name, base)
26
27 def tearDown(self):
28 self.test_dir.cleanup()
29
30 def test_keygen(self):
31 name1 = self.tname("keygen.pem")
32 k = Ed25519.generate()
33 k.export_private(name1, b'secret')
34
35 self.assertIsNone(load(name1))
36
37 k2 = load(name1, b'secret')
38
39 pubname = self.tname('keygen-pub.pem')
40 k2.export_public(pubname)
41 pk2 = load(pubname)
42
43 # We should be able to export the public key from the loaded
44 # public key, but not the private key.
45 pk2.export_public(self.tname('keygen-pub2.pem'))
46 self.assertRaises(Ed25519UsageError,
47 pk2.export_private, self.tname('keygen-priv2.pem'))
48
49 def test_emit(self):
50 """Basic sanity check on the code emitters."""
51 k = Ed25519.generate()
52
53 ccode = io.StringIO()
54 k.emit_c(ccode)
55 self.assertIn("ed25519_pub_key", ccode.getvalue())
56 self.assertIn("ed25519_pub_key_len", ccode.getvalue())
57
58 rustcode = io.StringIO()
59 k.emit_rust(rustcode)
60 self.assertIn("ED25519_PUB_KEY", rustcode.getvalue())
61
62 def test_emit_pub(self):
63 """Basic sanity check on the code emitters."""
64 pubname = self.tname("public.pem")
65 k = Ed25519.generate()
66 k.export_public(pubname)
67
68 k2 = load(pubname)
69
70 ccode = io.StringIO()
71 k2.emit_c(ccode)
72 self.assertIn("ed25519_pub_key", ccode.getvalue())
73 self.assertIn("ed25519_pub_key_len", ccode.getvalue())
74
75 rustcode = io.StringIO()
76 k2.emit_rust(rustcode)
77 self.assertIn("ED25519_PUB_KEY", rustcode.getvalue())
78
79 def test_sig(self):
80 k = Ed25519.generate()
81 buf = b'This is the message'
82 sig = k.raw_sign(buf)
83
84 # The code doesn't have any verification, so verify this
85 # manually.
86 k.key.public_key().verify(signature=sig, data=buf)
87
88 # Modify the message to make sure the signature fails.
89 self.assertRaises(InvalidSignature,
90 k.key.public_key().verify,
91 signature=sig,
92 data=b'This is thE message')
93
94
95if __name__ == '__main__':
96 unittest.main()