pi_aes.c
2.52 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
113
114
115
116
117
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "rijndael-api-ref.h"
#define BLOCK_SIZE 128
#define FILE_SIZE 512
/* aes lengths in bits as used by pi */
#define PI_AES_KEYLEN 128
#define PI_AES_BLOCKLEN 128
/* compatibility bridge between defn's for rijndael code and bb */
#define u8 BYTE
#define u32 unsigned long
/*
returns >=0 on success, -1 on error
*/
int aesKeyExpand(u8 *key,u8 *expkey)
{
keyInstance keyI;
int x,y,z,i,j;
if(makeKeyEqvtInv(&keyI,
DIR_DECRYPT ,
PI_AES_KEYLEN,
PI_AES_BLOCKLEN,
key)
!= TRUE){
return -1;
}
/* scan for creating expanded key in form used by pi */
i=0;
j=10*16;
for (x=0; x < 11; x++){
for(y=0; y < 4; y++){
for(z=0; z < 4; z++){
expkey[j+(i++)]=keyI.keySched[x][z][y];
if(i==16){
j-=16;
i=0;
}
}
}
}
return 0;
}
int aesEncrypt(u8 *key,u8 *initVector,u8 *dataIn,u32 bytes,u8 *dataOut)
{
keyInstance keyI;
cipherInstance cipher;
int error;
/* make key */
if(makeKey(&keyI,
DIR_ENCRYPT,
PI_AES_KEYLEN,
PI_AES_BLOCKLEN,
key)
!= TRUE){
return -1;
}
/* initialise parameters */
error = cipherInit(&cipher, MODE_CBC, initVector, PI_AES_BLOCKLEN);
if (error != TRUE) {
fprintf(stderr,"cipherInit error %d \n", error);
return -1;
}
/*encrypt */
if(blockEncrypt(&cipher, &keyI, dataIn, bytes*8, dataOut)
!= bytes*8){
fprintf(stderr, "cipher encryption error \n");
return -1;
}
return 0;
}
int aesDecrypt(u8 *key,u8 *initVector,u8 *dataIn,u32 bytes,u8 *dataOut)
{
keyInstance keyI;
cipherInstance cipher;
int error;
/* make key */
if(makeKeyEqvtInv(&keyI,
DIR_DECRYPT,
PI_AES_KEYLEN,
PI_AES_BLOCKLEN,
key)
!= TRUE){
return -1;
}
/* initialise parameters */
error = cipherInit(&cipher, MODE_CBC, initVector, PI_AES_BLOCKLEN);
if (error != TRUE) {
fprintf(stderr,"cipherInit error %d \n", error);
return -1;
}
/*encrypt */
if(blockDecryptEqvtInv(&cipher, &keyI, dataIn, bytes*8, dataOut)
!= bytes*8){
fprintf(stderr, "cipher encryption error \n");
return -1;
}
return 0;
}