Java 使用jce, code:

  1. import javax.crypto.Cipher;
  2. import javax.crypto.spec.IvParameterSpec;
  3. import javax.crypto.spec.SecretKeySpec;
  4. import java.util.Arrays;
  5.  
  6. //import org.apache.commons.codec.binary.Base64;
  7.  
  8. public class Encryptor {
  9.  
  10. /**
  11. * 字符串转换成十六进制字符串
  12. */
  13. public static String str2HexStr(String str) {
  14.  
  15. char[] chars = "0123456789ABCDEF".toCharArray();
  16. StringBuilder sb = new StringBuilder("");
  17. byte[] bs = str.getBytes();
  18. int bit;
  19. for (int i = 0; i < bs.length; i++) {
  20. bit = (bs[i] & 0x0f0) >> 4;
  21. sb.append(chars[bit]);
  22. bit = bs[i] & 0x0f;
  23. sb.append(chars[bit]);
  24. }
  25. return sb.toString();
  26. }
  27.  
  28. /**
  29. *
  30. * 十六进制转换字符串
  31. */
  32.  
  33. public static byte[] hexStr2Bytes(String hexStr) {
  34. System.out.println("in len :" + hexStr.length());
  35. String str = "0123456789ABCDEF";
  36. char[] hexs = hexStr.toCharArray();
  37. byte[] bytes = new byte[hexStr.length() / 2];
  38. int n;
  39. for (int i = 0; i < bytes.length; i++) {
  40. n = str.indexOf(hexs[2 * i]) * 16;
  41. n += str.indexOf(hexs[2 * i + 1]);
  42. bytes[i] = (byte) (n & 0xff);
  43. }
  44. System.out.println("out len :" + bytes.length);
  45. System.out.println("ddd" + Arrays.toString(bytes));
  46. return bytes;
  47. }
  48.  
  49. /**
  50. * bytes转换成十六进制字符串
  51. */
  52. public static String byte2HexStr(byte[] b) {
  53. String hs = "";
  54. String stmp = "";
  55. for (int n = 0; n < b.length; n++) {
  56. stmp = (Integer.toHexString(b[n] & 0XFF));
  57. if (stmp.length() == 1)
  58. hs = hs + "0" + stmp;
  59. else
  60. hs = hs + stmp;
  61. // if (n<b.length-1) hs=hs+":";
  62. }
  63. return hs.toUpperCase();
  64. }
  65.  
  66. public static String encrypt(String key, String initVector, String value) {
  67. try {
  68. System.out.println("key:\t" + Arrays.toString(key.getBytes("UTF-8")));
  69. System.out.println("iv:\t" + Arrays.toString(initVector.getBytes("UTF-8")));
  70. IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
  71. SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
  72.  
  73. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
  74. //Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
  75. cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
  76.  
  77. byte[] encrypted = cipher.doFinal(value.getBytes());
  78. System.out.println(Arrays.toString(encrypted));
  79. //System.out.println("encrypted string: "
  80. // + Base64.encodeBase64String(encrypted));
  81.  
  82. return byte2HexStr(encrypted);
  83. //return Base64.encodeBase64String(encrypted);
  84. } catch (Exception ex) {
  85. ex.printStackTrace();
  86. }
  87.  
  88. return null;
  89. }
  90.  
  91. public static String decrypt(String key, String initVector, String encrypted) {
  92. try {
  93. IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
  94. SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
  95.  
  96. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
  97. cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
  98.  
  99. //byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
  100. byte[] original = cipher.doFinal(hexStr2Bytes(encrypted));
  101.  
  102. return new String(original);
  103. } catch (Exception ex) {
  104. ex.printStackTrace();
  105. }
  106.  
  107. return null;
  108. }
  109.  
  110. public static void main(String[] args) {
  111. String key = "1234567890123456"; // 128 bit key
  112. String initVector = "0000000000000000"; // 16 bytes IV
  113.  
  114. String en = encrypt(key, initVector, "hello world, cryptopp");
  115. System.out.println(en);
  116. System.out.println(decrypt(key, initVector, en));
  117. }
  118. }

编译运行输出

  1. cypherTest javac Encryptor.java
  2. cypherTest java Encryptor
  3. key: [, , , , , , , , , , , , , , , ]
  4. iv: [, , , , , , , , , , , , , , , ]
  5. [, -, -, -, , -, , , -, -, -, -, -, -, -, -, -, -, -, -, -, , -, , -, , , , -, , -, -]
  6. 02D2CD9C25CF0B48E386F1CFD4D8EFBBF2BB90EC8462F86CA8211713BE03D0C5
  7. in len :
  8. out len :
  9. ddd[, -, -, -, , -, , , -, -, -, -, -, -, -, -, -, -, -, -, -, , -, , -, , , , -, , -, -]
  10. hello world, cryptopp

