📄 decrypt.cpp
字号:
#include "StdAfx.h"
#include ".\decrypt.h"
/**
* 公共构造器
* 参数:
* key 密钥,从证书获得
* IV 初始化向量,从证书获得
* keyLen AES密钥长度,标准位128,192,256
*/
Decrypt::Decrypt(unsigned char *key, unsigned char *IV,int keyLen=128)
{
this->key = new unsigned char[keyLen];
memcpy(this->key,key,keyLen);
//this->key = key;
this->IV = new unsigned char[IV_LEN];
memcpy(this->IV,IV,IV_LEN);
//this->IV = IV;
aes_set_key( &aesCtx, this->key, keyLen);
}
/**
* 对缓冲区进行解密
* 参数:
* debuf 源缓冲区
* rebuf 目标缓冲区,存放加密后的数据
* len 源缓冲区长度
* 返回:加密后缓冲区有效长度
*/
int Decrypt::DecryptBuffer(unsigned char *debuf,unsigned char *rebuf, int len)
{
//if( (len & 0x0F ) != 0 ) throw new ::exception("buffer size not a multiple of 16!");
if((len&0x0F)!=0)
{
cout<<"buffer size not a multiple of 16!"<<endl;
return -1;
}
unsigned char tmp[16];
unsigned char buff[16];
unsigned char *tp = rebuf;
unsigned char *buffer = debuf;
int offset,n,i,count=0;
memcpy(tmpIV, IV, IV_LEN); //备份IV
//printf("l=%d %d\n",l,buffer[len-1]);
for( offset = 0; offset < len; offset += 16,buffer+=16)
{
memcpy( buff, buffer, 16 );
memcpy( tmp, buff, 16);
aes_decrypt(&aesCtx, buff, buff );
for( i = 0; i < 16; i++ )
buff[i] ^= tmpIV[i];
memcpy( tmpIV, tmp, 16 );
//if(offset==0) printf("%s\n",buff);
n = (offset == len - 16 ) ? 16-buff[15] : 16;
if(n>16||n<0)
{
cout<<"填充无效!"<<endl;
return -1;
}
memcpy( tp, buff, n);
tp+=n;
//count+=n;
//printf("%d %d %d\n",n,len,buff[15]);
}
//printf("%d %d %d\n",n,len,buff[15]);
count=(int)(tp-rebuf);
//rebuf=tp;
//memcpy(rebuf,debuf,count);
//delete(debuf);
return count;
}
/**
* 静态方法,给定文件指针的位置,取得按照AES分段加密协定,解密文件时文件指针应该设置的位置
* 参数:
* sectionLength 段长
* treamPosition 文件指针位置
* headerLen 文件头长度
* 返回:解密文件时文件指针应该设置的位置(返回-1表示当前文件指针还在文件头,不能完成设置)
*/
unsigned long Decrypt::getProperPosition (int sectionLength,unsigned long streamPosition,int headerLen)
{
long xposi = streamPosition-headerLen;
if(xposi<0) return -1;
return (xposi%sectionLength==0) ? streamPosition : (streamPosition-xposi%sectionLength);
}
/**
* 根据段长和文件指针偏移计算块位置(块号)的静态方法,规定块号从0开始
* 参数:
* sectionLength 段长
* treamPosition 文件指针位置
* headerLen 文件头长度
* 返回:块号
*/
int Decrypt::getBlock(int sectionLength, unsigned long streamPosition, int headerLen)
{
return (int)((streamPosition-headerLen)%sectionLength)/16;
}
/**
* 根据段长和文件指针偏移计算段位置(段号)的静态方法,规定块号从0开始
* 参数:
* sectionLength 段长
* treamPosition 文件指针位置
* headerLen 文件头长度
* 返回:段号
*/
int Decrypt::getSection(int sectionLength,unsigned long streamPosition,int headerLen)
{
return (int)((streamPosition-headerLen)/sectionLength);
}
Decrypt::~Decrypt(void)
{
delete[] key;
delete[] IV;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -