12 #include <Curve25519.h>
13 #include <ChaChaPoly.h>
21 const uint8_t HASH_LEN = 32;
23 uint8_t key[HASH_LEN];
25 if (length < HASH_LEN) {
26 DEBUG_ERROR (
"Too small buffer. Should be 32 bytes");
33 hash.update ((
void*)buffer, length);
34 hash.finalize (key, HASH_LEN);
43 if (length > HASH_LEN) {
47 memcpy (buffer, key, length);
53 const uint8_t* iv, uint8_t ivlen,
const uint8_t* key, uint8_t keylen,
54 const uint8_t* aad, uint8_t aadLen,
const uint8_t* tag, uint8_t tagLen) {
55 if (key && iv &&
data) {
62 if (
cipher.setKey (key, keylen)) {
63 if (
cipher.setIV ((uint8_t*)iv, ivlen)) {
64 cipher.addAuthData ((uint8_t*)aad, aadLen);
66 bool ok =
cipher.checkTag ((uint8_t*)tag, tagLen);
70 DEBUG_ERROR (
"Data authentication error");
74 DEBUG_ERROR (
"Error setting IV");
77 DEBUG_ERROR (
"Error setting key");
80 DEBUG_ERROR (
"Error in key or IV");
87 const uint8_t* iv, uint8_t ivlen,
const uint8_t* key, uint8_t keylen,
88 const uint8_t* aad, uint8_t aadLen,
const uint8_t* tag, uint8_t tagLen) {
90 if (key && iv &&
data) {
97 if (
cipher.setKey ((uint8_t*)key, keylen)) {
98 if (
cipher.setIV ((uint8_t*)iv, ivlen)) {
99 cipher.addAuthData ((uint8_t*)aad, aadLen);
101 cipher.computeTag ((uint8_t*)tag, tagLen);
106 DEBUG_ERROR (
"Error setting IV");
109 DEBUG_ERROR (
"Error setting key");
112 DEBUG_ERROR (
"Error on input data for encryption");
121 return *(
volatile uint32_t*)RANDOM_32;
123 return esp_random ();
129 for (
unsigned int i = 0; i < len; i +=
sizeof (uint32_t)) {
131 if (i < len - (len %
sizeof (int32_t))) {
132 memcpy (
const_cast<uint8_t*
>(buf) + i, &rnd,
sizeof (uint32_t));
134 memcpy (
const_cast<uint8_t*
>(buf) + i, &rnd, len %
sizeof (int32_t));
138 return const_cast<uint8_t*
>(buf);
152 if (!Curve25519::dh2 (
const_cast<uint8_t*
>(remotePubKey),
privateDHKey)) {
153 DEBUG_WARN (
"DH2 error");