|
| 1 | +/* |
| 2 | + This file is part of the Arduino_SecureElement library. |
| 3 | +
|
| 4 | + Copyright (c) 2024 Arduino SA |
| 5 | +
|
| 6 | + This Source Code Form is subject to the terms of the Mozilla Public |
| 7 | + License, v. 2.0. If a copy of the MPL was not distributed with this |
| 8 | + file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 9 | +*/ |
| 10 | + |
| 11 | +/****************************************************************************** |
| 12 | + * INCLUDE |
| 13 | + ******************************************************************************/ |
| 14 | + |
| 15 | +#include <utility/SElementJWS.h> |
| 16 | +#include <utility/SElementBase64.h> |
| 17 | + |
| 18 | +String SElementJWS::publicKey(SecureElement & se, int slot, bool newPrivateKey) |
| 19 | +{ |
| 20 | + if (slot < 0 || slot > 8) { |
| 21 | + return ""; |
| 22 | + } |
| 23 | + |
| 24 | + byte publicKey[64]; |
| 25 | + |
| 26 | + if (newPrivateKey) { |
| 27 | + if (!se.generatePrivateKey(slot, publicKey)) { |
| 28 | + return ""; |
| 29 | + } |
| 30 | + } else { |
| 31 | + if (!se.generatePublicKey(slot, publicKey)) { |
| 32 | + return ""; |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + int length = publicKeyLength(); |
| 37 | + byte out[length]; |
| 38 | + |
| 39 | + appendPublicKey(publicKey, out); |
| 40 | + |
| 41 | + return b64::pemEncode(out, length, "-----BEGIN PUBLIC KEY-----\n", "\n-----END PUBLIC KEY-----\n"); |
| 42 | +} |
| 43 | + |
| 44 | +String SElementJWS::sign(SecureElement & se, int slot, const char* header, const char* payload) |
| 45 | +{ |
| 46 | + if (slot < 0 || slot > 8) { |
| 47 | + return ""; |
| 48 | + } |
| 49 | + |
| 50 | + String encodedHeader = b64::urlEncode((const byte*)header, strlen(header)); |
| 51 | + String encodedPayload = b64::urlEncode((const byte*)payload, strlen(payload)); |
| 52 | + |
| 53 | + String toSign; |
| 54 | + toSign.reserve(encodedHeader.length() + 1 + encodedPayload.length()); |
| 55 | + |
| 56 | + toSign += encodedHeader; |
| 57 | + toSign += '.'; |
| 58 | + toSign += encodedPayload; |
| 59 | + |
| 60 | + |
| 61 | + byte toSignSha256[32]; |
| 62 | + byte signature[64]; |
| 63 | + |
| 64 | + se.SHA256((const uint8_t*)toSign.c_str(), toSign.length(), toSignSha256); |
| 65 | + |
| 66 | + if (!se.ecSign(slot, toSignSha256, signature)) { |
| 67 | + return ""; |
| 68 | + } |
| 69 | + |
| 70 | + String encodedSignature = b64::urlEncode(signature, sizeof(signature)); |
| 71 | + |
| 72 | + String result; |
| 73 | + result.reserve(toSign.length() + 1 + encodedSignature.length()); |
| 74 | + |
| 75 | + result += toSign; |
| 76 | + result += '.'; |
| 77 | + result += encodedSignature; |
| 78 | + |
| 79 | + return result; |
| 80 | +} |
| 81 | + |
| 82 | +String SElementJWS::sign(SecureElement & se, int slot, const String& header, const String& payload) |
| 83 | +{ |
| 84 | + return sign(se, slot, header.c_str(), payload.c_str()); |
| 85 | +} |
0 commit comments