C++ 和 java 使用 AES CBC 128 加解密
Java 使用jce, code:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays; //import org.apache.commons.codec.binary.Base64; public class Encryptor { /**
* 字符串转换成十六进制字符串
*/
public static String str2HexStr(String str) { char[] chars = "0123456789ABCDEF".toCharArray();
StringBuilder sb = new StringBuilder("");
byte[] bs = str.getBytes();
int bit;
for (int i = 0; i < bs.length; i++) {
bit = (bs[i] & 0x0f0) >> 4;
sb.append(chars[bit]);
bit = bs[i] & 0x0f;
sb.append(chars[bit]);
}
return sb.toString();
} /**
*
* 十六进制转换字符串
*/ public static byte[] hexStr2Bytes(String hexStr) {
System.out.println("in len :" + hexStr.length());
String str = "0123456789ABCDEF";
char[] hexs = hexStr.toCharArray();
byte[] bytes = new byte[hexStr.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = str.indexOf(hexs[2 * i]) * 16;
n += str.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
System.out.println("out len :" + bytes.length);
System.out.println("ddd" + Arrays.toString(bytes));
return bytes;
} /**
* bytes转换成十六进制字符串
*/
public static String byte2HexStr(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
// if (n<b.length-1) hs=hs+":";
}
return hs.toUpperCase();
} public static String encrypt(String key, String initVector, String value) {
try {
System.out.println("key:\t" + Arrays.toString(key.getBytes("UTF-8")));
System.out.println("iv:\t" + Arrays.toString(initVector.getBytes("UTF-8")));
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
//Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(value.getBytes());
System.out.println(Arrays.toString(encrypted));
//System.out.println("encrypted string: "
// + Base64.encodeBase64String(encrypted)); return byte2HexStr(encrypted);
//return Base64.encodeBase64String(encrypted);
} catch (Exception ex) {
ex.printStackTrace();
} return null;
} public static String decrypt(String key, String initVector, String encrypted) {
try {
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); //byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
byte[] original = cipher.doFinal(hexStr2Bytes(encrypted)); return new String(original);
} catch (Exception ex) {
ex.printStackTrace();
} return null;
} public static void main(String[] args) {
String key = "1234567890123456"; // 128 bit key
String initVector = "0000000000000000"; // 16 bytes IV String en = encrypt(key, initVector, "hello world, cryptopp");
System.out.println(en);
System.out.println(decrypt(key, initVector, en));
}
}
编译运行输出
➜ cypherTest javac Encryptor.java
➜ cypherTest java Encryptor
key: [, , , , , , , , , , , , , , , ]
iv: [, , , , , , , , , , , , , , , ]
[, -, -, -, , -, , , -, -, -, -, -, -, -, -, -, -, -, -, -, , -, , -, , , , -, , -, -]
02D2CD9C25CF0B48E386F1CFD4D8EFBBF2BB90EC8462F86CA8211713BE03D0C5
in len :
out len :
ddd[, -, -, -, , -, , , -, -, -, -, -, -, -, -, -, -, -, -, -, , -, , -, , , , -, , -, -]
hello world, cryptopp
C++ 使用cryptopp库(https://www.cryptopp.com/ 下载后,make&& make install 编译安装)
#ifndef CRYPTOPP_H
#define CRYPTOPP_H #include <iostream>
#include <fstream>
#include <sstream> #include <cryptopp/aes.h>
#include <cryptopp/filters.h>
#include <cryptopp/modes.h> class cryptopp {
public:
static bool init(const std::string& key, const std::string& iv);
static std::string encrypt(const std::string& inputPlainText);
static std::string decrypt(const std::string& cipherTextHex);
private:
static byte s_key[CryptoPP::AES::DEFAULT_KEYLENGTH];
static byte s_iv[CryptoPP::AES::DEFAULT_KEYLENGTH];
};
#endif
#include "cryptopp.h" using namespace std; void print(const string& cipherText) {
cout << "[";
for( unsigned int i = ; i < cipherText.size(); i++ )
{
cout << int(cipherText[i]) << ", " ;
}
cout << "]"<< endl;
} byte cryptopp::s_key[CryptoPP::AES::DEFAULT_KEYLENGTH];
byte cryptopp::s_iv[CryptoPP::AES::DEFAULT_KEYLENGTH]; bool cryptopp::init(const string& key, const string& iv) {
if (key.size() != CryptoPP::AES::DEFAULT_KEYLENGTH) {
return false;
}
if (iv.size() != CryptoPP::AES::BLOCKSIZE) {
return false;
} for(int i = ; i < CryptoPP::AES::DEFAULT_KEYLENGTH; i++) {
s_key[i] = key[i];
}
for(int i = ; i < CryptoPP::AES::BLOCKSIZE; i++) {
s_iv[i] = iv[i];
}
//memset(s_key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH);
//memset(s_iv, 0x00, CryptoPP::AES::BLOCKSIZE);
return true;
} string cryptopp::encrypt(const string& plainText)
{
/*
if ((plainText.length() % CryptoPP::AES::BLOCKSIZE) != 0) {
return "";
}
*/ string cipherTextHex;
try {
string cipherText;
CryptoPP::AES::Encryption aesEncryption(s_key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, s_iv);
//CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( cipherText ), CryptoPP::StreamTransformationFilter::NO_PADDING);
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( cipherText ));
stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plainText.c_str() ), plainText.length() );
stfEncryptor.MessageEnd(); print(cipherText);
for( unsigned int i = ; i < cipherText.size(); i++ )
{
char ch[] = {};
sprintf(ch, "%02x", static_cast<byte>(cipherText[i]));
cipherTextHex += ch;
}
} catch (const std::exception &e) {
cipherTextHex = "";
} return cipherTextHex;
} string cryptopp::decrypt(const string& cipherTextHex)
{
/*
if(cipherTextHex.empty()) {
return string();
}
if ((cipherTextHex.length() % CryptoPP::AES::BLOCKSIZE) != 0) {
return string();
}
*/ string cipherText;
string decryptedText; unsigned int i = ;
while(true)
{
char c;
int x;
stringstream ss;
ss<<hex<<cipherTextHex.substr(i, ).c_str();
ss>>x;
c = (char)x;
cipherText += c;
if(i >= cipherTextHex.length() - )break;
i += ;
} try {
CryptoPP::AES::Decryption aesDecryption(s_key, CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, s_iv );
//CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedText ),CryptoPP::StreamTransformationFilter::NO_PADDING);
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedText ));
stfDecryptor.Put( reinterpret_cast<const unsigned char*>( cipherText.c_str() ), cipherText.size()); stfDecryptor.MessageEnd();
} catch (const std::exception &e) {
decryptedText = "";
} return decryptedText;
} int main() {
cryptopp::init("", "");
string en = cryptopp::encrypt("hello world, cryptopp");
cout << en << endl;
cout << cryptopp::decrypt(en) << endl;
}
编译 g++ cryptopp.cpp -lcryptopp
运行输出
$./a.out
[, -, -, -, , -, , , -, -, -, -, -, -, -, -, -, -, -, -, -, , -, , -, , , , -, , -, -, ]
02d2cd9c25cf0b48e386f1cfd4d8efbbf2bb90ec8462f86ca8211713be03d0c5
hello world, cryptopp
C++ 和 java 使用 AES CBC 128 加解密的更多相关文章
- Java 使用AES/CBC/PKCS7Padding 加解密字符串
介于java 不支持PKCS7Padding,只支持PKCS5Padding 但是PKCS7Padding 和 PKCS5Padding 没有什么区别要实现在java端用PKCS7Padding填充, ...
- JAVA AES CBC PKCS5Padding加解密
package com.hzxc.groupactivity.util; /** * Created by hdwang on 2019/1/17. */ import org.slf4j.Logge ...
- AES CBC/CTR 加解密原理
So, lets look at how CBC works first. The following picture shows the encryption when using CBC (in ...
- 使用java实现AES算法的加解密(亲测可用)
话不多说,直接上代码 import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.cryp ...
- openssl:AES CBC PKCS5 加解密 (C/GOLANG)
#include <openssl/aes.h> /* AES_CBC_PKCS5_Encrypt * 入参: * src:明文 * srcLen:明文长度 * key:密钥 长度只能是1 ...
- python 实现 AES CBC模式加解密
AES加密方式有五种:ECB, CBC, CTR, CFB, OFB 从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现 python 在 Windows下使用AE ...
- 手机号的 AES/CBC/PKCS7Padding 加解密
前言:接口中上次的手机号码和密码是传入的加密的,模拟自动化的时候也需要先对数据进行加密 1.各种语言实现 网上已经各种语言实现好的AES加密,可以点击查看:http://outofmemory.cn/ ...
- python 实现 AES ECB模式加解密
AES ECB模式加解密使用cryptopp完成AES的ECB模式进行加解密. AES加密数据块分组长度必须为128比特,密钥长度可以是128比特.192比特.256比特中的任意一个.(8比特 == ...
- JAVA实现AES的加密和解密算法
原文 JAVA实现AES的加密和解密算法 import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import ja ...
随机推荐
- 使用 gulp 编译 Sass
无论是 node-sass 还是 ruby-sass 使用 npm 安装都非常的慢,甚至会装不上.及其不利于团队协作.建议使用 less 作为 css 预处理器. 如果因为 less 不支持自定义函数 ...
- Tomcat 服务器基本知识
Tomcat下载安装和配置 下载 下载地址: http://tomcat.apache.org tomcat服务器分为很多版本, 其中包括windows版和linux版 ...
- 湖南师范大学2018年大学生程序设计竞赛新生赛 A 齐神和心美的游戏【hash】
[链接]:A [题意]:给你n个数的序列和k.判断是否可以三个数组成k(同一个数可以拿多次) [分析]:每个数vis记录一下.2层循环.两数之和不超过k以及剩下的数出现在序列中那么ok. [代码]: ...
- swagger (九)
创建创建microservicecloud-swagger pom文件 eureka: client: #客户端注册进eureka服务列表内 service-url: defaultZone: htt ...
- Placement new的用法及用途【转】
什么是placement new? 所谓placement new就是在用户指定的内存位置上构建新的对象,这个构建过程不需要额外分配内存,只需要调用对象的构造函数即可.举例来说: class foo{ ...
- HDU 6017 Girls Love 233(多态继承DP)
[题目链接] http://acm.hdu.edu.cn/showproblem.php?pid=6017 [题目大意] 给出一个只包含2和3的串,你可以花费两个智力值交换相邻的两个字符 问在智力值不 ...
- 【线性基】【贪心】【独立环】bzoj2115 [Wc2011] Xor
网上到处都是题解,自己画个图也很好理解.虽然环的个数很多,但是都可以通过独立环之间异或出来,不用管. 独立环求法:生成树之后,每次向图里添加非树边(u,v),则这个独立环的异或和为sum[u]^sum ...
- 【分块答案】【最小割】bzoj1532 [POI2005]Kos-Dicing
引用zky的题解:http://blog.csdn.net/iamzky/article/details/39667859 每条S-T路径代表一次比赛的结果.最小割会尽量让一个人赢得最多. 因为二分总 ...
- Linux下的echo输出换行符
echo -e "text1\ntext2" -e表示开启转移字符
- Swift,类的调用
1.class或者struct如果没有实例没办法直接调用 (1)设置class后可直接调用 class S{ static var width:Int{ //static代表公有的,都可使用 retu ...