C Aes 算法

I am not sure if C source code of aes implement is OK for you.

Here is a link you can download an AES source

http://www.cis.syr.edu/~wedu/seed/Labs/IPSec/files/libcrypt.tar

The aes.c and aes.h in folder libcrypt are what we need. The aes_demo.c under demo folder gives us a demo how to use it.

Now, we have everything we need. I create a Win32 console application say “aes256” targeting WM6 pro, add aes.h to header files and aes.c to source files.

In aes256.cpp,

extern "C"

{

#include "aes.h"

}

#include <string.h>

#include <stdio.h>

#include <windows.h>

int _tmain(int argc, _TCHAR* argv[])

{

    int n, i;

    aes_context ctx;

     WCHAR *in = TEXT("abc" );

     WCHAR *out;

     WCHAR *secret_key = TEXT("aa" );

    unsigned char buf[16];

unsigned char key[32];

     memset(buf,0,16);

memset(key,0,32);

     memcpy( buf, in, 16);

       /* Set the key */

       memcpy( key, secret_key, 32);

       aes_set_key( &ctx, key, 256);

      /* Encrypt */

       aes_encrypt( &ctx, buf, buf );

      /* Decrypt */

        aes_decrypt( &ctx, buf, buf );

       out=(WCHAR*)buf;

        return 0;

}

In the code, I did an encryption and a decryption.

A little clarification, in the code I didn’t convert WCHAR* to unsigned char*, I just did a bit copy. I think it is up to you whether to do a real convert or not, the difference is the length of data to be encrypted.

AES’s key size can be 128 bits, 192 bits, or 256 bits. Since you specify AES 256, I hard code the key size. Therefore if user passed a long key it will be cut, if short key it will be pad.

The code above only supports 128bit of plaintext encryption which is a block cipher of AES algorithm. If your plaintext is more than that there are several ways(AES modes) to encrypt data, such as ECB (Electronic Code Book), CBC (Cipher Block Chaining), CFB (Cipher Feedback),

For detail please refer to

http://en.wikipedia.org/wiki/Cipher_Block_Chaining#Cipher-block_chaining_.28CBC.29

And there are more codes need to be done.

 

Hope this helps,

Zhe Zhao

原文地址:https://www.cnblogs.com/iapp/p/3631777.html