服务器端使用的是nodejs编写的代码,对明文进行加密,客户端使用的是QT4.5.3编写代码,调用openssl crypto库函数,对密文进行解密。
注意:加解密要对等,即加解密的秘钥相同,向量也要相同,由于是两种不同的语言写的代码,因此两边都要做好一致性检查,比如秘钥的处理,密文的编码方式等等。
这里两边都对秘钥进行了MD5加密,并设置向量和秘钥一样(可自由设置秘钥和向量,我们的代码中处理成一样的比较便捷),密文采用base64编码,因此在QT那边一定要用fromBase64()来获取密文,否则会出错。
以下是nodejs加密端的代码:
function encChangeFuzzy(data) {
var key = "test";
var secretKey = new Buffer(key, "utf8");
secretKey = crypto.createHash("md5").update(secretKey).digest("hex");
secretKey = new Buffer(secretKey, "hex");
iv = secretKey;//设置向量和秘钥相同
var cipher = crypto.createCipheriv("aes-128-cbc", secretKey, iv), coder = [];
coder.push(cipher.update(data, "utf8", "base64"));
coder.push(cipher.final("base64"));
return coder.join("");
}
以下是QT端解密的代码:
#include<QObject>
#include <QtCore>
#include <openssl/aes.h>
int aes_decrypt(unsigned char *in, unsigned char *key, unsigned char* ivec, unsigned char *out)
{
if(!in || !key || !out) return 0;
AES_KEY aes;
if(AES_set_decrypt_key(key, 128, &aes) < 0)//设置解密秘钥
{
return 0;
}
int dateSize = strlen( (char*)in );
AES_cbc_encrypt(in, out, dateSize, &aes, ivec, AES_DECRYPT);//解密
/**pack5padding,获取最后一位数,以该数为个数,将out指向区域的最后位数用0替代**/
int out_len = strlen((char*)out);
int last_value = (unsigned char)out[out_len-1];
memset(out+out_len-last_value, 0, last_value);
return 1;
}
QString deCode( QString key,QString ivec, QString code)
{
int MSG_LEN = code.size();
//对秘钥进行MD5加密
QByteArray byteArray;
byteArray = key.toLatin1();
QByteArray hash = QCryptographicHash::hash(byteArray, QCryptographicHash::Md5);
//QByteArray strMD5 = hash.toHex();
//qDebug()<<"strMD5"<<strMD5.constData()<<" hash"<<hash;
//将加密后的秘钥转为unsigned char*类型
unsigned char keyArray[AES_BLOCK_SIZE];
memset((unsigned char*)keyArray, 0x00 ,AES_BLOCK_SIZE);
strcpy( (char*)keyArray, hash.constData() );
//对向量进行MD5加密
// QByteArray byteArrayIv;
// byteArrayIv = ivec.toLatin1();
// QByteArray hashIv = QCryptographicHash::hash(byteArrayIv, QCryptographicHash::Md5);
// //加密后的向量转为unsigned char*类型
// unsigned char ivArray[AES_BLOCK_SIZE];