1 // Copyright 2021 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #define PW_LOG_MODULE_NAME "ECDSA-UECC"
15 #define PW_LOG_LEVEL PW_LOG_LEVEL_WARN
16
17 #include "pw_crypto/ecdsa.h"
18 #include "pw_log/log.h"
19 #include "uECC.h"
20
21 namespace pw::crypto::ecdsa {
22
23 constexpr size_t kP256CurveOrderBytes = 32;
24
VerifyP256Signature(ConstByteSpan public_key,ConstByteSpan digest,ConstByteSpan signature)25 Status VerifyP256Signature(ConstByteSpan public_key,
26 ConstByteSpan digest,
27 ConstByteSpan signature) {
28 const uint8_t* public_key_bytes =
29 reinterpret_cast<const uint8_t*>(public_key.data());
30 const uint8_t* digest_bytes = reinterpret_cast<const uint8_t*>(digest.data());
31 const uint8_t* signature_bytes =
32 reinterpret_cast<const uint8_t*>(signature.data());
33
34 uECC_Curve curve = uECC_secp256r1();
35
36 // Supports SEC 1 uncompressed form (04||X||Y) only.
37 if (public_key.size() != (2 * kP256CurveOrderBytes + 1) ||
38 public_key_bytes[0] != 0x04) {
39 PW_LOG_DEBUG("Bad public key format");
40 return Status::InvalidArgument();
41 }
42
43 // Make sure the public key is on the curve.
44 if (!uECC_valid_public_key(public_key_bytes + 1, curve)) {
45 return Status::InvalidArgument();
46 }
47
48 // Signature expected in raw format (r||s)
49 if (signature.size() != kP256CurveOrderBytes * 2) {
50 PW_LOG_DEBUG("Bad signature format");
51 return Status::InvalidArgument();
52 }
53
54 // Digests must be at least 32 bytes. Digests longer than 32
55 // bytes are truncated to 32 bytes.
56 if (digest.size() < kP256CurveOrderBytes) {
57 PW_LOG_DEBUG("Digest is too short");
58 return Status::InvalidArgument();
59 }
60
61 // Verify the signature.
62 if (!uECC_verify(public_key_bytes + 1,
63 digest_bytes,
64 digest.size(),
65 signature_bytes,
66 curve)) {
67 PW_LOG_DEBUG("Signature verification failed");
68 return Status::Unauthenticated();
69 }
70
71 return OkStatus();
72 }
73
74 } // namespace pw::crypto::ecdsa
75