java实现多种加密模式的AES算法-总有一种你用的着
https://blog.csdn.net/u013871100/article/details/80100992
AES-128位-无向量-ECB/PKCS7Padding
package com.debug.steadyjack.springbootMQ.server.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
/**
* AES加密算法util
* Created by steadyjack on 2018/4/21.
*/
public class AESUtil {
private static final String EncryptAlg ="AES";
private static final String Cipher_Mode="AES/ECB/PKCS7Padding";
private static final String Encode="UTF-8";
private static final int Secret_Key_Size=32;
private static final String Key_Encode="UTF-8";
/**
* AES/ECB/PKCS7Padding 加密
* @param content
* @param key 密钥
* @return aes加密后 转base64
* @throws Exception
*/
public static String aesPKCS7PaddingEncrypt(String content, String key) throws Exception {
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Cipher cipher = Cipher.getInstance(Cipher_Mode);
byte[] realKey=getSecretKey(key);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(realKey,EncryptAlg));
byte[] data=cipher.doFinal(content.getBytes(Encode));
String result=new Base64().encodeToString(data);
return result;
} catch (Exception e) {
e.printStackTrace();
throw new Exception("AES加密失败:content=" +content +" key="+key);
}
}
/**
* AES/ECB/PKCS7Padding 解密
* @param content
* @param key 密钥
* @return 先转base64 再解密
* @throws Exception
*/
public static String aesPKCS7PaddingDecrypt(String content, String key) throws Exception {
try {
//Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
byte[] decodeBytes=Base64.decodeBase64(content);
Cipher cipher = Cipher.getInstance(Cipher_Mode);
byte[] realKey=getSecretKey(key);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(realKey,EncryptAlg));
byte[] realBytes=cipher.doFinal(decodeBytes);
return new String(realBytes, Encode);
} catch (Exception e) {
e.printStackTrace();
throw new Exception("AES解密失败:Aescontent = " +e.fillInStackTrace(),e);
}
}
/**
* 对密钥key进行处理:如密钥长度不够位数的则 以指定paddingChar 进行填充;
* 此处用空格字符填充,也可以 0 填充,具体可根据实际项目需求做变更
* @param key
* @return
* @throws Exception
*/
public static byte[] getSecretKey(String key) throws Exception{
final byte paddingChar=' ';
byte[] realKey = new byte[Secret_Key_Size];
byte[] byteKey = key.getBytes(Key_Encode);
for (int i =0;i<realKey.length;i++){
if (i<byteKey.length){
realKey[i] = byteKey[i];
}else {
realKey[i] = paddingChar;
}
}
return realKey;
}
}
————————————————
public static void main(String[] args) throws Exception{
//密钥 加密内容(对象序列化后的内容-json格式字符串)
String key="debug";
String content="{\"domain\":{\"method\":\"getDetails\",\"url\":\"http://www.baidu.com\"},\"name\":\"steadyjack_age\",\"age\":\"23\",\"address\":\"Canada\",\"id\":\"12\",\"phone\":\"15627284601\"}";
String encryptRes=aesPKCS7PaddingEncrypt(content,key);
System.out.println(String.format("加密结果:%s ",encryptRes));
String decryptRes=aesPKCS7PaddingDecrypt(encryptRes,key);
System.out.println(String.format("解密结果:%s ",decryptRes));
}
AES-128位-有向量-CBC/PKCS5Padding
package com.debug.steadyjack.springbootMQ.server.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
/**
* AES加解密工具
* Created by steadyjack on 2018/2/9.
*/
public class EncryptUtil {
private static final String CipherMode="AES/CBC/PKCS5Padding";
private static final String SecretKey="debug";
private static final Integer IVSize=16;
private static final String EncryptAlg ="AES";
private static final String Encode="UTF-8";
private static final int SecretKeySize=32;
private static final String Key_Encode="UTF-8";
/**
* 创建密钥
* @return
*/
private static SecretKeySpec createKey(){
StringBuilder sb=new StringBuilder(SecretKeySize);
sb.append(SecretKey);
if (sb.length()>SecretKeySize){
sb.setLength(SecretKeySize);
}
if (sb.length()<SecretKeySize){
while (sb.length()<SecretKeySize){
sb.append(" ");
}
}
try {
byte[] data=sb.toString().getBytes(Encode);
return new SecretKeySpec(data, EncryptAlg);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* 创建16位向量: 不够则用0填充
* @return
*/
private static IvParameterSpec createIV() {
StringBuffer sb = new StringBuffer(IVSize);
sb.append(SecretKey);
if (sb.length()>IVSize){
sb.setLength(IVSize);
}
if (sb.length()<IVSize){
while (sb.length()<IVSize){
sb.append("0");
}
}
byte[] data=null;
try {
data=sb.toString().getBytes(Encode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return new IvParameterSpec(data);
}
/**
* 加密:有向量16位,结果转base64
* @param context
* @return
*/
public static String encrypt(String context) {
try {
byte[] content=context.getBytes(Encode);
SecretKeySpec key = createKey();
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.ENCRYPT_MODE, key, createIV());
byte[] data = cipher.doFinal(content);
String result=Base64.encodeBase64String(data);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
* @param context
* @return
*/
public static String decrypt(String context) {
try {
byte[] data=Base64.decodeBase64(context);
SecretKeySpec key = createKey();
Cipher cipher = Cipher.getInstance(CipherMode);
cipher.init(Cipher.DECRYPT_MODE, key, createIV());
byte[] content = cipher.doFinal(data);
String result=new String(content,Encode);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) throws Exception{
//密钥 加密内容(对象序列化后的内容-json格式字符串)
String content="{\"domain\":{\"method\":\"getDetails\",\"url\":\"http://www.baidu.com\"},\"name\":\"steadyjack_age\",\"age\":\"23\",\"address\":\"Canada\",\"id\":\"12\",\"phone\":\"15627284601\"}";
String encryptText=encrypt(content);
String decryptText=decrypt(encryptText);
System.out.println(String.format("明文:%s \n加密结果:%s \n解密结果:%s ",content,encryptText,decryptText));
}
}
java实现多种加密模式的AES算法-总有一种你用的着的更多相关文章
- Java数据结构之字符串模式匹配算法---Brute-Force算法
模式匹配 在字符串匹配问题中,我们期待察看源串 " S串 " 中是否含有目标串 " 串T " (也叫模式串).其中 串S被称为主串,串T被称为子串. 1.如果在 ...
- Java数据结构之字符串模式匹配算法---KMP算法2
直接接上篇上代码: //KMP算法 public class KMP { // 获取next数组的方法,根据给定的字符串求 public static int[] getNext(String sub ...
- Java数据结构之字符串模式匹配算法---KMP算法
本文主要的思路都是参考http://kb.cnblogs.com/page/176818/ 如有冒犯请告知,多谢. 一.KMP算法 KMP算法可以在O(n+m)的时间数量级上完成串的模式匹配操作,其基 ...
- java.. C# 使用AES加密互解 采用AES-128-ECB加密模式
java需要下载外部包, commons codec.jar 1.6 較新的JAVA版本把Base64的方法改成靜態方法,可能會寫成Base64.encodeToString(encrypted, ...
- AES Java加密 C#解密 (128-ECB加密模式)
在项目中遇到这么一个问题: java端需要把一些数据AES加密后传给C#端,找了好多资料,算是解决了,分享一下: import sun.misc.BASE64Decoder; import sun.m ...
- AES算法加密java实现
package cn.itcast.coderUtils; import java.security.Key; import javax.crypto.Cipher; import javax.cry ...
- C#与Java互通AES算法加密解密
/// <summary>AES加密</summary> /// <param name="text">明文</param> /// ...
- .NET与Java互通AES算法加密解密
/// <summary>AES加密</summary> /// <param name="text">明文</param> /// ...
- 无线路由器的加密模式WEP,WPA-PSK(TKIP),WPA2-PSK(AES) WPA-PSK(TKIP)+WPA2-PSK(AES)。
目前无线路由器里带有的加密模式主要有:WEP,WPA-PSK(TKIP),WPA2-PSK(AES)和WPA-PSK(TKIP)+WPA2-PSK(AES). WEP(有线等效加密)WEP是Wired ...
随机推荐
- 二、JVM — 垃圾回收
JVM 垃圾回收 写在前面 本节常见面试题 本文导火索 1 揭开 JVM 内存分配与回收的神秘面纱 1.1 对象优先在 eden 区分配 1.2 大对象直接进入老年代 1.3 长期存活的对象将进入老年 ...
- pureftp安装
1.下载 #cd /usr/local/src #wget http://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-1.0.36.t ...
- CPU与GPU,我们应该使用哪个?
CPU与GPU,我们应该使用哪个? CPU与GPU CPU即中央处理器,GPU即图形处理器. 两者的相同之处:两者都有总线和外界联系,有自己的缓存体系,以及数字和逻辑运算单元 两者的区别之处:在于存在 ...
- Apache 的 httpd-mpm.conf 文件详解
#prefork 多路处理模块 <IfModule mpm_prefork_module> StartServers 5 #设置服务器启动时建立的子进程数量, ...
- 2019 计蒜之道 复赛 B. 个性化评测系统 (模拟,实现,暴搜)
24.02% 1000ms 262144K "因材施教"的教育方式自古有之,互联网时代,要实现真正意义上的个性化教育,离不开大数据技术的扶持.VIPKID 英语 2020 多万学员 ...
- Codeforces 935 简单几何求圆心 DP快速幂求与逆元
A #include <bits/stdc++.h> #define PI acos(-1.0) #define mem(a,b) memset((a),b,sizeof(a)) #def ...
- New Machine Learning Server for Deep Learning in Nuke(翻译)
最近一直在开发Orchestra Pipeline System,歇两天翻译点文章换换气.这篇文章是无意间看到的,自己从2015年就开始关注机器学习在视效领域的应用了,也曾利用碎片时间做过一些算法移植 ...
- c调用c++
g++ main.c math.cpp math.h中加入extern "C"
- [易学易懂系列|golang语言|零基础|快速入门|(二)]
现在我们来写代码,首先我们要新建一个项目. 新建项目: 点击:File>>New>>Project...如下图: 在New Project窗口,Location:输入:“goP ...
- php 强制类型转换
123 123.01 array("123",123) true false null (string) "123" "123.01" ...