nostr_core_lib/examples/simple_keygen.c

96 lines
3.0 KiB
C

/*
* Simple Key Generation Example
*
* This example demonstrates basic NOSTR key generation using the nostr_core library.
*/
#include <stdio.h>
#include <stdlib.h>
#include "nostr_core.h"
int main() {
printf("NOSTR Core Library - Simple Key Generation Example\n");
printf("==================================================\n\n");
// Initialize the library
if (nostr_init() != NOSTR_SUCCESS) {
fprintf(stderr, "Failed to initialize NOSTR core library\n");
return 1;
}
printf("✓ NOSTR core library initialized\n\n");
// Generate a random keypair
unsigned char private_key[NOSTR_PRIVATE_KEY_SIZE];
unsigned char public_key[NOSTR_PUBLIC_KEY_SIZE];
printf("Generating random NOSTR keypair...\n");
int result = nostr_generate_keypair(private_key, public_key);
if (result != NOSTR_SUCCESS) {
fprintf(stderr, "Failed to generate keypair: %s\n", nostr_strerror(result));
nostr_cleanup();
return 1;
}
// Convert keys to hex format
char private_hex[NOSTR_HEX_KEY_SIZE];
char public_hex[NOSTR_HEX_KEY_SIZE];
nostr_bytes_to_hex(private_key, NOSTR_PRIVATE_KEY_SIZE, private_hex);
nostr_bytes_to_hex(public_key, NOSTR_PUBLIC_KEY_SIZE, public_hex);
// Convert keys to bech32 format
char nsec_bech32[NOSTR_BECH32_KEY_SIZE];
char npub_bech32[NOSTR_BECH32_KEY_SIZE];
if (nostr_key_to_bech32(private_key, "nsec", nsec_bech32) != NOSTR_SUCCESS ||
nostr_key_to_bech32(public_key, "npub", npub_bech32) != NOSTR_SUCCESS) {
fprintf(stderr, "Failed to convert keys to bech32 format\n");
nostr_cleanup();
return 1;
}
// Display the generated keys
printf("✓ Keypair generated successfully!\n\n");
printf("Private Key (hex): %s\n", private_hex);
printf("Public Key (hex): %s\n", public_hex);
printf("nsec (bech32): %s\n", nsec_bech32);
printf("npub (bech32): %s\n", npub_bech32);
printf("\n=== Key Validation Test ===\n");
// Test key validation by decoding the generated nsec
unsigned char decoded_private_key[NOSTR_PRIVATE_KEY_SIZE];
result = nostr_decode_nsec(nsec_bech32, decoded_private_key);
if (result == NOSTR_SUCCESS) {
printf("✓ nsec validation: PASSED\n");
// Verify the decoded key matches the original
int keys_match = 1;
for (int i = 0; i < NOSTR_PRIVATE_KEY_SIZE; i++) {
if (private_key[i] != decoded_private_key[i]) {
keys_match = 0;
break;
}
}
if (keys_match) {
printf("✓ Key consistency: PASSED\n");
} else {
printf("✗ Key consistency: FAILED\n");
}
} else {
printf("✗ nsec validation: FAILED (%s)\n", nostr_strerror(result));
}
// Cleanup
nostr_cleanup();
printf("\nExample completed successfully!\n");
printf("You can now use these keys with NOSTR applications.\n");
return 0;
}