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

  1. AES在线加密解密-附AES128,192,256,CBC,CFB,ECB,OFB,PCBC各种加密解密源码

    一.AES在线加密解密:AES 128/192/256位CBC/CFB/ECB/OFB/PCBC在线加密解密|在线工具|在线助手|在线生成|在线制作 http://www.it399.com/aes ...

  2. PHP AES的加密解密

    AES加密算法 密码学中的高级加密标准(Advanced Encryption Standard,AES),又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准.这个标准用来替代原先的DE ...

  3. PHP AES的加密解密-----【弃用】

    mcrypt_decrypt在PHP7.*已经被弃用,取而代之的是openssl_decrypt/encrypt,请参考: PHP7.* AES的加密解密 AES加密算法 密码学中的高级加密标准(Ad ...

  4. 一个java的DES加密解密类转换成C#

    一个java的des加密解密代码如下: //package com.visionsky.util; import java.security.*; //import java.util.regex.P ...

  5. 兼容PHP和Java的des加密解密代码分享

    这篇文章主要介绍了兼容PHP和Java的des加密解密代码分享,适合如服务器是JAVA语言编写,客户端是PHP编写,并需要des加密解密的情况,需要的朋友可以参考下 作为一个iOS工程师来解决安卓的问 ...

  6. PHP7.* AES的加密解密

    之前写过一篇: PHP AES的加密解密-----[弃用] 使用的是php5.*之前的mcrypt_decrypt 函数,该函数已经在php7.1后弃用了,上马的是openssl的openssl_en ...

  7. Java常用的加密解密类(对称加密类)

    Java常用的加密解密类 原文转载至:http://blog.csdn.net/wyc_cs/article/details/8793198 原创 2013年04月12日 14:33:35 1704 ...

  8. AES对称加密解密类

    import java.io.UnsupportedEncodingException; import javax.crypto.Cipher; import javax.crypto.spec.Se ...

  9. Golang之AES/DES加密解密

    AES/DES加密/解密涉及4个概念:1. Block, 也叫分组, 相应加密/解密的算法. 2. BlockMode, 模式, 相应加密/解密的处理.3. InitalVectory, 初始向量4. ...

随机推荐

  1. ionic3使用cnpm可能会出现的问题

    在跑一个ionic3项目的时候发现,新建的页面无法被识别,总是报错 cannot find modules '../pages/login/login.modules' 在排除多种可能性后,确定了是因 ...

  2. Sumo生成数据

    1.生成input_net.net.xml文件 参数解释:http://www.sumo.dlr.de/userdoc/NETGENERATE.html#Grid_Network 1).生成grid ...

  3. 解决SpringMVC+Thymeleaf中文乱码

    乱码效果截图 解决办法:在org.thymeleaf.templateresolver.ServletContextTemplateResolver和org.thymeleaf.spring5.vie ...

  4. DevExpress.Mvvm.Free

    DevExpress MVVM Framework is a set of components helping to work in the Model-View-ViewModel pattern ...

  5. spoj Minimax Triangulation

    题解: dp+计算几何 F[i][j]表示第i-j条边的答案 然后转移一下 代码: #include<bits/stdc++.h> using namespace std; ]; ][]; ...

  6. 在Linux终端安装Julia

    官方参考文档:https://julialang.org/downloads/platform.html#generic-binaries 一.centos终端安装 打开Linux终端输入 sudo ...

  7. python编码及转换

    第一种:ASCII码 ASCII(American Standard Code for Information Interchange,美国信息交换标准代码)是基于拉丁字母的一套电脑编码系统,主要用于 ...

  8. 模仿select下拉列表

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...

  9. LNMP(二)

    第二十一课 LNMP(二) 目录 一.默认虚拟主机 二.Nginx用户认证 三.Nginx域名重定向 四.Nginx访问日志 五.Nginx日志切割 六.静态文件不记录日志和过期时间 七.Nginx防 ...

  10. VMware网络连接模式——桥接模式、NAT模式以及仅主机模式的介绍和区别

    在使用VMware Workstation(以下简称:VMware)创建虚拟机的过程中,配置虚拟机的网络连接是非常重要的一环,当我们为虚拟机配置网络连接时,我们可以看到如下图所示的几种网络连接模式:桥 ...