monocypher-demo/main.c
2025-08-24 15:24:05 +02:00

66 lines
1.7 KiB
C

#include "monocypher.h"
#include "seed.h"
#include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PRINT_HEX(arr, len) print_hex(#arr, (const uint8_t *)(arr), (len))
void print_hex(const char *name, const uint8_t *data, size_t len) {
printf("%s (%zu bytes):\n", name, len);
for (size_t i = 0; i < len; i++) {
if (i % 16 == 0)
printf(" %04zx: ", i);
printf("%02X ", data[i]);
if ((i + 1) % 16 == 0 || i + 1 == len)
printf("\n");
}
}
int main(void) {
/* These can be used if not on bare metal */
// uint8_t seed[32];
// arc4random_buf(seed, 32);
uint8_t seckey[64]; /* secret key */
uint8_t pubkey[32]; /* Matching public key */
PRINT_HEX(seed, seed_len);
/* The seed is wiped automatically here */
crypto_eddsa_key_pair(seckey, pubkey, seed);
PRINT_HEX(pubkey, 32);
PRINT_HEX(seckey, 64);
uint8_t message[4];
/* Generate a random message */
arc4random_buf(message, 4);
PRINT_HEX(message, sizeof(message));
uint8_t signature[64];
/* Sign it and store the signature in sig[] */
crypto_eddsa_sign(signature, seckey, (const uint8_t *)message, sizeof(message));
PRINT_HEX(signature, 64);
/* Assert valid */
assert(!crypto_eddsa_check(signature, pubkey, (const uint8_t *)message, sizeof(message)));
/* Tamper with payload to invalidate the signature */
arc4random_buf(message, 4);
PRINT_HEX(message, sizeof(message));
/* Assert invalid */
assert(crypto_eddsa_check(signature, pubkey, (const uint8_t *)message, sizeof(message)));
/* Wipe the secret key if it is no longer needed */
crypto_wipe(seckey, 32);
printf("Program finished: Ok!\n");
}