欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Crypto++ AES 加密解密流程

程序员文章站 2022-04-28 21:35:05
#include #include #include ......
// aesdemo.cpp : 定义控制台应用程序的入口点。
//

#include <stdio.h>
#include <tchar.h>
#include <iostream>

#include "aes.h"

using namespace std;
using namespace cryptopp;


int main()
{
    cout << "aes demo "<< aes::staticalgorithmname() << endl;
    unsigned char aeskey[aes::default_keylength] = "aes"; //密钥

    aesencryption aesencryptor; //加密器     
    aesencryptor.setkey(aeskey, aes::default_keylength); //设定加密密钥

    char* srcdata = "123456789abcdefghi987654321";

    cout << "will be encode:" << srcdata << endl;

    unsigned char xorblock[aes::blocksize]; //必须设定为全零
    memset(xorblock, 0, aes::blocksize); //置零
    unsigned char inblock[aes::blocksize]; //要加密的数据块
    unsigned char outblock[aes::blocksize]; //加密后的密文块

    aesdecryption aesdecryptor;
    aesdecryptor.setkey(aeskey, aes::default_keylength);
    unsigned char plaintext[aes::blocksize];

    int srclen = strlen(srcdata);
    char* dstdata = (char*)calloc(srclen, sizeof(char));
    int pos = 0;
    do 
    {
        int relaysize = srclen - pos; 
        int cpsize = relaysize > aes::blocksize ? aes::blocksize : relaysize;
        memset(inblock, 0, aes::blocksize);
        memset(outblock, 0, aes::blocksize);
        memset(plaintext, 0, aes::blocksize);
        memcpy(inblock, srcdata + pos, cpsize);
        aesencryptor.processandxorblock(inblock, xorblock, outblock); //加密
        aesdecryptor.processandxorblock(outblock, xorblock, plaintext);
        memcpy(dstdata + pos, plaintext, cpsize);
        pos += cpsize;

    } while (pos < srclen-1);
    cout << "after encode and decode :" << dstdata << endl;
    free(dstdata);
    getchar();
    return 0;
}