/* Copyright (c) 2020-2021 The Creators of Simphone

   See the file COPYING.LESSER.txt for copying permission.
*/

#ifndef _KEYGEN_H_
#define _KEYGEN_H_

#include "simtypes.h"

#define FILE_KEY "key"
#define FILE_CONTACTS "contacts"

/* convert seed of specified type to dynamically-allocated numeric
   or alphabetical (if numeric = false) ASCII string and return SIMSTRING */
simtype convert_seed_to_string (const simtype seed, unsigned type, simbool numeric);

/* convert ASCII string to binary seed and return the seed as dynamically-allocated SIMSTRING.
   set the seed *type which will be SIM_KEY_NONE in case of failure, in which case the returned string indicates
   which part of the input string was not recognized. can be nil if the string is totally wrong */
simtype convert_string_to_seed (const char *string, unsigned *type);

/* initialize random buffer */
void random_buffer_init (simrandom generator);

/* add the specified number of entropy bits and return new number of bits (and bytes in *bytes) currently in random buffer */
unsigned random_buffer_add_bits (simrandom generator, unsigned bits, unsigned *bytes);

/* add audio data to random buffer */
void random_buffer_add (simrandom generator, const void *input, unsigned length, unsigned maxlen);

/* add extra data to random buffer */
void random_buffer_xor (simrandom generator, const simbyte *input, unsigned length);

/* initialize specified random generator with audio entropy. split entropy to equal parts and use (1-based) part */
simbool random_buffer_open (simrandom generator, unsigned part, unsigned parts);

/* release random buffer */
void random_buffer_close (simrandom generator);

/* return system or own (if myself = true) EC and RSA public key */
simtype key_get (simbool myself, simtype *ec, simtype *rsa);

/* generate random seed with the specified number of bits. return nil if not enough entropy present or else SIMSTRING */
simtype key_generate_seed (int size);

/* generate keytest.h */
int key_generate_test_ (void);

/* generate RSA/EC keys of specified size from specified seed or randomly if type is SIM_KEY_NONE.
   consumes both password and seed unless nil */
int key_generate_key (unsigned *decrement, simtype password, simtype seed, unsigned type);

#define KEY_MODE_KILL 0 /* delete saved key */
#define KEY_MODE_SAVE 1 /* set password */
#define KEY_MODE_MAKE 2 /* newly generated key */
#define KEY_MODE_LOAD 4 /* login */

/* save (generated) keys. mode is KEY_MODE_xxx */
int key_save_ (int mode);

/* load the private key file */
int key_init_ (const char *password);

/* release the loaded private key */
void key_uninit (void);

/* dump private key */
void key_log_private (const char *module, int level);

/* perform speed tests with the specified minimal number of seconds per test */
void print_speed_ (unsigned seconds);

#endif
