JAVA AES CBC 加密 解密
AES 256 , KEY 的长度为 32字节(32*8=256bit).
AES 128 , KEY 的长度为 16字节(16*8=128bit)
CBC 模式需要IV, IV的值是固定写死,还是当参数传入,自己看情况。IV的长度没研究,这里用的是16字符。
java PKCS5Padding 对应 C#.NET 的 PKCS7 。
明文,KEY和IV 三者 string 转 byte[] 时要统一编码,如UTF-8。
加密后 cipher.doFinal() 得到密文byte[] ,是直接转string,还是转为base64编码的string ,要统一。
AesCbc:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication1; import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; /**
*
* @author jk
*/
public class AesCbc {
private static final String IV_STRING = "abcdefghABCDEFGH"; private static final String charset = "UTF-8"; // AES 266 = KEY 长度是32个字符 = (32*8=266)
public static String encrypt(String content, String key) {
try {
byte[] contentBytes = content.getBytes(charset);
byte[] keyBytes = key.getBytes(charset);
byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes);
return Base64Utils.encode(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} public static byte[] aesEncryptBytes(byte[] contentBytes, byte[] keyBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
return cipherOperation(contentBytes, keyBytes, Cipher.ENCRYPT_MODE);
} private static byte[] cipherOperation(byte[] contentBytes, byte[] keyBytes, int mode) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
//cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(java.util.Base64.Decoder.decode(IV.
SecretKeySpec keySpec=new SecretKeySpec(keyBytes,"AES");
Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");
byte[] initParam=IV_STRING.getBytes(charset);
IvParameterSpec ivParameterSpec=new IvParameterSpec(initParam);
// SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
// byte[] initParam = IV_STRING.getBytes(charset);
// IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);
// Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(mode, keySpec, ivParameterSpec);
return cipher.doFinal(contentBytes);
} public static String decrypt(String content, String key) {
try {
byte[] encryptedBytes = Base64Utils.decode(content);
byte[] keyBytes = key.getBytes(charset);
byte[] decryptedBytes = aesDecryptBytes(encryptedBytes, keyBytes);
return new String(decryptedBytes, charset);
}catch (Exception e){
e.printStackTrace();
}
return null;
} public static byte[] aesDecryptBytes(byte[] contentBytes, byte[] keyBytes) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
return cipherOperation(contentBytes, keyBytes, Cipher.DECRYPT_MODE);
}
}
Base64Utils:
package javaapplication1; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.codec.binary.Base64; /**
* */
/**
* <p>
* BASE64编码解码工具包
* </p>
* <p>
* 依赖javabase64-1.3.1.jar
* </p>
*
* @author IceWee
* @date 2012-5-19
* @version 1.0
*/
public class Base64Utils { /**
* */
/**
* 文件读取缓冲区大小
*/
private static final int CACHE_SIZE = 1024; public static final String _charset = "UTF-8"; /**
* */
/**
* <p>
* BASE64字符串解码为二进制数据
* </p>
*
* @param base64
* @return
* @throws Exception
*/
public static byte[] decode(String str) throws Exception {
Base64 _base64 = new Base64();
return _base64.decodeBase64(str.getBytes(_charset));
} /**
* */
/**
* <p>
* 二进制数据编码为BASE64字符串
* </p>
*
* @param bytes
* @return
* @throws Exception
*/
public static String encode(byte[] bytes) throws Exception {
Base64 _base64 = new Base64();
return new String(_base64.encodeBase64Chunked(bytes));
} /**
* */
/**
* <p>
* 将文件编码为BASE64字符串
* </p>
* <p>
* 大文件慎用,可能会导致内存溢出
* </p>
*
* @param filePath 文件绝对路径
* @return
* @throws Exception
*/
public static String encodeFile(String filePath) throws Exception {
byte[] bytes = fileToByte(filePath);
return encode(bytes);
} /**
* */
/**
* <p>
* BASE64字符串转回文件
* </p>
*
* @param filePath 文件绝对路径
* @param base64 编码字符串
* @throws Exception
*/
public static void decodeToFile(String filePath, String base64) throws Exception {
byte[] bytes = decode(base64);
byteArrayToFile(bytes, filePath);
} /**
* */
/**
* <p>
* 文件转换为二进制数组
* </p>
*
* @param filePath 文件路径
* @return
* @throws Exception
*/
public static byte[] fileToByte(String filePath) throws Exception {
byte[] data = new byte[0];
File file = new File(filePath);
if (file.exists()) {
FileInputStream in = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
data = out.toByteArray();
}
return data;
} /**
* */
/**
* <p>
* 二进制数据写文件
* </p>
*
* @param bytes 二进制数据
* @param filePath 文件生成目录
*/
public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
InputStream in = new ByteArrayInputStream(bytes);
File destFile = new File(filePath);
if (!destFile.getParentFile().exists()) {
destFile.getParentFile().mkdirs();
}
destFile.createNewFile();
OutputStream out = new FileOutputStream(destFile);
byte[] cache = new byte[CACHE_SIZE];
int nRead = 0;
while ((nRead = in.read(cache)) != -1) {
out.write(cache, 0, nRead);
out.flush();
}
out.close();
in.close();
} }
base 64 编码引用了 org.apache.commons.codec.binary.Base64,可以从网上下载。
测试代码 main:
static void TestAesCbc() {
String cc = "中华人民共和国~!@#¥%……&*()——+12345678ABC中华人民共和国~!@#¥%……&*()——+12345678ABC中华人民共和国~!@#¥%……&*()——+12345678ABC中华人民共和国~!@#¥%……&*()——+12345678ABC";
System.out.println("明文:\r\n" + cc);
System.out.println("AES 256 -------:\r\n");
String aesKey = "12345678901234567890123456789012";
String aa = AesCbc.encrypt(cc, aesKey);
System.out.println("密文:\r\n" + aa);
String dd = AesCbc.decrypt(aa, aesKey);
System.out.println("解密后明文:\r\n" + dd);
System.out.println("AES 128 -------:\r\n");
String aesKey2 = "1234567890123456";
aa = AesCbc.encrypt(cc, aesKey2);
System.out.println("密文:\r\n" + aa);
dd = AesCbc.decrypt(aa, aesKey2);
System.out.println("解密后明文:\r\n" + dd);
}
end
JAVA AES CBC 加密 解密的更多相关文章
- AES在线加密解密-附AES128,192,256,CBC,CFB,ECB,OFB,PCBC各种加密解密源码
一.AES在线加密解密:AES 128/192/256位CBC/CFB/ECB/OFB/PCBC在线加密解密|在线工具|在线助手|在线生成|在线制作 http://www.it399.com/aes ...
- PHP AES的加密解密
AES加密算法 密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准.这个标准用来替代原先的DE ...
- PHP AES的加密解密-----【弃用】
mcrypt_decrypt在PHP7.*已经被弃用,取而代之的是openssl_decrypt/encrypt,请参考: PHP7.* AES的加密解密 AES加密算法 密码学中的高级加密标准(Ad ...
- 一个java的DES加密解密类转换成C#
一个java的des加密解密代码如下: //package com.visionsky.util; import java.security.*; //import java.util.regex.P ...
- 兼容PHP和Java的des加密解密代码分享
这篇文章主要介绍了兼容PHP和Java的des加密解密代码分享,适合如服务器是JAVA语言编写,客户端是PHP编写,并需要des加密解密的情况,需要的朋友可以参考下 作为一个iOS工程师来解决安卓的问 ...
- PHP7.* AES的加密解密
之前写过一篇: PHP AES的加密解密-----[弃用] 使用的是php5.*之前的mcrypt_decrypt 函数,该函数已经在php7.1后弃用了,上马的是openssl的openssl_en ...
- Java常用的加密解密类(对称加密类)
Java常用的加密解密类 原文转载至:http://blog.csdn.net/wyc_cs/article/details/8793198 原创 2013年04月12日 14:33:35 1704 ...
- AES对称加密解密类
import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.Se ...
- Golang之AES/DES加密解密
AES/DES加密/解密涉及4个概念:1. Block, 也叫分组, 相应加密/解密的算法. 2. BlockMode, 模式, 相应加密/解密的处理.3. InitalVectory, 初始向量4. ...
随机推荐
- Ajax+Struts2用户注册功能实现
详细请参考源码(Github):https://github.com/QQ3330447288/ajaxRegister 1.目录结构 2.截图 3.核心代码: register.jsp <sc ...
- 机器学习之决策树_CART算法
目录 3.CART算法(classification and regression tree tree) 3.1 CART生成算法(回归树生成和分类树生成) 3.2 CART剪枝 决策树基本知识参考, ...
- pycharm 执行unittest 没有生成测试报告
解决: [第一步] [第二步]
- 『流畅的Python』第5章笔记_一等函数
- jq初入行常用动画
--jq动画分类--(1)jQuery的动画其实就是将之前提到过的各种特效进行封装,并对其性能进行优化.(2)jQuery动画分为三个部分:非自定义动画,自定义动画,和全局动画设置. 一.非自定义动画 ...
- React文档(十一)提升state
经常有些组件需要映射同一个改变的数据.我们建议将共用的state提升至最近的同一个祖先元素.我们来看看这是怎样运作的. 在这一节中,我们会创建一个温度计算器来计算提供的水温是否足够沸腾. 我们先创建一 ...
- mac 配置php+php_fpm+nginx
首先brew安装前面文章上有的 安装nginx brew install nginx #启动nginx sudo nginx #测试配置是否有语法错误 sudo nginx -t 测试成功 如果不加 ...
- learning makefile var
- day08_python_1124
01 昨日内容回顾 文件操作 文件操作的流程: 1,打开文件创建文件句柄. 2,对文件句柄进行操作. 3,关闭文件句柄. 读, r r+ rb r+b read() 全部读取 read(n) 读取一部 ...
- Android动画-View动画
View动画 Android动画分为三类:View动画,帧动画,和属性动画.帧动画也是View动画的一种. View动画的作用对象是View,之所以强调这一点是因为其作用对象有别于Android的另一 ...