forked from vedantk/gcrypt-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcry.cc
82 lines (65 loc) · 2.4 KB
/
gcry.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "gcry.hh"
void xerr(const char* msg)
{
fprintf(stderr, "%s\n", msg);
exit(1);
}
void gcrypt_init()
{
/* Version check should be the very first call because it
makes sure that important subsystems are intialized. */
if (!gcry_check_version (GCRYPT_VERSION))
{
xerr("gcrypt: library version mismatch");
}
gcry_error_t err = 0;
/* We don't want to see any warnings, e.g. because we have not yet
parsed program options which might be used to suppress such
warnings. */
err = gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
/* ... If required, other initialization goes here. Note that the
process might still be running with increased privileges and that
the secure memory has not been intialized. */
/* Allocate a pool of 16k secure memory. This make the secure memory
available and also drops privileges where needed. */
err |= gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
/* It is now okay to let Libgcrypt complain when there was/is
a problem with the secure memory. */
err |= gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
/* ... If required, other initialization goes here. */
/* Tell Libgcrypt that initialization has completed. */
err |= gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
if (err) {
xerr("gcrypt: failed initialization");
}
}
size_t get_keypair_size(int nbits)
{
size_t aes_blklen = gcry_cipher_get_algo_blklen(GCRY_CIPHER_AES128);
return nbits * aes_blklen;
}
void get_aes_ctx(gcry_cipher_hd_t* aes_hd)
{
const size_t keylen = 16;
char passwd_hash[keylen];
char* passwd = getpass("Keypair Password: ");
size_t pass_len = passwd ? strlen(passwd) : 0;
if (pass_len == 0) {
xerr("getpass: not a valid password");
}
int err = gcry_cipher_open(aes_hd, GCRY_CIPHER_AES128,
GCRY_CIPHER_MODE_CFB, 0);
if (err) {
xerr("gcrypt: failed to create aes handle");
}
gcry_md_hash_buffer(GCRY_MD_MD5, (void*) &passwd_hash,
(const void*) passwd, pass_len);
err = gcry_cipher_setkey(*aes_hd, (const void*) &passwd_hash, keylen);
if (err) {
xerr("gcrypt: could not set cipher key");
}
err = gcry_cipher_setiv(*aes_hd, (const void*) &passwd_hash, keylen);
if (err) {
xerr("gcrypt: could not set cipher initialization vector");
}
}