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 ...
随机推荐
- rertful规范
RESTful API的理解 断言 assert 条件(True)执行下面代码 assert 条件(False) 报错 什么是接口? 1- URL,用于进行系统之间操作数据. 2- 面向对象接口,用于 ...
- MAC使用homeBrew安装Redis
homeBrew的操作命令如下: brew search ** //查找某个软件包 brew list //列出已经安装的软件的包 brew install ** //安装某个软件包,默认安装的是稳定 ...
- Laravel5.5配置使用redis
1.安装redis linux上redis的安装与配置 2.安装redis客户端 composer require predis/predis或者安装 PhpRedis PHP 扩展brew inst ...
- javaScript Promise 入门
Promise是JavaScript的异步编程模式,为繁重的异步回调带来了福音. 一直以来,JavaScript处理异步都是以callback的方式,假设需要进行一个异步队列,执行起来如下: anim ...
- CSS选择符——分门别类
CSS选择符--分门别类 有时候,老是会对一些CSS选择器模模糊糊,傻傻分不清.今天花了点时间整理了一下,感觉世界清静了不少. 用XMIND做出了思维导图: 主要有11中选择器:元素.类ID.后代.子 ...
- notepad++ remove duplicate line
To remove duplicate lines just press Ctrl + F, select the “Replace” tab and in the “Find” field, pla ...
- POJ 1466 Girls and Boys(二分图匹配)
[题目链接] http://poj.org/problem?id=1466 [题目大意] 给出一些人和他们所喜欢的人,两个人相互喜欢就能配成一对, 问最后没有配对的人的最少数量 [题解] 求最少数量, ...
- 【树状数组】bzoj2789 [Poi2012]Letters
处理数组A,A[i]表示字符串a的第i个字符排序后应去的位置,队列可. 对于多次出现的字符,其在a中的顺序和在b中的顺序应该是一一对应的. #include<cstdio> #includ ...
- jvm-监视管理控制台-jconsole
命令: jconsole 作用: jvm进程运行状态的实时.可视化工具 效果: 连接远程jvm进程: 1.首先远程jvm进程,开启了jmx服务: -Dcom.sun.management.jmxrem ...
- Services
*在实际运行中同样的Service的确只能有一个. Services有两种启动形式: Started:其他组件调用startService()方法启动一个Service.一旦启动,Service将一直 ...