之前文章c++实现AES加密解密算法介绍了c++实现加解密,本文介绍:用Java代码生成AES加密字符串,在c++代码里面解密字符串
一、Java代码
加密:
public static String encrypt(String content) {
try {
if (content.isEmpty())
return "";
String password = "t7CLWhtUTAgAFbw0";
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
String str = Base64.encodeBase64String(result);
return str; // 加密
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
} catch (NoSuchPaddingException e) {
// e.printStackTrace();
} catch (InvalidKeyException e) {
// e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// e.printStackTrace();
} catch (BadPaddingException e) {
// e.printStackTrace();
}
return null;
}
解密:
public static String decrypt(String str) {
try {
String password = "t7CLWhtUTAgAFbw0";
byte[] content = Base64.decodeBase64(str);
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(content);
return new String(result);
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
} catch (NoSuchPaddingException e) {
// e.printStackTrace();
} catch (InvalidKeyException e) {
// e.printStackTrace();
} catch (IllegalBlockSizeException e) {
// e.printStackTrace();
} catch (BadPaddingException e) {
// e.printStackTrace();
} catch (Exception e) {
// e.printStackTrace();
}
return "";
}
二、Java测试代码
String enStr = encrypt("hello world");
System.out.println("enStr: " + enStr);
System.out.println("deStr: " + decrypt(enStr));
测试结果:
三、c++测试代码
使用CAesLib.lib,代码如下:
// TestAesLib.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include "encrypt_decrypt.h"
using namespace std;
#pragma comment(lib, "CAesLib.lib")
int _tmain(int argc, _TCHAR* argv[])
{
CAes256::initAes("t7CLWhtUTAgAFbw0");
// "hello world"
string enstr = "IlphHBX6JENV1iW09ZW2Tg=="; // 原文:hello world,加密字符串来自java代码加密
string str = CAes256::decryptData("IlphHBX6JENV1iW09ZW2Tg=="); // c++解密
cout << "str = " << str << endl;
cout << "enstr = " << CAes256::encryptData(str) << endl; // c++加密,对比结果与java代码加密的是否一样
system("pause");
return 0;
}
运行结果: