同样密码每次生成一样加密结果
前端页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function(){
$(function() {
$("#btn").click(function() {
var username = encode64($("#username").val()); //对数据加密
var password = encode64($("#password").val());
alert(username);
alert(password);
$("#username").val(username);
$("#password").val(password);
document.fm.submit(); //fm为form表单name
})
})
// base64加密开始
var keyStr = "ABCDEFGHIJKLMNOP" + "QRSTUVWXYZabcdef" + "ghijklmnopqrstuv"
+ "wxyz0123456789+/" + "=";
function encode64(input) {
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
do {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)
+ keyStr.charAt(enc3) + keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
return output;
}
// base64加密结束
})
</script>
</head>
<body>
<a href="index2">跳转到index2</a>
<form action="testBase64" name="fm">
<input type="text" name="username" id="username"/>
<input type="password" name="password" id="password" />
<button id="btn">0000</button>
</form>
</body>
</html>
后端代码
@RequestMapping("/testBase64")
public void aas(String username,String password) throws SQLException {
System.out.println("解密前username:"+username);
System.out.println("解密前password:"+password);
System.out.println("解密后username:"+new String(Base64Utils.decode(username)));
System.out.println("解密后password:"+new String(Base64Utils.decode(password)));
}
解密类代码
public class Base64Utils {
private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/', };
private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,
-1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
-1, -1 };
/**
* 解密
* @param str
* @return
*/
public static byte[] decode(String str) {
byte[] data = str.getBytes();
int len = data.length;
ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
int i = 0;
int b1, b2, b3, b4;
while (i < len) {
do {
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1) {
break;
}
do {
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1) {
break;
}
buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
do {
b3 = data[i++];
if (b3 == 61) {
return buf.toByteArray();
}
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1) {
break;
}
buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
do {
b4 = data[i++];
if (b4 == 61) {
return buf.toByteArray();
}
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1) {
break;
}
buf.write((int) (((b3 & 0x03) << 6) | b4));
}
return buf.toByteArray();
}
}
结果
同样密码每次生成不一样加密结果
来源:https://www.cnblogs.com/seanRay/p/15336332.html
前端
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
<script type="text/javascript">
$(function() {
$("#btn").click(function() {
//动态从后端获取加密用的key
var $key = "";
$.ajax({
type: "post",
async: false,
url: "http://127.0.0.1:8081/test/key",
success: function(result) {
console.log(result);
$key = result;
}
})
//获取输入的用户名和密码
var username = $("#username").val();
var $password = $("#password").val();
console.log("加密前:name:"+username+",pwd:"+$password);
//将字符串转换成utf-8编码格式的WordArray对象
var key = CryptoJS.enc.Utf8.parse($key);
console.log("key:" + key + ",$key:" + $key);
var password = CryptoJS.enc.Utf8.parse($password);
//使用AES加密算法对其进行加密。加密过程中使用了key作为密钥,采用ECB模式和Pkcs7填充方式
var encrypted = CryptoJS.AES.encrypt(password, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
//加密后转为字符串
var encryptedPwd = encrypted.toString();
console.log("对密码加密:" + encrypted);
console.log("加密后转为字符串:" + encryptedPwd);
//对加密结果进行解密
var decrypt = CryptoJS.AES.decrypt(encryptedPwd, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
//解密结果转为字符串
var testDecryptStr = CryptoJS.enc.Utf8.stringify(decrypt).toString();
console.log("解密:" + decrypt);
console.log("解密结果字符串:" + testDecryptStr);
//发送请求到后端
var requestBody = {
name: username,
pwd: encryptedPwd, //加密后的密码
key: $key //加密用的key
};
$.ajax({
"url": "http://127.0.0.1:8081/test/test1",
"type": "post",
"data": requestBody,
"dataType": "json",
"success": function(response) {
console.log("请求成功,解密结果:"+response.data);
},
"error": function(response) {
}
});
console.log("----------------------");
})
})
</script>
</head>
<body>
<a href="index2">跳转到index2</a>
<form action="" name="fm">
<input type="text" name="username" id="username" />
<input type="password" name="password" id="password" />
<button type="button" id="btn">发送请求</button>
</form>
</body>
</html>
后端
加解密工具类
package com.wzw.config.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AesUtils {
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
/**
* 加密
* @param content 要加密的内容
* @param key 加密用的key
* @return 加密后的值
*/
public static String encrypt(String content, String key) {
try {
//获得密码的字节数组
byte[] raw = key.getBytes();
//根据密码生成AES密钥
SecretKeySpec skey = new SecretKeySpec(raw, "AES");
//根据指定算法ALGORITHM自成密码器
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
//初始化密码器,第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二个参数为生成的AES密钥
cipher.init(Cipher.ENCRYPT_MODE, skey);
//获取加密内容的字节数组(设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte [] byte_content = content.getBytes("utf-8");
//密码器加密数据
byte [] encode_content = cipher.doFinal(byte_content);
//将加密后的数据转换为字符串返回
return Base64.encodeBase64String(encode_content);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 解密
* @param encryptStr 加密后密码
* @param decryptKey 加密的key
* @return 解密值
*/
public static String decrypt(String encryptStr, String decryptKey) {
try {
//获得密码的字节数组
byte[] raw = decryptKey.getBytes();
//根据密码生成AES密钥
SecretKeySpec skey = new SecretKeySpec(raw, "AES");
//根据指定算法ALGORITHM自成密码器
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
//初始化密码器,第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作,第二个参数为生成的AES密钥
cipher.init(Cipher.DECRYPT_MODE, skey);
//把密文字符串转回密文字节数组
byte [] encode_content = Base64.decodeBase64(encryptStr);
//密码器解密数据
byte [] byte_content = cipher.doFinal(encode_content);
//将解密后的数据转换为字符串返回
return new String(byte_content,"utf-8");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
controller
import cn.hutool.core.util.RandomUtil;
import com.wzw.base.pojo.Result;
import com.wzw.base.pojo.User;
import com.wzw.config.utils.AesUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping("/test1")
@ResponseBody
public Result test1(User user,String key) throws Exception {
String s = AesUtils.decrypt(user.getPwd(), key);
System.out.println(s);
Result ok = Result.ok();
ok.setData(s);
return ok;
}
@RequestMapping("/key")
@ResponseBody
private String create16String()
{
return RandomUtil.randomString(16);
}
}
结果
加密结果不一样,但是解密结果一样