blob: 8cb3220f8020be07430f0bc3b605ff896a526181 [file] [log] [blame]
David Brownb6e0ae62017-11-21 15:13:04 -07001"""
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 ec
13from cryptography.hazmat.primitives.hashes import SHA256
14
15sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
16
17from imgtool.keys import load, ECDSA256P1, ECDSAUsageError
18
19class EcKeyGeneration(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 = ECDSA256P1.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(ECDSAUsageError,
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 = ECDSA256P1.generate()
52
53 ccode = io.StringIO()
54 k.emit_c(ccode)
55 self.assertIn("ecdsa_pub_key", ccode.getvalue())
56 self.assertIn("ecdsa_pub_key_len", ccode.getvalue())
57
58 rustcode = io.StringIO()
59 k.emit_rust(rustcode)
60 self.assertIn("ECDSA_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 = ECDSA256P1.generate()
66 k.export_public(pubname)
67
68 k2 = load(pubname)
69
70 ccode = io.StringIO()
71 k2.emit_c(ccode)
72 self.assertIn("ecdsa_pub_key", ccode.getvalue())
73 self.assertIn("ecdsa_pub_key_len", ccode.getvalue())
74
75 rustcode = io.StringIO()
76 k2.emit_rust(rustcode)
77 self.assertIn("ECDSA_PUB_KEY", rustcode.getvalue())
78
79 def test_sig(self):
80 k = ECDSA256P1.generate()
81 buf = b'This is the message'
David Brown2c9153a2017-11-21 15:18:12 -070082 sig = k.raw_sign(buf)
David Brownb6e0ae62017-11-21 15:13:04 -070083
84 # The code doesn't have any verification, so verify this
85 # manually.
86 k.key.public_key().verify(
87 signature=sig,
88 data=buf,
89 signature_algorithm=ec.ECDSA(SHA256()))
90
91 # Modify the message to make sure the signature fails.
92 self.assertRaises(InvalidSignature,
93 k.key.public_key().verify,
94 signature=sig,
95 data=b'This is thE message',
96 signature_algorithm=ec.ECDSA(SHA256()))
97
98if __name__ == '__main__':
99 unittest.main()