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 ...
随机推荐
- thinkphp5最美跳转页面
声明下:此教程来自TP官网,如果需要看原文,请点击一下链接 http://www.thinkphp.cn/code/3437.html 先给大家看下效果: 直接撸代码: 第一步:为了增加对移动设备 ...
- Centos7源码编译安装tengine1.5.1
安装依赖包 yum install pcre pcre-devel openssl openssl-devel gcc make zlib-devel wget -y 下载和创建用户 mkdir /t ...
- (二)mysql忘记root密码
(1)mysql 5.7.6以前版本 修改配置文件vim /etc/my.cnf [mysqld] skip-grant-tables 重启mysql systemctl restart mysqld ...
- [thinkphp] 公共头部底部如何传递数据
分组底下有一个公共模板文件夹 Modules/Index/Tpl/public/ 如何传递数据给模板呢? 在 入口文件/Lib/Action/ 中创建类CommonAction.class.php ...
- HDU 2551 竹青遍野(循环,水)
/* 他开始在他的院子种竹子,第1个月种1根竹子,第2个月种8根竹子,第3个月种27根竹子 ...第N个月就种(N^3)根竹子.当他种下第X根竹子那一刻,就是他重出江湖之时! 告诉你X的值, 你能算出 ...
- 分享Kali Linux 2017年第29周镜像文件
分享Kali Linux 2017年第29周镜像文件 Kali Linux官方于7月16日发布2017年的第29周镜像.这次维持了11个镜像文件的规模.默认的Gnome桌面的4个镜像,E17.KDE ...
- [BZOJ 4144] Petrol
Link: BZOJ 4144 传送门 Solution: 一道不错的图论综合题 因为只询问关键点,因此重点是要求出关键点之间的最短路,以最短路建图 记$nst[i]$为离$i$最近的关键点:可以发现 ...
- 【矩阵哈希】【二分答案】【哈希表】bzoj1567 [JSOI2008]Blue Mary的战役地图
引用题解:http://hzwer.com/5153.html 当然,二分可以换成哈希表. #include<cstdio> #include<iostream> #inclu ...
- Oracle常见故障问题
1. ORA-27102: out of memory 创建pfile文件: create pfile from spfile: 修改pfile文件 修改文件/home/oracle/app/orac ...
- &#x开头的是什么编码?
在 Node 层利用 cheerio 解析网页时,输出的中文内容都是以 &#x 开头的一堆像乱码一样的东西,尝试过各种编码都无效,而且神奇的是,将这一堆“乱码”保存成网页后,通过浏览器打开又可 ...