David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 1 | """ |
| 2 | ECDSA key management |
| 3 | """ |
| 4 | |
| 5 | from cryptography.hazmat.backends import default_backend |
| 6 | from cryptography.hazmat.primitives import serialization |
| 7 | from cryptography.hazmat.primitives.asymmetric import ec |
| 8 | from cryptography.hazmat.primitives.hashes import SHA256 |
| 9 | |
| 10 | from .general import KeyClass |
| 11 | |
| 12 | class ECDSAUsageError(Exception): |
| 13 | pass |
| 14 | |
| 15 | class ECDSA256P1Public(KeyClass): |
| 16 | def __init__(self, key): |
| 17 | self.key = key |
| 18 | |
| 19 | def shortname(self): |
| 20 | return "ecdsa" |
| 21 | |
| 22 | def _unsupported(self, name): |
| 23 | raise ECDSAUsageError("Operation {} requires private key".format(name)) |
| 24 | |
| 25 | def _get_public(self): |
| 26 | return self.key |
| 27 | |
| 28 | def get_public_bytes(self): |
| 29 | # The key is embedded into MBUboot in "SubjectPublicKeyInfo" format |
| 30 | return self._get_public().public_bytes( |
| 31 | encoding=serialization.Encoding.DER, |
| 32 | format=serialization.PublicFormat.SubjectPublicKeyInfo) |
| 33 | |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame^] | 34 | def get_private_bytes(self, minimal): |
| 35 | self._unsupported('get_private_bytes') |
| 36 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 37 | def export_private(self, path, passwd=None): |
| 38 | self._unsupported('export_private') |
| 39 | |
| 40 | def export_public(self, path): |
| 41 | """Write the public key to the given file.""" |
| 42 | pem = self._get_public().public_bytes( |
| 43 | encoding=serialization.Encoding.PEM, |
| 44 | format=serialization.PublicFormat.SubjectPublicKeyInfo) |
| 45 | with open(path, 'wb') as f: |
| 46 | f.write(pem) |
| 47 | |
| 48 | def sig_type(self): |
| 49 | return "ECDSA256_SHA256" |
| 50 | |
| 51 | def sig_tlv(self): |
| 52 | return "ECDSA256" |
| 53 | |
| 54 | def sig_len(self): |
| 55 | # The DER encoding depends on the high bit, and can be |
| 56 | # anywhere from 70 to 72 bytes. Because we have to fill in |
| 57 | # the length field before computing the signature, however, |
| 58 | # we'll give the largest, and the sig checking code will allow |
| 59 | # for it to be up to two bytes larger than the actual |
| 60 | # signature. |
| 61 | return 72 |
| 62 | |
Fabio Utzig | 4a5477a | 2019-05-27 15:45:08 -0300 | [diff] [blame] | 63 | def verify(self, signature, payload): |
| 64 | k = self.key |
| 65 | if isinstance(self.key, ec.EllipticCurvePrivateKey): |
| 66 | k = self.key.public_key() |
| 67 | return k.verify(signature=signature, data=payload, |
| 68 | signature_algorithm=ec.ECDSA(SHA256())) |
| 69 | |
| 70 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 71 | class ECDSA256P1(ECDSA256P1Public): |
| 72 | """ |
| 73 | Wrapper around an ECDSA private key. |
| 74 | """ |
| 75 | |
| 76 | def __init__(self, key): |
| 77 | """key should be an instance of EllipticCurvePrivateKey""" |
| 78 | self.key = key |
| 79 | |
| 80 | @staticmethod |
| 81 | def generate(): |
| 82 | pk = ec.generate_private_key( |
| 83 | ec.SECP256R1(), |
| 84 | backend=default_backend()) |
| 85 | return ECDSA256P1(pk) |
| 86 | |
| 87 | def _get_public(self): |
| 88 | return self.key.public_key() |
| 89 | |
Ioannis Konstantelias | 78e57c7 | 2019-11-28 16:06:12 +0200 | [diff] [blame^] | 90 | def _build_minimal_ecdsa_privkey(self, der): |
| 91 | ''' |
| 92 | Builds a new DER that only includes the EC private key, removing the |
| 93 | public key that is added as an "optional" BITSTRING. |
| 94 | ''' |
| 95 | offset_PUB = 68 |
| 96 | EXCEPTION_TEXT = "Error parsing ecdsa key. Please submit an issue!" |
| 97 | if der[offset_PUB] != 0xa1: |
| 98 | raise ECDSAUsageError(EXCEPTION_TEXT) |
| 99 | len_PUB = der[offset_PUB + 1] |
| 100 | b = bytearray(der[:-offset_PUB]) |
| 101 | offset_SEQ = 29 |
| 102 | if b[offset_SEQ] != 0x30: |
| 103 | raise ECDSAUsageError(EXCEPTION_TEXT) |
| 104 | b[offset_SEQ + 1] -= len_PUB |
| 105 | offset_OCT_STR = 27 |
| 106 | if b[offset_OCT_STR] != 0x04: |
| 107 | raise ECDSAUsageError(EXCEPTION_TEXT) |
| 108 | b[offset_OCT_STR + 1] -= len_PUB |
| 109 | if b[0] != 0x30 or b[1] != 0x81: |
| 110 | raise ECDSAUsageError(EXCEPTION_TEXT) |
| 111 | b[2] -= len_PUB |
| 112 | return b |
| 113 | |
| 114 | def get_private_bytes(self, minimal): |
| 115 | priv = self.key.private_bytes( |
| 116 | encoding=serialization.Encoding.DER, |
| 117 | format=serialization.PrivateFormat.PKCS8, |
| 118 | encryption_algorithm=serialization.NoEncryption()) |
| 119 | if minimal: |
| 120 | priv = self._build_minimal_ecdsa_privkey(priv) |
| 121 | return priv |
| 122 | |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 123 | def export_private(self, path, passwd=None): |
| 124 | """Write the private key to the given file, protecting it with the optional password.""" |
| 125 | if passwd is None: |
| 126 | enc = serialization.NoEncryption() |
| 127 | else: |
| 128 | enc = serialization.BestAvailableEncryption(passwd) |
| 129 | pem = self.key.private_bytes( |
| 130 | encoding=serialization.Encoding.PEM, |
| 131 | format=serialization.PrivateFormat.PKCS8, |
| 132 | encryption_algorithm=enc) |
| 133 | with open(path, 'wb') as f: |
| 134 | f.write(pem) |
| 135 | |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 136 | def raw_sign(self, payload): |
| 137 | """Return the actual signature""" |
David Brown | b6e0ae6 | 2017-11-21 15:13:04 -0700 | [diff] [blame] | 138 | return self.key.sign( |
| 139 | data=payload, |
| 140 | signature_algorithm=ec.ECDSA(SHA256())) |
David Brown | 2c9153a | 2017-11-21 15:18:12 -0700 | [diff] [blame] | 141 | |
| 142 | def sign(self, payload): |
| 143 | # To make fixed length, pad with one or two zeros. |
| 144 | sig = self.raw_sign(payload) |
| 145 | sig += b'\000' * (self.sig_len() - len(sig)) |
| 146 | return sig |