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 ...
随机推荐
- B/S,C/S架构的区别
B/S架构:browser/server,采用的是浏览器服务器模式. C/S架构:client/server,采用的是客户端服务器模式. B/S架构,客户端是浏览器基本不需要维护,只需要维护升级服务器 ...
- Ant Design -- 图片可拖拽效果,图片跟随鼠标移动
Ant Design 图片可拖拽效果,图片跟随鼠标移动,需计算鼠标在图片中与图片左上角的X轴的距离和鼠标在图片中与图片左上角的Y轴的距离. constructor(props) { super(pro ...
- VB程序设计中Combobox的取值问题
Private a As Double Private Sub Combo1_Click() '1位小数,系数用10 a = Combo1.ItemData(Combo1.ListIn ...
- 03python面向对象编程5
5.1 继承机制及其使用 继承是面向对象的三大特征之一,也是实现软件复用的重要手段.Python 的继承是多继承机制,即一个子类可以同时有多个直接父类. Python 子类继承父类的语法是在定义子类时 ...
- ffmpeg使用分析视频
https://www.cnblogs.com/Finley/p/8646711.html 先存下
- 计蒜客 蓝桥模拟 F. 结果填空:数独
代码: #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream& ...
- 【学习】022 ActiveMQ
一.消息中间件概述 1.1消息中间件产生的背景 在客户端与服务器进行通讯时.客户端调用后,必须等待服务对象完成处理返回结果才能继续执行. 客户与服务器对象的生命周期紧密耦合,客户进程和服务对象进程都 ...
- python3-使用__slots__
正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性.先定义class: class Student(object): pa ...
- AGC007题解
发现自己思维能力又跟不上了...做题有点吃力...所以回归AGC刷题计划... AGC040506都写了一部分题然后懒得补全了,所以从07开始做吧.大概是从C开始. C 这也太人类智慧了吧... 我先 ...
- Keras MAE和MSE source code
def mean_squared_error(y_true, y_pred): if not K.is_tensor(y_pred): y_pred = K.constant(y_pred) y_tr ...