]> cvs.zerfleddert.de Git - proxmark3-svn/blob - common/polarssl/libpcrypto.c
9be9fd266e32105a6ce0bbc8021dad37eff03610
[proxmark3-svn] / common / polarssl / libpcrypto.c
1 //-----------------------------------------------------------------------------
2 // Copyright (C) 2018 Merlok
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // crypto commands
9 //-----------------------------------------------------------------------------
10
11 #include "polarssl/libpcrypto.h"
12 #include <polarssl/aes.h>
13 #include <polarssl/aes_cmac128.h>
14
15 // NIST Special Publication 800-38A \97 Recommendation for block cipher modes of operation: methods and techniques, 2001.
16 int aes_encode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length){
17 uint8_t iiv[16] = {0};
18 if (iv)
19 memcpy(iiv, iv, 16);
20
21 aes_context aes;
22 aes_init(&aes);
23 if (aes_setkey_enc(&aes, key, 128))
24 return 1;
25 if (aes_crypt_cbc(&aes, AES_ENCRYPT, length, iiv, input, output))
26 return 2;
27 aes_free(&aes);
28
29 return 0;
30 }
31
32 int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int length){
33 uint8_t iiv[16] = {0};
34 if (iv)
35 memcpy(iiv, iv, 16);
36
37 aes_context aes;
38 aes_init(&aes);
39 if (aes_setkey_dec(&aes, key, 128))
40 return 1;
41 if (aes_crypt_cbc(&aes, AES_DECRYPT, length, iiv, input, output))
42 return 2;
43 aes_free(&aes);
44
45 return 0;
46 }
47
48 // NIST Special Publication 800-38B \97 Recommendation for block cipher modes of operation: The CMAC mode for authentication.
49 // https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/AES_CMAC.pdf
50 int aes_cmac(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length) {
51 memset(mac, 0x00, 16);
52 uint8_t iiv[16] = {0};
53 if (iv)
54 memcpy(iiv, iv, 16);
55
56 // padding: ISO/IEC 9797-1 Message Authentication Codes (MACs) - Part 1: Mechanisms using a block cipher
57 uint8_t data[2049] = {0}; // length + 16
58 memcpy(data, input, length);
59 data[length] = 0x80;
60 int datalen = (length & 0xfffffff0) + 0x10;
61
62 // NIST 800-38B
63 aes_cmac128_context ctx;
64 aes_cmac128_starts(&ctx, key);
65 aes_cmac128_update(&ctx, data, datalen);
66 aes_cmac128_final(&ctx, mac);
67
68 return 0;
69 }
70
71 int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length) {
72 uint8_t cmac[16] = {0};
73 memset(mac, 0x00, 8);
74
75 int res = aes_cmac(iv, key, input, cmac, length);
76 if (res)
77 return res;
78
79 for(int i = 0; i < 8; i++)
80 mac[i] = cmac[i * 2 + 1];
81
82 return 0;
83 }
Impressum, Datenschutz