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 对称加密的更多相关文章

  1. vue中使用AES.js和crypto.js加密

    一:crypto-js加密 1.1:安装依赖 npm install crypto-js --save-dev 1.2 :在项目目录上创建一个js文件里面写入加密,解密的代码 mport Crypto ...

  2. 数字签名中公钥和私钥是什么?对称加密与非对称加密,以及RSA的原理

    http://baijiahao.baidu.com/s?id=1581684919791448393&wfr=spider&for=pc https://blog.csdn.net/ ...

  3. 对称加密与非对称加密,以及RSA的原理

    一 , 概述 在现代密码学诞生以前,就已经有很多的加密方法了.例如,最古老的斯巴达加密棒,广泛应用于公元前7世纪的古希腊.16世纪意大利数学家卡尔达诺发明的栅格密码,基于单表代换的凯撒密码.猪圈密码, ...

  4. (转)对称加密与非对称加密,以及RSA的原理

    一 概述 二对称加密和非对称加密 对称加密 非对称加密 区别 三RSA原理 整数运算 同余运算 当模数为合数n时 当模数为质数p的时候 离散对数问题 RSA原理 一 , 概述 在现代密码学诞生以前,就 ...

  5. 对称加密与非对称加密,及Hash算法

    一 , 概述 在现代密码学诞生以前,就已经有很多的加密方法了.例如,最古老的斯巴达加密棒,广泛应用于公元前7世纪的古希腊.16世纪意大利数学家卡尔达诺发明的栅格密码,基于单表代换的凯撒密码.猪圈密码, ...

  6. 对称加密----AES和DES加密、解密

    目前主流的加密方式有:(对称加密)AES.DES        (非对称加密)RSA.DSA 调用AES/DES加密算法包最精要的就是下面两句话: Cipher cipher = Cipher.get ...

  7. AES/CBC/PKCS5Padding对称加密

    package unit; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.cry ...

  8. JDK自带方法实现AES对称加密

    请看代码. 1 package jdbc.pro.lin; 2 3 import java.security.InvalidAlgorithmParameterException; 4 import ...

  9. 前后端对称加密(AES)

    后端实现(JAVA) package com.vcgeek.hephaestus.demo; import org.apache.commons.codec.binary.Base64; import ...

随机推荐

  1. IndexError: list index out of range的错误原因

    第1种可能情况list[index]index超出范围 第2种可能情况list是一个空的 没有一个元素进行list[0]就会出现该错误 ————————————————版权声明:本文为CSDN博主「m ...

  2. 3,LinkedList

    一,LinkedList简介 1,LinkedList 是一个继承于AbstractSequentialList的双向链表.它也可以被当作堆栈.队列或双端队列进行操作. 2,LinkedList 实现 ...

  3. 【HDOJ6629】string matching(exkmp)

    题意:给定一个长为n的字符串,求其每个位置开始于其自身暴力匹配出相同或不同的结果的总比较次数 n<=1e6 思路:exkmp板子 #include<bits/stdc++.h> us ...

  4. Hive学习之路(一)Hive初识

    Hive简介 什么是Hive Hive由Facebook实现并开源 是基于Hadoop的一个数据仓库工具 可以将结构化的数据映射为一张数据库表 提供HQL(Hive SQL)查询功能 底层数据是存储在 ...

  5. 2017年度最具商业价值人工智能公司TOP50 榜单发布

    2017年度最具商业价值人工智能公司TOP50 榜单发布 未来最有赚钱潜力的50个人工智能项目都在这里了. 经过了60年的发展,人工智能在2017年,正式走向应用的元年. 从今年起,人工智能首次被写入 ...

  6. CDN:BootCDN 项目列表-摘录-20180405

    ylbtech-CDN:BootCDN 项目列表-20180405 1.返回顶部 1.   2. 2.返回顶部   3.返回顶部   4.返回顶部   5.返回顶部 1. http://www.boo ...

  7. gitlab+jenkins自动化打包IOS-jenkins配置

    实现的效果如图:  构建界面: 完成效果: 功能说明: 根据选择的代码分支,执行构建打包 构建成功后根据ipa/apk生成二维码,并可在历史构建列表中展示各个版本的二维码,通过手机扫描二维码可直接安装 ...

  8. (appium+python)UI自动化_03_元素定位工具

    前言 在UI自动化过程中,需要对手机app上的元素进行定位,然后进一步编写自动化脚本操作app.定位元素首先需要定位工具来辅助查看页面元素.小编常用的定位工具有2种,分别是uiautomatorvie ...

  9. Xpath表达式的粗介绍

    关于在自动化中Xpath表达式的书写,其实我也只是刚刚入门,粗略的跟着网上的教程学了一下,这篇我就来分享总结一下我学习到的知识. 首先呢,我们先认识一下什么是Xpath.Xpath是XML路径语言,它 ...

  10. NYOJ 654喜欢玩warcraft的ltl(01背包/常数级优化)

    传送门 Description ltl 非常喜欢玩warcraft,因为warcraft十分讲究团队整体实力,而他自己现在也为升级而不拖累团队而努力. 他现在有很多个地点来选择去刷怪升级,但是在每一个 ...