Skip to content

Add JWS utility #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 3 additions & 54 deletions src/ECP256Certificate.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
/* This is needed for memmem */
#define _GNU_SOURCE
#include <string.h>
#include <utility/SElementBase64.h>
#include "ECP256Certificate.h"

/******************************************************************************
Expand All @@ -29,58 +30,6 @@
#define ASN1_SEQUENCE 0x30
#define ASN1_SET 0x31

/******************************************************************************
* LOCAL MODULE FUNCTIONS
******************************************************************************/

static String base64Encode(const byte in[], unsigned int length, const char* prefix, const char* suffix) {
static const char* CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

int b;
String out;

int reserveLength = 4 * ((length + 2) / 3) + ((length / 3 * 4) / 76) + strlen(prefix) + strlen(suffix);
out.reserve(reserveLength);

if (prefix) {
out += prefix;
}

for (unsigned int i = 0; i < length; i += 3) {
if (i > 0 && (i / 3 * 4) % 76 == 0) {
out += '\n';
}

b = (in[i] & 0xFC) >> 2;
out += CODES[b];

b = (in[i] & 0x03) << 4;
if (i + 1 < length) {
b |= (in[i + 1] & 0xF0) >> 4;
out += CODES[b];
b = (in[i + 1] & 0x0F) << 2;
if (i + 2 < length) {
b |= (in[i + 2] & 0xC0) >> 6;
out += CODES[b];
b = in[i + 2] & 0x3F;
out += CODES[b];
} else {
out += CODES[b];
out += '=';
}
} else {
out += CODES[b];
out += "==";
}
}

if (suffix) {
out += suffix;
}

return out;
}

/******************************************************************************
* CTOR/DTOR
******************************************************************************/
Expand Down Expand Up @@ -184,7 +133,7 @@ int ECP256Certificate::signCSR(byte * signature)

String ECP256Certificate::getCSRPEM()
{
return base64Encode(_certBuffer, _certBufferLen, "-----BEGIN CERTIFICATE REQUEST-----\n", "\n-----END CERTIFICATE REQUEST-----\n");
return b64::pemEncode(_certBuffer, _certBufferLen, "-----BEGIN CERTIFICATE REQUEST-----\n", "\n-----END CERTIFICATE REQUEST-----\n");
}

int ECP256Certificate::buildCert()
Expand Down Expand Up @@ -323,7 +272,7 @@ int ECP256Certificate::signCert()

String ECP256Certificate::getCertPEM()
{
return base64Encode(_certBuffer, _certBufferLen, "-----BEGIN CERTIFICATE-----\n", "\n-----END CERTIFICATE-----\n");
return b64::pemEncode(_certBuffer, _certBufferLen, "-----BEGIN CERTIFICATE-----\n", "\n-----END CERTIFICATE-----\n");
}