C++ 使用cryptopp库(https://www.cryptopp.com/  下载后,make&& make install 编译安装)

  1. #ifndef CRYPTOPP_H
  2. #define CRYPTOPP_H
  3.  
  4. #include <iostream>
  5. #include <fstream>
  6. #include <sstream>
  7.  
  8. #include <cryptopp/aes.h>
  9. #include <cryptopp/filters.h>
  10. #include <cryptopp/modes.h>
  11.  
  12. class cryptopp {
  13. public:
  14. static bool init(const std::string& key, const std::string& iv);
  15. static std::string encrypt(const std::string& inputPlainText);
  16. static std::string decrypt(const std::string& cipherTextHex);
  17. private:
  18. static byte s_key[CryptoPP::AES::DEFAULT_KEYLENGTH];
  19. static byte s_iv[CryptoPP::AES::DEFAULT_KEYLENGTH];
  20. };
  21. #endif
  1. #include "cryptopp.h"
  2.  
  3. using namespace std;
  4.  
  5. void print(const string& cipherText) {
  6. cout << "[";
  7. for( unsigned int i = ; i < cipherText.size(); i++ )
  8. {
  9. cout << int(cipherText[i]) << ", " ;
  10. }
  11. cout << "]"<< endl;
  12. }
  13.  
  14. byte cryptopp::s_key[CryptoPP::AES::DEFAULT_KEYLENGTH];
  15. byte cryptopp::s_iv[CryptoPP::AES::DEFAULT_KEYLENGTH];
  16.  
  17. bool cryptopp::init(const string& key, const string& iv) {
  18. if (key.size() != CryptoPP::AES::DEFAULT_KEYLENGTH) {
  19. return false;
  20. }
  21. if (iv.size() != CryptoPP::AES::BLOCKSIZE) {
  22. return false;
  23. }
  24.  
  25. for(int i = ; i < CryptoPP::AES::DEFAULT_KEYLENGTH; i++) {
  26. s_key[i] = key[i];
  27. }
  28. for(int i = ; i < CryptoPP::AES::BLOCKSIZE; i++) {
  29. s_iv[i] = iv[i];
  30. }
  31. //memset(s_key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH);
  32. //memset(s_iv, 0x00, CryptoPP::AES::BLOCKSIZE);
  33. return true;
  34. }
  35.  
  36. string cryptopp::encrypt(const string& plainText)
  37. {
  38. /*
  39. if ((plainText.length() % CryptoPP::AES::BLOCKSIZE) != 0) {
  40. return "";
  41. }
  42. */
  43.  
  44. string cipherTextHex;
  45. try {
  46. string cipherText;
  47. CryptoPP::AES::Encryption aesEncryption(s_key, CryptoPP::AES::DEFAULT_KEYLENGTH);
  48. CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, s_iv);
  49. //CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( cipherText ), CryptoPP::StreamTransformationFilter::NO_PADDING);
  50. CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( cipherText ));
  51. stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plainText.c_str() ), plainText.length() );
  52. stfEncryptor.MessageEnd();
  53.  
  54. print(cipherText);
  55. for( unsigned int i = ; i < cipherText.size(); i++ )
  56. {
  57. char ch[] = {};
  58. sprintf(ch, "%02x", static_cast<byte>(cipherText[i]));
  59. cipherTextHex += ch;
  60. }
  61. } catch (const std::exception &e) {
  62. cipherTextHex = "";
  63. }
  64.  
  65. return cipherTextHex;
  66. }
  67.  
  68. string cryptopp::decrypt(const string& cipherTextHex)
  69. {
  70. /*
  71. if(cipherTextHex.empty()) {
  72. return string();
  73. }
  74. if ((cipherTextHex.length() % CryptoPP::AES::BLOCKSIZE) != 0) {
  75. return string();
  76. }
  77. */
  78.  
  79. string cipherText;
  80. string decryptedText;
  81.  
  82. unsigned int i = ;
  83. while(true)
  84. {
  85. char c;
  86. int x;
  87. stringstream ss;
  88. ss<<hex<<cipherTextHex.substr(i, ).c_str();
  89. ss>>x;
  90. c = (char)x;
  91. cipherText += c;
  92. if(i >= cipherTextHex.length() - )break;
  93. i += ;
  94. }
  95.  
  96. try {
  97. CryptoPP::AES::Decryption aesDecryption(s_key, CryptoPP::AES::DEFAULT_KEYLENGTH);
  98. CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, s_iv );
  99. //CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedText ),CryptoPP::StreamTransformationFilter::NO_PADDING);
  100. CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedText ));
  101. stfDecryptor.Put( reinterpret_cast<const unsigned char*>( cipherText.c_str() ), cipherText.size());
  102.  
  103. stfDecryptor.MessageEnd();
  104. } catch (const std::exception &e) {
  105. decryptedText = "";
  106. }
  107.  
  108. return decryptedText;
  109. }
  110.  
  111. int main() {
  112. cryptopp::init("", "");
  113. string en = cryptopp::encrypt("hello world, cryptopp");
  114. cout << en << endl;
  115. cout << cryptopp::decrypt(en) << endl;
  116. }

编译 g++ cryptopp.cpp -lcryptopp

