Blame view

RIOT/sys/crypto/modes/cbc.c 2.26 KB
a752c7ab   elopes   add first test an...
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
  /*
   * Copyright (C) 2015 Freie Universitรคt Berlin
   *
   * This file is subject to the terms and conditions of the GNU Lesser
   * General Public License v2.1. See the file LICENSE in the top level
   * directory for more details.
   */
  
  /**
   * @ingroup     sys_crypto_modes
   * @{
   *
   * @file
   * @brief       Crypto mode - cipher block chaining
   *
   * @author      Nico von Geyso <nico.geyso@fu-berlin.de>
   *
   * @}
   */
  
  
  #include <string.h>
  #include "crypto/modes/cbc.h"
  
  int cipher_encrypt_cbc(cipher_t* cipher, uint8_t iv[16],
                         const uint8_t* input, size_t length, uint8_t* output)
  {
      size_t offset = 0;
      uint8_t block_size, input_block[CIPHER_MAX_BLOCK_SIZE] = {0},
              *output_block_last;
  
      block_size = cipher_get_block_size(cipher);
      if (length % block_size != 0) {
          return CIPHER_ERR_INVALID_LENGTH;
      }
  
      output_block_last = iv;
      do {
          /* CBC-Mode: XOR plaintext with ciphertext of (n-1)-th block */
          memcpy(input_block, input + offset, block_size);
          for (int i = 0; i < block_size; ++i) {
              input_block[i] ^= output_block_last[i];
          }
  
          if (cipher_encrypt(cipher, input_block, output + offset) != 1) {
              return CIPHER_ERR_ENC_FAILED;
          }
  
          output_block_last = output + offset;
          offset += block_size;
      } while (offset < length);
  
      return offset;
  }
  
  
  int cipher_decrypt_cbc(cipher_t* cipher, uint8_t iv[16],
                         const uint8_t* input, size_t length, uint8_t* output)
  {
      size_t offset = 0;
      const uint8_t *input_block, *input_block_last;
      uint8_t block_size;
  
  
      block_size = cipher_get_block_size(cipher);
      if (length % block_size != 0) {
          return CIPHER_ERR_INVALID_LENGTH;
      }
  
      input_block_last = iv;
      do {
          input_block = input + offset;
          uint8_t *output_block = output + offset;
  
          if (cipher_decrypt(cipher, input_block, output_block) != 1) {
              return CIPHER_ERR_DEC_FAILED;
          }
  
          /* CBC-Mode: XOR plaintext with ciphertext of (n-1)-th block */
          for (uint8_t i = 0; i < block_size; ++i) {
              output_block[i] ^= input_block_last[i];
          }
  
          input_block_last = input_block;
          offset += block_size;
      } while (offset < length);
  
      return offset;
  }