aes.c
2.5 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdlib.h>
#include <string.h>
#include "aes.h"
#include <PR/bbtypes.h>
#include "aes_api.h"
#define BLOCK_SIZE 128
#define FILE_SIZE 512
/* aes lengths in bits as used by pi */
#define PI_AES_KEYLEN (sizeof(BbAesKey)*8)
#define PI_AES_BLOCKLEN (sizeof(BbAesKey)*8)
/*
returns >=0 on success, -1 on error
***********************************
use this only for HW
for software encryption and decryption, the
key expansion is included
if key is in ascii isAscii = 1, else 0
***********************************
*/
int aes_HwKeyExpand(u8 *key,u8 *expkey)
{
AesKeyInstance keyI;
if(aesMakeKey(&keyI, AES_DIR_DECRYPT, PI_AES_KEYLEN, key) != TRUE){
return -1;
}
/* scan for creating expanded key in form used by pi */
memcpy(expkey, keyI.rk, 44*4);
return 0;
}
/*************************************
* Use this only for software (Key expansion included)
* isAscii = 1 means initVector and key are in ascii
*************************************
*/
int aes_SwEncrypt(u8 *key,u8 *initVector,u8 *dataIn,u32 bytes,u8 *dataOut)
{
AesKeyInstance keyI;
AesCipherInstance cipher;
int error;
/* make key */
if(aesMakeKey(&keyI, AES_DIR_ENCRYPT, PI_AES_KEYLEN, key) != TRUE){
return -1;
}
/* initialise parameters */
error = aesCipherInit(&cipher, AES_MODE_CBC, initVector);
if (error != TRUE) {
/*
fprintf(stderr,"cipherInit error %d \n", error);
*/
return -1;
}
/*encrypt */
if(aesBlockEncrypt(&cipher, &keyI, dataIn, bytes*8, dataOut)
!= bytes*8){
/*
fprintf(stderr, "cipher encryption error \n");
*/
return -1;
}
return 0;
}
/*************************************
* Use this only for software (Key expansion included)
* isAscii = 1 means key and IV are in ascii
*************************************
*/
int aes_SwDecrypt(u8 *key,u8 *initVector,u8 *dataIn,u32 bytes,u8 *dataOut)
{
AesKeyInstance keyI;
AesCipherInstance cipher;
int error;
/* make key */
if(aesMakeKey(&keyI, AES_DIR_DECRYPT, PI_AES_KEYLEN, key) != TRUE){
return -1;
}
/* initialise parameters */
error = aesCipherInit(&cipher, AES_MODE_CBC, initVector);
if (error != TRUE) {
/*
fprintf(stderr,"cipherInit error %d \n", error);
*/
return -1;
}
/*encrypt */
if(aesBlockDecrypt(&cipher, &keyI, dataIn, bytes*8, dataOut) != bytes*8){
/*
fprintf(stderr, "cipher encryption error \n");
*/
return -1;
}
return 0;
}