运行输出

  1. $./a.out
  2. [, -, -, -, , -, , , -, -, -, -, -, -, -, -, -, -, -, -, -, , -, , -, , , , -, , -, -, ]
  3. 02d2cd9c25cf0b48e386f1cfd4d8efbbf2bb90ec8462f86ca8211713be03d0c5
  4. hello world, cryptopp

C++ 和 java 使用 AES CBC 128 加解密的更多相关文章

  1. Java 使用AES/CBC/PKCS7Padding 加解密字符串

    介于java 不支持PKCS7Padding,只支持PKCS5Padding 但是PKCS7Padding 和 PKCS5Padding 没有什么区别要实现在java端用PKCS7Padding填充, ...

  2. JAVA AES CBC PKCS5Padding加解密

    package com.hzxc.groupactivity.util; /** * Created by hdwang on 2019/1/17. */ import org.slf4j.Logge ...

  3. AES CBC/CTR 加解密原理

    So, lets look at how CBC works first. The following picture shows the encryption when using CBC (in ...

  4. 使用java实现AES算法的加解密(亲测可用)

    话不多说,直接上代码 import javax.crypto.Cipher;   import javax.crypto.spec.IvParameterSpec; import javax.cryp ...

  5. openssl:AES CBC PKCS5 加解密 (C/GOLANG)

    #include <openssl/aes.h> /* AES_CBC_PKCS5_Encrypt * 入参: * src:明文 * srcLen:明文长度 * key:密钥 长度只能是1 ...

  6. python 实现 AES CBC模式加解密

    AES加密方式有五种:ECB, CBC, CTR, CFB, OFB 从安全性角度推荐CBC加密方法,本文介绍了CBC,ECB两种加密方法的python实现 python 在 Windows下使用AE ...

  7. 手机号的 AES/CBC/PKCS7Padding 加解密

    前言:接口中上次的手机号码和密码是传入的加密的,模拟自动化的时候也需要先对数据进行加密 1.各种语言实现 网上已经各种语言实现好的AES加密,可以点击查看:http://outofmemory.cn/ ...

  8. python 实现 AES ECB模式加解密

    AES ECB模式加解密使用cryptopp完成AES的ECB模式进行加解密. AES加密数据块分组长度必须为128比特,密钥长度可以是128比特.192比特.256比特中的任意一个.(8比特 == ...

  9. JAVA实现AES的加密和解密算法

    原文 JAVA实现AES的加密和解密算法 import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import ja ...

随机推荐

  1. thinkphp5最美跳转页面

    声明下:此教程来自TP官网,如果需要看原文,请点击一下链接   http://www.thinkphp.cn/code/3437.html 先给大家看下效果: 直接撸代码: 第一步:为了增加对移动设备 ...

  2. Centos7源码编译安装tengine1.5.1

    安装依赖包 yum install pcre pcre-devel openssl openssl-devel gcc make zlib-devel wget -y 下载和创建用户 mkdir /t ...

  3. (二)mysql忘记root密码

    (1)mysql 5.7.6以前版本 修改配置文件vim /etc/my.cnf [mysqld] skip-grant-tables 重启mysql systemctl restart mysqld ...

  4. [thinkphp] 公共头部底部如何传递数据

    分组底下有一个公共模板文件夹 Modules/Index/Tpl/public/ 如何传递数据给模板呢? 在  入口文件/Lib/Action/  中创建类CommonAction.class.php ...

  5. HDU 2551 竹青遍野(循环,水)

    /* 他开始在他的院子种竹子,第1个月种1根竹子,第2个月种8根竹子,第3个月种27根竹子 ...第N个月就种(N^3)根竹子.当他种下第X根竹子那一刻,就是他重出江湖之时! 告诉你X的值, 你能算出 ...

  6. 分享Kali Linux 2017年第29周镜像文件

     分享Kali Linux 2017年第29周镜像文件 Kali Linux官方于7月16日发布2017年的第29周镜像.这次维持了11个镜像文件的规模.默认的Gnome桌面的4个镜像,E17.KDE ...

  7. [BZOJ 4144] Petrol

    Link: BZOJ 4144 传送门 Solution: 一道不错的图论综合题 因为只询问关键点,因此重点是要求出关键点之间的最短路,以最短路建图 记$nst[i]$为离$i$最近的关键点:可以发现 ...

  8. 【矩阵哈希】【二分答案】【哈希表】bzoj1567 [JSOI2008]Blue Mary的战役地图

    引用题解:http://hzwer.com/5153.html 当然,二分可以换成哈希表. #include<cstdio> #include<iostream> #inclu ...

  9. Oracle常见故障问题

    1. ORA-27102: out of memory 创建pfile文件: create pfile from spfile: 修改pfile文件 修改文件/home/oracle/app/orac ...

  10. &#x开头的是什么编码?

    在 Node 层利用 cheerio 解析网页时,输出的中文内容都是以 &#x 开头的一堆像乱码一样的东西,尝试过各种编码都无效,而且神奇的是,将这一堆“乱码”保存成网页后,通过浏览器打开又可 ...