crypto: improve key handling
[vpp.git] / src / plugins / crypto_ia32 / aes_cbc.c
index 281cc83..7befdd2 100644 (file)
@@ -95,10 +95,12 @@ aesni_ops_enc_aes_cbc (vlib_main_t * vm, vnet_crypto_op_t * ops[],
                                                         vm->thread_index);
   int rounds = AESNI_KEY_ROUNDS (ks);
   u8 dummy[8192];
-  u8 *src[4], *dst[4], *key[4];
+  u8 *src[4] = { };
+  u8 *dst[4] = { };
+  vnet_crypto_key_index_t key_index[4] = { ~0, ~0, ~0, ~0 };
   u32x4 dummy_mask, len = { };
   u32 i, j, count, n_left = n_ops;
-  __m128i r[4], k[4][rounds + 1];
+  __m128i r[4] = { }, k[4][rounds + 1];
 
 more:
   for (i = 0; i < 4; i++)
@@ -125,10 +127,13 @@ more:
            dst[i] = ops[0]->dst;
            len[i] = ops[0]->len;
            dummy_mask[i] = ~0;
-           if (key[i] != ops[0]->key)
+           if (key_index[i] != ops[0]->key_index)
              {
-               aes_key_expand (k[i], ops[0]->key, ks);
-               key[i] = ops[0]->key;
+               aesni_key_data_t *kd;
+               key_index[i] = ops[0]->key_index;
+               kd = (aesni_key_data_t *) cm->key_data[key_index[i]];
+               clib_memcpy_fast (k[i], kd->encrypt_key,
+                                 (rounds + 1) * sizeof (__m128i));
              }
            ops[0]->status = VNET_CRYPTO_OP_STATUS_COMPLETED;
            n_left--;
@@ -186,23 +191,25 @@ static_always_inline u32
 aesni_ops_dec_aes_cbc (vlib_main_t * vm, vnet_crypto_op_t * ops[],
                       u32 n_ops, aesni_key_size_t ks)
 {
+  crypto_ia32_main_t *cm = &crypto_ia32_main;
   int rounds = AESNI_KEY_ROUNDS (ks);
-  u8 *last_key = 0;
-  u32 i;
-  __m128i k[rounds + 1];
+  vnet_crypto_op_t *op = ops[0];
+  aesni_key_data_t *kd = (aesni_key_data_t *) cm->key_data[op->key_index];
+  u32 n_left = n_ops;
+
+  ASSERT (n_ops >= 1);
+
+decrypt:
+  aes_cbc_dec (kd->decrypt_key, op->src, op->dst, op->iv, op->len, rounds);
+  op->status = VNET_CRYPTO_OP_STATUS_COMPLETED;
 
-  for (i = 0; i < n_ops; i++)
+  if (--n_left)
     {
-      vnet_crypto_op_t *op = ops[i];
-      if (last_key != op->key)
-       {
-         aes_key_expand (k, op->key, ks);
-         last_key = op->key;
-         aes_key_enc_to_dec (k, rounds);
-       }
-      aes_cbc_dec (k, op->src, op->dst, op->iv, op->len, rounds);
-      op->status = VNET_CRYPTO_OP_STATUS_COMPLETED;
+      op += 1;
+      kd = (aesni_key_data_t *) cm->key_data[op->key_index];
+      goto decrypt;
     }
+
   return n_ops;
 }
 
@@ -237,7 +244,8 @@ crypto_ia32_aesni_cbc_init (vlib_main_t * vm)
     {
       for (int i = 0; i < 4; i++)
        {
-         if (read(fd, ptd->cbc_iv, sizeof (ptd->cbc_iv)) < 0)
+         if (read(fd, ptd->cbc_iv, sizeof (ptd->cbc_iv)) !=
+             sizeof (ptd->cbc_iv))
            {
              err = clib_error_return_unix (0, "'/dev/urandom' read failure");
              goto error;