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. ...
随机推荐
- selenium自动加载各个浏览器插件
在自动化测试过程中,通过selenium启动浏览器时,可能需要加载插件(如测试用的firebug.或产品中要求必须添加某插件等).读取用户数据(自己浏览器的配置文件/别人直接给的浏览器配置文件).设置 ...
- 最近使用Navicat for MySQl访问远程mysql数据库,出现报错,显示“2003- Can't connect MySQL Server on 'localhost'(10038)“。
优先考虑mysql数据库是否开启 1.先看报错窗口. 通过百度,最终找到的原因是:远程3306端口未对外开放. 于是下面进行远程3306端口开放操作. 首先远程连接服务器,点击“开始”-“管理 ...
- Centos7 多网卡抓包可以抓到UDP但程序recvfrom不到
问题: Centos7多网卡,抓包时发现某网卡上有UDP包,但是用程序recvfrom无法接收到消息. 解决步骤: 1.确认防火墙是否关闭: 已关闭 2.确认网卡是否开启过滤:cat /proc/sy ...
- OSSIM安装使用教程(OSSIM-5.6.5)
一.说明 1.1 相关概念说明 SEM,security event management,安全事件管理,指对事件进行实时监控,收集信息差展生通知和告警的行为. SIM,security inform ...
- linux学习--目录切换命令 cd
- libdl.so 动态库加载、查找
使用libdl.so库 动态库加载原理 动态库中函数的查找已经封装成 libdl.so,有4个函数: dlopen : 打开一个动态库 dlsym : 在打开的动态库里找一个函数 dlclo ...
- SocketServer模块,hmac模块验证client合法性
hmac模块: 1.模块初识: import hmac # h = hmac.new() #括号里要给它连个bytes类型,一个是自定义的secret_key,一个是你想进行加密的bytes # 密文 ...
- vuex-state
Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中,且子组件能通过 this.$store访问 const app = new Vue({ el: '#app', ...
- 【深入理解Java集合框架】红黑树讲解(上)
来源:史上最清晰的红黑树讲解(上) - CarpenterLee 作者:CarpenterLee(转载已获得作者许可,如需转载请与原作者联系) 文中所有图片点击之后均可查看大图! 史上最清晰的红黑树讲 ...
- redis 集群常用命令
systemctl start redis.service #redis 启动redis-server /etc/redis.conf #redis 加载配置文件启动 redis-cli -h 192 ...