AES前后端加密
1、前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="js/rollups/tripledes.js"></script>
<script src="js/components/aes.js"></script>
<script src="js/components/mode-ecb-min.js"></script>
</head>
<body>
<input id="test" name="gj">
<button onclick="test()">点击</button>
<script>
function test(){
var param = $("input[name='gj']").val();
Encrypt(param);
} var key = CryptoJS.enc.Utf8.parse('sadaasdsad');
function Encrypt(word){ var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
console.log(encrypted.toString());
}
function Decrypt(word) { var decrypt = CryptoJS.AES.decrypt(word, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
</script>
</body>
</html>
2、后端JAVA代码
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger; /**
* @Author:yw
* @Description:AES 加密解密
* @Date: Created in 18:392018/6/11
*/
public class AESUtil {
private static final String KEY ="sadaasdsad"
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默认的加密算法 /**
* AES 加密操作
*
* @param content 待加密内容
* @param password 加密密码
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content, String decryptKey) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));// 初始化为加密模式的密码器 byte[] result = cipher.doFinal(byteContent);// 加密 return Base64.encodeBase64String(result);//通过Base64转码返回
} catch (Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
} return null;
} /**
* AES 加密操作
*
* @param content 待加密内容
* @param password 加密密码
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器 byte[] byteContent = content.getBytes("utf-8"); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"));// 初始化为加密模式的密码器 byte[] result = cipher.doFinal(byteContent);// 加密 return Base64.encodeBase64String(result);//通过Base64转码返回
} catch (Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
} return null;
}
/**
* AES 解密操作
*
* @param content
* @param password
* @return
*/
public static String decrypt(String content, String decryptKey) { try {
//实例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); //使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(decryptKey.getBytes(), "AES")); //执行操作
byte[] result = cipher.doFinal(Base64.decodeBase64(content)); return new String(result, "utf-8");
} catch (Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
} return null;
} /**
* AES 解密操作
*
* @param content
* @param password
* @return
*/
public static String decrypt(String content) { try {
//实例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); //使用密钥初始化,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(KEY.getBytes(), "AES")); //执行操作
byte[] result = cipher.doFinal(Base64.decodeBase64(content)); return new String(result, "utf-8");
} catch (Exception ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
} return null;
}
/**
* 生成加密秘钥
*
* @return
*/
private static SecretKeySpec getSecretKey(final String password) {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = null; try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM); //AES 要求密钥长度为 128
kg.init(128, new SecureRandom(password.getBytes())); //生成一个密钥
SecretKey secretKey = kg.generateKey(); return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
} public static void main(String[] args) {
String content = "13958160820"; //0gqIDaFNAAmwvv3tKsFOFf9P9m/6MWlmtB8SspgxqpWKYnELb/lXkyXm7P4sMf3e
System.out.println("加密前:" + content); System.out.println("加密密钥和解密密钥:" + KEY); String encrypt = encrypt(content, KEY);
System.out.println(encrypt.length()+":加密后:" + encrypt); String decrypt = decrypt(encrypt, KEY);
System.out.println("解密后:" + decrypt); }
/* *//**
* 加密
* @method encrypt
* @param content 需要加密的内容
* @param password 加密密码
* @return
* @throws
* @since v1.0
*//*
public static String encrypt(String content){
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(KEY.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return parseByte2HexStr(result);// 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
} *//**
* 加密
* @method encrypt
* @param content 需要加密的内容
* @param password 加密密码
* @return
* @throws
* @since v1.0
*//*
public static String encrypt(String content, String password){
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return parseByte2HexStr(result);// 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
} *//**
* 解密
* @method decrypt
* @param content 待解密内容
* @param password 解密密钥
* @return
* @throws
* @since v1.0
*//*
public static String decrypt(String content, String password){
try {
byte[] param = parseHexStr2Byte(content);
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(param);
return new String(result); // 解密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (BadPaddingException e) {
e.printStackTrace();
} return null;
} *//**
* 解密
* @method decrypt
* @param content 待解密内容
* @param password 解密密钥
* @return
* @throws
* @since v1.0
*//*
public static String decrypt(String content){
try {
byte[] param = Base64.decodeBase64(parseHexStr2Byte(content)); KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(KEY.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 创建密码器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(param);
return new String(result); // 解密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}catch (NoSuchPaddingException e) {
e.printStackTrace();
}catch (InvalidKeyException e) {
e.printStackTrace();
}catch (IllegalBlockSizeException e) {
e.printStackTrace();
}catch (BadPaddingException e) {
e.printStackTrace();
} return null;
} *//**
* 将二进制转换成16进制
* @method parseByte2HexStr
* @param buf
* @return
* @throws
* @since v1.0
*//*
public static String parseByte2HexStr(byte buf[]){
StringBuffer sb = new StringBuffer();
for(int i = 0; i < buf.length; i++){
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
} *//**
* 将16进制转换为二进制
* @method parseHexStr2Byte
* @param hexStr
* @return
* @throws
* @since v1.0
*//*
public static byte[] parseHexStr2Byte(String hexStr){
if(hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
} *//**
* 另外一种加密方式--这种加密方式有两种限制
* 1、密钥必须是16位的
* 2、待加密内容的长度必须是16的倍数,如果不是16的倍数,就会出如下异常
* javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
要解决如上异常,可以通过补全传入加密内容等方式进行避免。
* @method encrypt2
* @param content 需要加密的内容
* @param password 加密密码
* @return
* @throws
* @since v1.0
*//*
public static byte[] encrypt2(String content, String password){
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}*/
}
js链接地址:https://pan.baidu.com/s/1MtmtRxrIVQsBw9EpZsTAyQ 密码:aax3
这个地址也行:https://github.com/sytelus/CryptoJS/tree/master/components
AES前后端加密的更多相关文章
- 微信小程序aes前后端加密解密交互
aes前后端加密解密交互 小程序端 1. 首先引入aes.js /** * [description] CryptoJS v3.1.2 * [description] zhuangzhudada so ...
- 谈谈《Dotnet core结合jquery的前后端加密解密密码密文传输的实现》一文中后端解密失败的原因
详情请看<Dotnet core结合jquery的前后端加密解密密码密文传输的实现>,正常来讲,这个博客里面的代码是没有问题的,但是我有时候却会直接报错,原因是后台解密失败:Interna ...
- java前后端加密(转载)
最近做一个项目的安全渗透测评,测评人员发来一份测试报告,报告明确提出不允许明文参数传输,因为数据在传输的过程中可能被拦截,被监听,所以在传输数据的时候使用数据的原始内容进行传输的话,安全隐患是非常大的 ...
- Dotnet core结合jquery的前后端加密解密密码密文传输的实现
在一个正常的项目中,登录注册的密码是密文传输到后台服务端的,也就是说,首先前端js对密码做处理,随后再传递到服务端,服务端解密再加密传出到数据库里面.Dotnet已经提供了RSA算法的加解密类库,我们 ...
- 结合jquery的前后端加密解密 适用于WebApi的SQL注入过滤器 Web.config中customErrors异常信息配置 ife2018 零基础学院 day 4 ife2018 零基础学院 day 3 ife 零基础学院 day 2 ife 零基础学院 day 1 - 我为什么想学前端
在一个正常的项目中,登录注册的密码是密文传输到后台服务端的,也就是说,首先前端js对密码做处理,随后再传递到服务端,服务端解密再加密传出到数据库里面.Dotnet已经提供了RSA算法的加解密类库,我们 ...
- python前后端加密方式
后端加密方法: python后端加密方式: # 双重工加密 #bytes((7788).encode('utf-8')):为后端加密二把手,多加的锁,该参数可为空,必须加bytes才能实现 md5pa ...
- 16: vue + crypto-js + python前后端加密解密
1.1 vue中使用crypto-js进行AES加密解密 参考博客:https://www.cnblogs.com/qixidi/p/10137935.html 1.初始化vue项目 vue i ...
- 学习加密(四)spring boot 使用RSA+AES混合加密,前后端传递参数加解密
学习加密(四)spring boot 使用RSA+AES混合加密,前后端传递参数加解密 技术标签: RSA AES RSA AES 混合加密 整合 前言: 为了提高安全性采用了RS ...
- 前后端登录注册之node剖析与token的使用状态
登录模块功能详解 1.用户名密码的格式验证 由前端完成,根据需求自行决定,不加叙述 2.点击提交按钮思路详解 前端将用户名 以及加密后的密码还有验证码输入的内容统一发给后端 由后端和数据库的数据进行 ...
随机推荐
- python os模块一些常用操作
os.getcwd() ## 获取当前路径 os.chdir("dirpath") ## 改变目录 os.makedirs("dirname") ## 递归创建 ...
- JavaScript校验网址
JavaScript校验网址 var linkUrl = 'https://www.baidu.com' if( typeof (linkUrl) != undefined && li ...
- 索引原理-btree索引与hash索引的区别
btree索引与hash索引的区别,之前不清楚,mark一下. Hash索引结构的特殊性,其检索效率非常高,索引的检索可以一次定位,不像B-Tree索引需要从根节点到枝节点,最后才能访问到页节点这样多 ...
- 20145214 《Java程序设计》第3周学习总结
教材学习内容总结 对象(Object):存在的具体实体,具有明确的状态和行为 类(Class):具有相同属性和行为的一组对象的集合,用于组合各个对象所共有操作和属性的一种机制 从类看对象:类定义可以视 ...
- MySQL_解决ERROR 2006 (HY000) at line XX MySQL server has gone away问题
参考:http://www.111cn.net/database/mysql/106911.htm 1.修改mysqld的配置文件my.cnf 调整max_allowed_packet的值,修改为5M ...
- JDK、J2EE、J2SE、J2ME的区别
JDK.J2EE.J2SE.J2ME的区别 你对JDK.J2EE.J2SE.J2ME概念是否了解,这里和大家分享一下JDK.J2EE.J2SE.J2ME的概念以及他们的关系区别,相信本文介绍一定会让你 ...
- 异步:asyncio和aiohttp的一些应用(1)
1. asyncio 1.1asyncio/await 用法 async/await 是 python3.5中新加入的特性, 将异步从原来的yield 写法中解放出来,变得更加直观. 在3.5之前,如 ...
- 爬虫框架Scrapy之Request/Response
Request yield scrapy.Request(url, self.parse) Request 源码: # 部分代码 class Request(object_ref): def __in ...
- jQuery实现输入框提示,当获取焦点时提示消失,当失去焦点时内容为空则显示提示,否则保留输入信息
首先看效果 默认状态下 获取焦点状态下 什么也没输入,离开 有输入离开 输入默认值离开 代码 <!DOCTYPE html> <html> <head> <m ...
- Python学习札记(十八) 高级特性4 生成器
参考:生成器 Note 1.通过列表生成式,我们可以直接创建一个列表.但是,受到内存限制,列表容量肯定是有限的,且容易造成空间浪费.所以,如果列表元素可以按照某种算法推算出来,那我们可以在循环的过程中 ...