Crypto++加密解密—AES(ECB模式)+MAC认证

[复制链接]
查看1018 | 回复0 | 2012-4-1 19:25:54 | 显示全部楼层 |阅读模式
AES是一种对称密钥加密算法,ECB(Electronic Code Book)是一种加密模式。若对一文本加密,只有算法是不够的,还要选择模式。常用的模式有ECB,CFB,CBC,OFB。除了ECB外后三者都需要初始向量IV(initialization Vector)。(此段为加解密扫盲语,若看不懂需要做点功课了!)。
而MAC认证本身并不对消息加密,只是为了防止消息被非法篡改。本文代码先对消息做个认证然后采用AES加密,最后再还原消息。(初学者之作,大牛绕行)
StdAfx.h 头文件代码若下
#if !defined(AFX_STDAFX_H__3BD17221_972E_411D_871C_4AB7F4CD6B64__INCLUDED_)
#define AFX_STDAFX_H__3BD17221_972E_411D_871C_4AB7F4CD6B64__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <iostream>
using namespace std;
// Crypto++ Library
#ifdef _DEBUG
#  pragma comment( lib, "cryptlibd" )
#else
#  pragma comment( lib, "cryptlib" )
#endif
Crypto__test.cpp
源码如下:
#include "stdafx.h"
// Runtime Includes
#include <iostream>
#include <string>
// Crypto++ Includes
#include "default.h"
#include "filters.h" // StringSource and
                     // StreamTran单机传奇ormation
#include "osrng.h"
#include "hex.h"
using namespace std;
using namespace CryptoPP;
//先对消息(message)做MAC认证(messageMACed),然后采用AES—ECB加密模式对认证后的消息加密(CipherText)。对加密的消息(CipherText)解密为带MAC的消息(recoverMACed)然后去掉MAC即可得到原来的消息(recovered)。
int main(int argc, char* argv[])
{
    string message = "I am Houjialin";   
    byte password[] ={ 0x01, 0x02, 0x03, 0x04, 0x05, 0x6, 0x7};//认证使用的密码(密钥)
    string messageMACed,CipherText,recoverMACed,recovered;
//MAC消息认证
    StringSource(message,true, new DefaultEncryptorWithMAC( password, sizeof(password), new StringSink(messageMACed)));
//AES—ECB加密
    byte key[ AES::DEFAULT_KEYLENGTH ];//创建密钥
    ::memset( key, 0x01, AES::DEFAULT_KEYLENGTH );//初始化密钥(1填充)
    ECB_Mode< AES >::Encryption  Encryptor( key, sizeof(key));
//ECB属于不带初始向量的分块模式,将原文分块时若不够整块则需要填充,此处的DEFAULT_PADDING即为使用默认数据填充。(若需详细资料可查阅相关Crypto++帮助文档)
    StringSource( messageMACed, true,new StreamTran单机传奇ormationFilter( Encryptor,new StringSink( CipherText ),BlockPaddingSchemeDef::BlockPaddingScheme::DEFAULT_PADDING,true));
//AES—ECB解密
    ECB_Mode< AES >::Decryption Decryptor( key, sizeof(key) );
    StringSource( CipherText, true,new StreamTran单机传奇ormationFilter( Decryptor,new StringSink( recoverMACed ),BlockPaddingSchemeDef::BlockPaddingScheme::DEFAULT_PADDING,true));
//去掉MAC
    StringSource(recoverMACed,true,new DefaultDecryptorWithMAC(password,sizeof(password),new StringSink( recovered )));
cout<<"原始消息:  "<<message<<"\n"<<endl;
    cout<<"认证后的消息:"<<messageMACed<<"\n"<<endl;
    cout<<"加密后的消息:"<<CipherText<<"\n"<<endl;
    cout<<"解密后带MAC的消息:"<<recoverMACed<<"\n"<<endl;
    cout << "去掉MAC后的消息:" << recovered << endl;
    return 0;
}
发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则