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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值