#include <stdint.h>
#include <stdbool.h>
#include <limits.h>
+#include <string.h>
#include <openssl/evp.h>
return YACA_ERROR_NONE;
}
+static int key_copy_simple(const yaca_key_h key, yaca_key_h *out)
+{
+ assert(key != YACA_KEY_NULL);
+ assert(out != NULL);
+
+ int ret;
+ struct yaca_key_simple_s *simple = key_get_simple(key);
+ assert(simple != NULL);
+
+ struct yaca_key_simple_s *copy;
+ size_t size = sizeof(struct yaca_key_simple_s) + simple->bit_len / 8;
+
+ ret = yaca_zalloc(size, (void**)©);
+ if (ret != YACA_ERROR_NONE)
+ return ret;
+
+ memcpy(copy, key, size);
+ *out = (yaca_key_h)copy;
+ return YACA_ERROR_NONE;
+}
+
static int encrypt_ctx_backup(struct yaca_encrypt_context_s *c,
const EVP_CIPHER *cipher,
const yaca_key_h sym_key,
if (ret != YACA_ERROR_NONE)
return ret;
+ ret = key_copy_simple(sym_key, &bc->sym_key);
+ if (ret != YACA_ERROR_NONE)
+ goto err;
+ if (iv != YACA_KEY_NULL) {
+ ret = key_copy_simple(iv, &bc->iv);
+ if (ret != YACA_ERROR_NONE)
+ goto err;
+ }
bc->cipher = cipher;
- bc->sym_key = key_copy(sym_key);
- bc->iv = key_copy(iv);
bc->padding = YACA_PADDING_PKCS7;
c->backup_ctx = bc;
return YACA_ERROR_NONE;
+
+err:
+ yaca_key_destroy(bc->iv);
+ yaca_key_destroy(bc->sym_key);
+ yaca_free(bc);
+ return ret;
}
static int encrypt_ctx_restore(struct yaca_encrypt_context_s *c)
}
}
-static yaca_key_h key_copy_simple(const struct yaca_key_simple_s *key)
-{
- int ret;
- assert(key != NULL);
-
- struct yaca_key_simple_s *copy;
- size_t size = sizeof(struct yaca_key_simple_s) + key->bit_len / 8;
-
- ret = yaca_zalloc(size, (void**)©);
- if (ret != YACA_ERROR_NONE)
- return YACA_KEY_NULL;
-
- memcpy(copy, key, size);
- return (yaca_key_h)copy;
-}
-
-static yaca_key_h key_copy_evp(const struct yaca_key_evp_s *key)
-{
- int ret;
- assert(key != NULL);
-
- struct yaca_key_evp_s *copy = NULL;
- ret = yaca_zalloc(sizeof(struct yaca_key_evp_s), (void**)©);
- if (ret != YACA_ERROR_NONE)
- return YACA_KEY_NULL;
-
- /* raise the refcount */
- EVP_PKEY_up_ref(key->evp);
-
- copy->key.type = key->key.type;
- copy->evp = key->evp;
- return (yaca_key_h)copy;
-}
-
-yaca_key_h key_copy(const yaca_key_h key)
-{
- struct yaca_key_simple_s *simple = key_get_simple(key);
- struct yaca_key_evp_s *evp = key_get_evp(key);
-
- if (simple != NULL)
- return key_copy_simple(simple);
- else if (evp != NULL)
- return key_copy_evp(evp);
-
- return YACA_KEY_NULL;
-}
-
API int yaca_key_get_type(const yaca_key_h key, yaca_key_type_e *key_type)
{
const struct yaca_key_s *lkey = (const struct yaca_key_s *)key;