pi_aes.c 2.52 KB
#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;
}