void ECP256Certificate::getDateFromCompressedData(DateInfo& date) {
Expand Down
7 changes: 5 additions & 2 deletions src/ECP256Certificate.h
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@ class ECP256Certificate {
/* Import DER buffer into CertClass*/
int importCert(const byte certDER[], size_t derLen);

protected:

int publicKeyLength();
int appendPublicKey(const byte publicKey[], byte out[]);

private:

struct CertInfo {
Expand Down Expand Up @@ -154,7 +159,6 @@ class ECP256Certificate {
int versionLength();
int issuerOrSubjectLength(const CertInfo& issuerOrSubjectData);
int sequenceHeaderLength(int length);
int publicKeyLength();
int signatureLength(const byte signature[]);
int serialNumberLength(const byte serialNumber[], int length);
int authorityKeyIdLength(const byte authorityKeyId[], int length);
Expand All @@ -171,7 +175,6 @@ class ECP256Certificate {
int appendVersion(int version, byte out[]);
int appendName(const String& name, int type, byte out[]);
int appendIssuerOrSubject(const CertInfo& issuerOrSubjectData, byte out[]);
int appendPublicKey(const byte publicKey[], byte out[]);
int appendSignature(const byte signature[], byte out[]);
int appendSerialNumber(const byte serialNumber[], int length, byte out[]);
int appendDate(int year, int month, int day, int hour, int minute, int second, byte out[]);
Expand Down
23 changes: 23 additions & 0 deletions src/utility/SElementArduinoCloudJWT.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
This file is part of the Arduino_SecureElement library.

Copyright (c) 2024 Arduino SA

This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "SElementArduinoCloudJWT.h"

constexpr char JWT_HEADER[] = "{\"alg\":\"ES256\",\"typ\":\"JWT\"}";
String getAIoTCloudJWT(SecureElement &se, String issuer, uint64_t iat, uint8_t slot)
{
SElementJWS jws;
String jwtClaim = "{\"iat\":";
jwtClaim += String((uint32_t)iat);
jwtClaim += ",\"iss\":\"";
jwtClaim += issuer;
jwtClaim += "\"}";
String token = jws.sign(se, slot, JWT_HEADER, jwtClaim.c_str());
return token;
}
17 changes: 17 additions & 0 deletions src/utility/SElementArduinoCloudJWT.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*
This file is part of the Arduino_SecureElement library.

Copyright (c) 2024 Arduino SA

This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

#ifndef SECURE_ELEMENT_AIoTCloud_JWT_H_
#define SECURE_ELEMENT_AIoTCloud_JWT_H_
#include "SElementJWS.h"

String getAIoTCloudJWT(SecureElement &se, String issuer, uint64_t iat, uint8_t slot = 1);

#endif
101 changes: 101 additions & 0 deletions src/utility/SElementBase64.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
This file is part of the Arduino_SecureElement library.

Copyright (c) 2024 Arduino SA

This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

#include <utility/SElementBase64.h>

namespace arduino { namespace b64 {

String urlEncode(const byte in[], unsigned int length) {
static const char* CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=";

int b;
String out;

int reserveLength = 4 * ((length + 2) / 3);
out.reserve(reserveLength);

for (unsigned int i = 0; i < length; i += 3) {
b = (in[i] & 0xFC) >> 2;
out += CODES[b];

b = (in[i] & 0x03) << 4;
if (i + 1 < length) {
b |= (in[i + 1] & 0xF0) >> 4;
out += CODES[b];
b = (in[i + 1] & 0x0F) << 2;
if (i + 2 < length) {
b |= (in[i + 2] & 0xC0) >> 6;
out += CODES[b];
b = in[i + 2] & 0x3F;
out += CODES[b];
} else {
out += CODES[b];
}
} else {
out += CODES[b];
}
}

while (out.lastIndexOf('=') != -1) {
out.remove(out.length() - 1);
}

return out;
}

String pemEncode(const byte in[], unsigned int length, const char* prefix, const char* suffix) {
static const char* CODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

int b;
String out;

int reserveLength = 4 * ((length + 2) / 3) + ((length / 3 * 4) / 76) + strlen(prefix) + strlen(suffix);
out.reserve(reserveLength);

if (prefix) {
out += prefix;
}

for (unsigned int i = 0; i < length; i += 3) {
if (i > 0 && (i / 3 * 4) % 76 == 0) {
out += '\n';
}

b = (in[i] & 0xFC) >> 2;
out += CODES[b];

b = (in[i] & 0x03) << 4;
if (i + 1 < length) {
b |= (in[i + 1] & 0xF0) >> 4;
out += CODES[b];
b = (in[i + 1] & 0x0F) << 2;
if (i + 2 < length) {
b |= (in[i + 2] & 0xC0) >> 6;
out += CODES[b];
b = in[i + 2] & 0x3F;
out += CODES[b];
} else {
out += CODES[b];
out += '=';
}
} else {
out += CODES[b];
out += "==";
}
}

if (suffix) {
out += suffix;
}

return out;
}

}} // arduino::b64
20 changes: 20 additions & 0 deletions src/utility/SElementBase64.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
This file is part of the Arduino_SecureElement library.

Copyright (c) 2024 Arduino SA

This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

#pragma once

#include <Arduino.h>

namespace arduino { namespace b64 {

String urlEncode(const byte in[], unsigned int length);
String pemEncode(const byte in[], unsigned int length, const char* prefix, const char* suffix);

}} // arduino::b64
85 changes: 85 additions & 0 deletions src/utility/SElementJWS.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
This file is part of the Arduino_SecureElement library.

Copyright (c) 2024 Arduino SA

This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/******************************************************************************
* INCLUDE
******************************************************************************/

#include <utility/SElementJWS.h>
#include <utility/SElementBase64.h>

String SElementJWS::publicKey(SecureElement & se, int slot, bool newPrivateKey)
{
if (slot < 0 || slot > 8) {
return "";
}

byte publicKey[64];

if (newPrivateKey) {
if (!se.generatePrivateKey(slot, publicKey)) {
return "";
}
} else {
if (!se.generatePublicKey(slot, publicKey)) {
return "";
}
}

int length = publicKeyLength();
byte out[length];

appendPublicKey(publicKey, out);

return b64::pemEncode(out, length, "-----BEGIN PUBLIC KEY-----\n", "\n-----END PUBLIC KEY-----\n");
}

String SElementJWS::sign(SecureElement & se, int slot, const char* header, const char* payload)
{
if (slot < 0 || slot > 8) {
return "";
}

String encodedHeader = b64::urlEncode((const byte*)header, strlen(header));
String encodedPayload = b64::urlEncode((const byte*)payload, strlen(payload));

String toSign;
toSign.reserve(encodedHeader.length() + 1 + encodedPayload.length());

toSign += encodedHeader;
toSign += '.';
toSign += encodedPayload;


byte toSignSha256[32];
byte signature[64];

se.SHA256((const uint8_t*)toSign.c_str(), toSign.length(), toSignSha256);

if (!se.ecSign(slot, toSignSha256, signature)) {
return "";
}

String encodedSignature = b64::urlEncode(signature, sizeof(signature));

String result;
result.reserve(toSign.length() + 1 + encodedSignature.length());

result += toSign;
result += '.';
result += encodedSignature;

return result;
}

String SElementJWS::sign(SecureElement & se, int slot, const String& header, const String& payload)
{
return sign(se, slot, header.c_str(), payload.c_str());
}
Loading