home /
secrets /
src /
core /
secret.c
secret.c
//
// secret.c
// secrets
//
// Created by Anders on 08/07/2020.
//
#include <stdlib.h>
#include <string.h>
#include "secret.h"
#include "../util/stringu.h"
#include "../util/require.h"
#include "../util/hexstring.h"
Secret* secret_from_line_alloc(const char *line) {
char *copy = stringu_copy_alloc(line);
stringu_trim(copy);
char* split[5];
stringu_split(copy, split, "-");
Secret *secret = calloc(1, sizeof(*secret));
hexstring_to_bin(secret->salt, split[0], SALT_SIZE);
hexstring_to_bin(secret->nonce, split[1], NONCE_SIZE);
hexstring_to_bin(secret->mac, split[2], MAC_SIZE);
require(strlen(split[3]) % 2 == 0, "unexpected sequence size");
uint16_t cipher_seq_len = (uint16_t) strlen(split[3]) / 2;
secret->cipher = malloc(cipher_seq_len);
secret->cipher_size = cipher_seq_len;
hexstring_to_bin(secret->cipher, split[3], cipher_seq_len);
free(copy);
return secret;
}
void secret_free(Secret* secret) {
free(secret->cipher);
free(secret);
}
char* secret_to_line_alloc(const Secret *secret) {
uint32_t line_len = (SALT_SIZE + NONCE_SIZE + MAC_SIZE + secret->cipher_size) * 2 + 4;
char* line = malloc(line_len);
char* next = line;
next = hexstring_from_bin(next, secret->salt, SALT_SIZE);
*next++ = '-';
next = hexstring_from_bin(next, secret->nonce, NONCE_SIZE);
*next++ = '-';
next = hexstring_from_bin(next, secret->mac, MAC_SIZE);
*next++ = '-';
next = hexstring_from_bin(next, secret->cipher, secret->cipher_size);
*next++ = '\0';
return line;
}