tcp-chat/src/cli/modes/RsaGen.c

65 lines
1.7 KiB
C

#include "modes.h"
#include "cryptography/RSA.h"
Result(void) run_RsaGenStdin(u32 key_size) {
Deferral(4);
printfe("reading stdin...\n");
Array(u8) input_buf = Array_alloc_size(64*1024);
Defer(Array_free(input_buf));
br_hmac_drbg_context rng = { .vtable = &br_hmac_drbg_vtable };
br_hmac_drbg_init(&rng, &br_sha256_vtable, NULL, 0);
i64 read_n = 0;
do {
read_n = fread(input_buf.data, 1, input_buf.size, stdin);
if(read_n < 0){
Return RESULT_ERROR("ERROR: can't read stdin", false);
}
// put bytes to rng as seed
br_hmac_drbg_update(&rng, input_buf.data, read_n);
} while(read_n == input_buf.size);
printfe("generating RSA key pair based on stdin...\n");
br_rsa_private_key sk;
br_rsa_public_key pk;
try_void(RSA_generateKeyPair(key_size, &sk, &pk, &rng.vtable));
Defer(
RSA_destroyPrivateKey(&sk);
RSA_destroyPublicKey(&pk);
);
str sk_str = RSA_serializePrivateKey_base64(&sk);
printf("rsa_private_key = %s\n", sk_str.data);
str_free(sk_str);
str pk_str = RSA_serializePublicKey_base64(&pk);
printf("\nrsa_public_key = %s\n", pk_str.data);
str_free(pk_str);
Return RESULT_VOID;
}
Result(void) run_RsaGenRandom(u32 key_size) {
Deferral(4);
printfe("generating random RSA key pair...\n");
br_rsa_private_key sk;
br_rsa_public_key pk;
try_void(RSA_generateKeyPairFromSystemRandom(key_size, &sk, &pk));
Defer(
RSA_destroyPrivateKey(&sk);
RSA_destroyPublicKey(&pk);
);
str sk_str = RSA_serializePrivateKey_base64(&sk);
printf("rsa_private_key = %s\n", sk_str.data);
str_free(sk_str);
str pk_str = RSA_serializePublicKey_base64(&pk);
printf("\nrsa_public_key = %s\n", pk_str.data);
str_free(pk_str);
Return RESULT_VOID;
}