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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
/* SPDX-License-Identifier: GPL-2.0-or-later
* Copyright (C) 2023 Eneas Ulir de Queiroz
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "uencrypt.h"
static void check_enc_dec(const int enc)
{
if (enc == -1)
return;
fprintf(stderr, "Error: both -d and -e were specified.\n");
exit(EXIT_FAILURE);
}
static void show_usage(const char* name)
{
fprintf(stderr, "Usage: %s: [-d | -e] [-n] -k key [-i iv] [-c cipher]\n"
"-d = decrypt; -e = encrypt; -n = no padding\n", name);
}
static void uencrypt_clear_free(void *ptr, size_t len)
{
if (ptr) {
memset(ptr, 0, len);
free(ptr);
}
}
int main(int argc, char *argv[])
{
int enc = -1;
unsigned char *iv = NULL;
unsigned char *key = NULL;
long keylen = 0, ivlen = 0;
int opt;
int padding = 1;
const cipher_t *cipher = get_default_cipher();
ctx_t* ctx;
int ret = EXIT_FAILURE;
while ((opt = getopt(argc, argv, "c:dei:k:n")) != -1) {
switch (opt) {
case 'c':
if (!(cipher = get_cipher_or_print_error(optarg)))
exit(EXIT_FAILURE);
break;
case 'd':
check_enc_dec(enc);
enc = 0;
break;
case 'e':
check_enc_dec(enc);
enc = 1;
break;
case 'i':
iv = hexstr2buf(optarg, &ivlen);
if (iv == NULL) {
fprintf(stderr, "Error setting IV to %s. The IV should be encoded in hex.\n",
optarg);
exit(EINVAL);
}
memset(optarg, '*', strlen(optarg));
break;
case 'k':
key = hexstr2buf(optarg, &keylen);
if (key == NULL) {
fprintf(stderr, "Error setting key to %s. The key should be encoded in hex.\n",
optarg);
exit(EINVAL);
}
memset(optarg, '*', strlen(optarg));
break;
case 'n':
padding = 0;
break;
default:
show_usage(argv[0]);
exit(EINVAL);
}
}
if (ivlen != get_cipher_ivsize(cipher)) {
fprintf(stderr, "Error: IV must be %d bytes; given IV is %ld bytes.\n",
get_cipher_ivsize(cipher), ivlen);
exit(EXIT_FAILURE);
}
if (keylen != get_cipher_keysize(cipher)) {
fprintf(stderr, "Error: key must be %d bytes; given key is %ld bytes.\n",
get_cipher_keysize(cipher), keylen);
exit(EXIT_FAILURE);
}
ctx = create_ctx(cipher, key, iv, !!enc, padding);
if (ctx) {
ret = do_crypt(stdin, stdout, ctx);
free_ctx(ctx);
}
uencrypt_clear_free(iv, ivlen);
uencrypt_clear_free(key, keylen);
return ret;
}
|