RSA *rsa;
};
+static int openssl_perror(const char *pfx)
+{
+ unsigned long err = ERR_get_error();
+ PARA_ERROR_LOG("%s: \"%s\"\n", pfx, ERR_reason_error_string(err));
+ return -E_OPENSSL;
+}
+
void get_random_bytes_or_die(unsigned char *buf, int num)
{
- unsigned long err;
+ int ret;
- /* RAND_bytes() returns 1 on success, 0 otherwise. */
- if (RAND_bytes(buf, num) == 1)
+ if (RAND_bytes(buf, num) == 1) /* success */
return;
- err = ERR_get_error();
- PARA_EMERG_LOG("%s\n", ERR_reason_error_string(err));
+ ret = openssl_perror("RAND_bytes");
+ PARA_EMERG_LOG("%s\n", strerror(-ret));
exit(EXIT_FAILURE);
}
BIGNUM *n, *e;
const unsigned char *p = blob, *end = blob + blen;
- rsa = RSA_new();
- if (!rsa)
- return -E_BIGNUM;
+ assert((rsa = RSA_new()));
ret = read_bignum(p, end - p, &e);
if (ret < 0)
goto free_rsa;
static int read_pem_private_key(const char *path, struct asymmetric_key *priv)
{
EVP_PKEY *pkey;
- BIO *bio = BIO_new(BIO_s_file());
+ BIO *bio;
+ assert((bio = BIO_new(BIO_s_file())));
priv->rsa = NULL;
- if (!bio)
- return -E_PRIVATE_KEY;
if (BIO_read_filename(bio, path) <= 0)
goto bio_free;
pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL);
BIGNUM *n, *e, *d, *iqmp, *p, *q; /* stored in the key file */
const unsigned char *cp = blob;
- rsa = RSA_new();
- if (!rsa)
- return -E_BIGNUM;
+ assert((rsa = RSA_new()));
ret = read_bignum(cp, end - cp, &n);
if (ret < 0)
goto free_rsa;
}
int apc_pub_encrypt(struct asymmetric_key *pub, unsigned char *inbuf,
- unsigned len, unsigned char *outbuf)
+ unsigned len, unsigned char **outbuf)
{
int ret, flen = len; /* RSA_public_encrypt expects a signed int */
+ *outbuf = NULL;
if (flen < 0)
return -E_ENCRYPT;
- ret = RSA_public_encrypt(flen, inbuf, outbuf, pub->rsa,
+ *outbuf = alloc(RSA_size(pub->rsa));
+ ret = RSA_public_encrypt(flen, inbuf, *outbuf, pub->rsa,
RSA_PKCS1_OAEP_PADDING);
- return ret < 0? -E_ENCRYPT : ret;
+ if (ret < 0) {
+ free(*outbuf);
+ *outbuf = NULL;
+ return -E_ENCRYPT;
+ }
+ return ret;
}
struct stream_cipher {
struct stream_cipher *sc = alloc(sizeof(*sc));
assert(len >= 2 * AES_CRT128_BLOCK_SIZE);
- sc->aes = EVP_CIPHER_CTX_new();
+ assert((sc->aes = EVP_CIPHER_CTX_new()));
EVP_EncryptInit_ex(sc->aes, EVP_aes_128_ctr(), NULL, data,
data + AES_CRT128_BLOCK_SIZE);
return sc;
void hash_function(const char *data, unsigned long len, unsigned char *hash)
{
- EVP_MD_CTX *c = EVP_MD_CTX_new();
- int ret = EVP_DigestInit_ex(c, EVP_sha1(), NULL);
+ int ret;
+ EVP_MD_CTX *c;
+
+ assert((c = EVP_MD_CTX_new()));
+ ret = EVP_DigestInit_ex(c, EVP_sha1(), NULL);
assert(ret != 0);
ret = EVP_DigestUpdate(c, data, len);
assert(ret != 0);
void hash2_function(const char *data, unsigned long len, unsigned char *hash)
{
- EVP_MD_CTX *c = EVP_MD_CTX_new();
- int ret = EVP_DigestInit_ex(c, EVP_sha256(), NULL);
+ int ret;
+ EVP_MD_CTX *c;
+
+ assert((c = EVP_MD_CTX_new()));
+ ret = EVP_DigestInit_ex(c, EVP_sha256(), NULL);
assert(ret != 0);
ret = EVP_DigestUpdate(c, data, len);
assert(ret != 0);