AES apache commons-crypto 对称加密
apache实现的AES256加密
官方用户指导链接:http://commons.apache.org/proper/commons-crypto/userguide.html
官方字节缓存实现的例子链接:http://commons.apache.org/proper/commons-crypto/xref-test/org/apache/commons/crypto/examples/CipherByteBufferExample.html
其实官方给了两种实现,另外一种是字节数组方式,如果加密的字符串过长,官方例子中的new的字节数组会异常,不如字节缓存方式更好。这里说下字节缓存的实现。
官方例子的main方法是加密和解密一起处理的,不实际;我将官方例子中的main方法里的逻辑拆出来了加密和解密两个方法(注:@slf4j需要用到lombok,如果你没有引入,则把该注解去掉,修改代码中的log)
package com.dmy.util; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.crypto.cipher.CryptoCipher;
import org.apache.commons.crypto.utils.Utils;
import org.springframework.util.Base64Utils; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.util.Properties; /**
* Example showing the CryptoCipher API using a ByteBuffer
*/
@Slf4j
public class CipherByteBufferExample {
//32字节长度的秘钥,也就是256位
static final SecretKeySpec key = new SecretKeySpec(getUTF8Bytes("12345678901234561234567890123456"), "AES");
//固定16字节长度
static final IvParameterSpec iv = new IvParameterSpec(getUTF8Bytes("1234567890123456"));
//加密方法/加密模式/填充方式,CBC是安全性好于ECB,适合传输长度长的报文,是SSL、IPSec的标准
static final String transform = "AES/CBC/PKCS5Padding"; /**
* Converts String to UTF8 bytes
*
* @param input the input string
* @return UTF8 bytes
*/
private static byte[] getUTF8Bytes(String input) {
return input.getBytes(StandardCharsets.UTF_8);
} /**
* Converts ByteBuffer to String
*
* @param buffer input byte buffer
* @return the converted string
*/
private static String asString(ByteBuffer buffer) {
final ByteBuffer copy = buffer.duplicate();
final byte[] bytes = new byte[copy.remaining()];
copy.get(bytes);
return new String(bytes, StandardCharsets.UTF_8);
} /**
* 加密
* @param text 需要加密的明文
* @return 经过base64加密后的密文
* @throws IOException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws ShortBufferException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static String encrypt(String text) throws IOException, InvalidAlgorithmParameterException, InvalidKeyException, ShortBufferException, BadPaddingException, IllegalBlockSizeException {
Properties properties = new Properties();
final ByteBuffer outBuffer;
final int bufferSize = 1024;
final int updateBytes;
final int finalBytes;
//Creates a CryptoCipher instance with the transformation and properties.
try (CryptoCipher encipher = Utils.getCipherInstance(transform, properties)) { ByteBuffer inBuffer = ByteBuffer.allocateDirect(bufferSize);
outBuffer = ByteBuffer.allocateDirect(bufferSize);
inBuffer.put(getUTF8Bytes(text)); inBuffer.flip(); // ready for the cipher to read it
// Show the data is there
log.debug("inBuffer={}", asString(inBuffer)); // Initializes the cipher with ENCRYPT_MODE,key and iv.
encipher.init(Cipher.ENCRYPT_MODE, key, iv); // Continues a multiple-part encryption/decryption operation for byte buffer.
updateBytes = encipher.update(inBuffer, outBuffer);
log.debug("updateBytes={}", updateBytes); // We should call do final at the end of encryption/decryption.
finalBytes = encipher.doFinal(inBuffer, outBuffer);
log.debug("finalBytes={}", finalBytes);
} outBuffer.flip(); // ready for use as decrypt
byte[] encoded = new byte[updateBytes + finalBytes];
outBuffer.duplicate().get(encoded);
String encodedString = Base64Utils.encodeToString(encoded);
log.debug("encodedString={}", encodedString);
return encodedString;
} /**
* 解密
* @param encodedString 经过base64加密后的密文
* @return 明文
* @throws IOException
* @throws InvalidAlgorithmParameterException
* @throws InvalidKeyException
* @throws ShortBufferException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static String dencrypt(String encodedString) throws IOException, InvalidAlgorithmParameterException, InvalidKeyException, ShortBufferException, BadPaddingException, IllegalBlockSizeException {
Properties properties = new Properties();
final ByteBuffer outBuffer;
final int bufferSize = 1024;
ByteBuffer decoded = ByteBuffer.allocateDirect(bufferSize);
//Creates a CryptoCipher instance with the transformation and properties.
try (CryptoCipher decipher = Utils.getCipherInstance(transform, properties)) {
decipher.init(Cipher.DECRYPT_MODE, key, iv);
outBuffer = ByteBuffer.allocateDirect(bufferSize);
outBuffer.put(Base64Utils.decode(getUTF8Bytes(encodedString)));
outBuffer.flip();
decipher.update(outBuffer, decoded);
decipher.doFinal(outBuffer, decoded);
decoded.flip(); // ready for use
log.debug("decoded={}", asString(decoded));
} return asString(decoded);
} }
AES apache commons-crypto 对称加密的更多相关文章
- vue中使用AES.js和crypto.js加密
一:crypto-js加密 1.1:安装依赖 npm install crypto-js --save-dev 1.2 :在项目目录上创建一个js文件里面写入加密,解密的代码 mport Crypto ...
- 数字签名中公钥和私钥是什么?对称加密与非对称加密,以及RSA的原理
http://baijiahao.baidu.com/s?id=1581684919791448393&wfr=spider&for=pc https://blog.csdn.net/ ...
- 对称加密与非对称加密,以及RSA的原理
一 , 概述 在现代密码学诞生以前,就已经有很多的加密方法了.例如,最古老的斯巴达加密棒,广泛应用于公元前7世纪的古希腊.16世纪意大利数学家卡尔达诺发明的栅格密码,基于单表代换的凯撒密码.猪圈密码, ...
- (转)对称加密与非对称加密,以及RSA的原理
一 概述 二对称加密和非对称加密 对称加密 非对称加密 区别 三RSA原理 整数运算 同余运算 当模数为合数n时 当模数为质数p的时候 离散对数问题 RSA原理 一 , 概述 在现代密码学诞生以前,就 ...
- 对称加密与非对称加密,及Hash算法
一 , 概述 在现代密码学诞生以前,就已经有很多的加密方法了.例如,最古老的斯巴达加密棒,广泛应用于公元前7世纪的古希腊.16世纪意大利数学家卡尔达诺发明的栅格密码,基于单表代换的凯撒密码.猪圈密码, ...
- 对称加密----AES和DES加密、解密
目前主流的加密方式有:(对称加密)AES.DES (非对称加密)RSA.DSA 调用AES/DES加密算法包最精要的就是下面两句话: Cipher cipher = Cipher.get ...
- AES/CBC/PKCS5Padding对称加密
package unit; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.cry ...
- JDK自带方法实现AES对称加密
请看代码. 1 package jdbc.pro.lin; 2 3 import java.security.InvalidAlgorithmParameterException; 4 import ...
- 前后端对称加密(AES)
后端实现(JAVA) package com.vcgeek.hephaestus.demo; import org.apache.commons.codec.binary.Base64; import ...
随机推荐
- 【leetcode】486. Predict the Winner
题目如下: Given an array of scores that are non-negative integers. Player 1 picks one of the numbers fro ...
- Android解析编译之后的所有文件(so,dex,xml,arsc)格式
我们在之前一篇一篇介绍了如何解析Android中编译之后的所有文件格式,所有的工作都完成了,这里我们就来做个总结,我们为什么要做这些工作: 第一篇:解析so文件格式 点击进入 这里我们解析so文件,主 ...
- OSI参考模型和网络排错
OSI七层协议 应用层 应用程序通信服务 表示层 显示 加密 数据格式 会话层 服务器和客户机建立会话 netstat -nb 查看会话 mscofig 传输层 可靠回话传输 分段 ...
- php面试专题---15、MySQL数据库基础考察点
php面试专题---15.MySQL数据库基础考察点 一.总结 一句话总结: 注意:只写精品 1.mysql定义int(3),那么我存1234就错了么? 不是:无影响:只会影响显示字符的个数:可以为整 ...
- UNITY编辑器模式下static变量的坑
在unity中写编辑器扩展工具,如在编辑器中加个菜单,点击这个菜单项时执行打包功能. 类如下,其中的静态变量,如果每次进来不清空,则LIST会越来越大,打包函数执行完后系统不会帮我们清空 #if UN ...
- 1204C Anna, Svyatoslav and Maps
题目大意 给你一个有向图和一个路径 让你在给定路径中选出尽量少的点使得新路径的最短路长度和原路径相等 给定路径相邻两点间距离为1 分析 先floyd求出两点间最短路 之后每次对于点i找到所有跟它的最短 ...
- chrome 手机端滑动列表的时候控制台会出现很多提示的解决办法
问题: Unable to preventDefault inside passive event listener 可以加入touch-action 属性,具体参照MDN, https://deve ...
- Vim 8.0 版本安装方法及添加Python支持
利用Git安装 最简单也是最有效的方法 1. 获取Vim仓库: git clone https://github.com/vim/vim.git 2. 升级到最新的版本: cd vim git pul ...
- Unity3D利用Logcat调试安卓
发布安卓包之后再次测试发生什么问题很难知道怎么了,比如说出现闪退等情况,可以用Logcat检测到,logcat是Android中一个命令行工具,可以用于得到程序的log信息,可以用 logcat 命令 ...
- JavaScript 高级程序设计(第3版)第二章 (在html中使用js)
1.script元素的属性(6个):①async(异步脚本),只对外部脚本有效 ②defer(延迟脚本),只对外部脚本有效 ③charset,src(可跨域),type,language 2.尽可能使 ...