js前端加密 //引入js依赖//js 加密解密var data = "888888";var srcs = CryptoJS.enc.Utf8.parse(data); //key是页面加载的时候由服务器端生成的,用隐藏域保存。var key = CryptoJS.enc.Utf8.parse('o7H8uIM2O5qv65l2')
//引入js依赖
//js 加密解密
var data = "888888";
var srcs = CryptoJS.enc.Utf8.parse(data); //key是页面加载的时候由服务器端生成的,用隐藏域保存。
var key = CryptoJS.enc.Utf8.parse('o7H8uIM2O5qv65l2');//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
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});
return 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();
}
//java 后台加密解密 key是页面加载的时候由服务器端生成的,用隐藏域保存。
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
public class EncryptUtil {
private static final String KEY = "abcdefgabcdefg12";
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
public static String base64Encode(byte[] bytes){
return Base64.encodeBase64String(bytes);
}
public static byte[] base64Decode(String base64Code) throws Exception{
return new BASE64Decoder().decodeBuffer(base64Code);
}
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
return cipher.doFinal(content.getBytes("utf-8"));
}
public static String aesEncrypt(String content, String encryptKey) throws Exception {
return base64Encode(aesEncryptToBytes(content, encryptKey));
}
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
return aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
}
/**
* 测试
*
*/
public static void main(String[] args) throws Exception {
String content = "Test String么么哒"; //0gqIDaFNAAmwvv3tKsFOFf9P9m/6MWlmtB8SspgxqpWKYnELb/lXkyXm7P4sMf3e
System.out.println("加密前:" + content);
System.out.println("加密密钥和解密密钥:" + KEY);
String encrypt = aesEncrypt(content, KEY);
System.out.println(encrypt.length()+":加密后:" + encrypt);
String decrypt = aesDecrypt(encrypt, KEY);
System.out.println("解密后:" + decrypt);
}
}
java验证码生成 使用以及登入
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
/**
* 验证码生成器
*
*/
public class ValidateCode {
// 图片的宽度。
private int width = 160;
// 图片的高度。
private int height = 28;
// 验证码字符个数
private int codeCount = 4;
// 验证码干扰线数
private int lineCount = 150;
// 验证码
private String code = null;
// 验证码图片Buffer
private BufferedImage buffImg = null;
private char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
public ValidateCode() {
this.createCode();
}
/**
*
* @param width
* 图片宽
* @param height
* 图片高
*/
public ValidateCode(int width, int height) {
this.width = width;
this.height = height;
this.createCode();
}
/**
*
* @param width
* 图片宽
* @param height
* 图片高
* @param codeCount
* 字符个数
* @param lineCount
* 干扰线条数
*/
public ValidateCode(int width, int height, int codeCount, int lineCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
this.createCode();
}
public void createCode() {
int x = 0, fontHeight = 0, codeY = 0;
int red = 0, green = 0, blue = 0;
x = width / (codeCount + 2);// 每个字符的宽度
fontHeight = height - 2;// 字体的高度
codeY = height - 4;
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = buffImg.createGraphics();
// 生成随机数
Random random = new Random();
// 将图像填充为白色
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height);
// 创建字体
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
g.setFont(font);
//干扰线
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width / 8);
int ye = ys + random.nextInt(height / 8);
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(new Color(red, green, blue));
g.drawLine(xs, ys, xe, ye);
}
// randomCode记录随机产生的验证码
StringBuffer randomCode = new StringBuffer();
// 随机产生codeCount个字符的验证码。
for (int i = 0; i < codeCount; i++) {
String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
red = random.nextInt(255);
green = random.nextInt(255);
blue = random.nextInt(255);
g.setColor(new Color(red, green, blue));
g.drawString(strRand, (i + 1) * x, codeY);
// 将产生的四个随机数组合在一起。
randomCode.append(strRand);
}
// 将四位数字的验证码保存到Session中。
code = randomCode.toString();
}
public void write(String path) throws IOException {
OutputStream sos = new FileOutputStream(path);
this.write(sos);
}
public void write(OutputStream sos) throws IOException {
ImageIO.write(buffImg, "png", sos);
sos.close();
}
public BufferedImage getBuffImg() {
return buffImg;
}
public String getCode() {
return code;
}
}
//控制器使用验证码
@RequestMapping("/getCode.do")
public void getCode(HttpServletRequest reqeust, HttpServletResponse response) throws IOException {
response.setContentType("image/jpeg");
// 禁止图像缓存。
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
HttpSession session = reqeust.getSession();
ValidateCode vCode = new ValidateCode(100, 28, 4, 100);
session.setAttribute(Helper.SESSION_CHECKCODE, vCode.getCode());
vCode.write(response.getOutputStream());
}
//login.html 登入界面代码 前端AES加密传输后端解密以及n次输入验证不通过后需要验证码
//java 控制器 在请求登录页面时需要后端生成一个随机的16位字符串的key,用于前后端加密解密用,该key在登录成功后销毁,存储在session中
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(){
//生成login_token
session.setAttribute(Helper.SESSION_LOGIN_TOKEN,RandomUtil.generateString(16));//登录令牌,用于密码加密的key,16位长度
if(session.getAttribute(Helper.SESSION_USER) == null){
return "login";
}
else
return "redirect:/";
}
表单请求(应为为了安全 所以使用加密解密)
@RequestMapping(value = "/signIn", method = RequestMethod.POST,produces = "text/html;charset=UTF-8")
@ResponseBody
public String signIn(String username,String password,boolean remember,String checkCode) throws AuthorizationException{
System.out.println(username+","+password+","+remember+","+checkCode);
Object token = session.getAttribute(Helper.SESSION_LOGIN_TOKEN);//原始令牌
if(token==null) return JSON.toJSONString(new Result(false,"timeout"));//登录成功后token失效,则页面失效,客户端需要重定向到主界面
Object countObj = session.getAttribute(Helper.SESSION_LOGIN_FAILURE_COUNT);
int count = countObj==null?ConfigInfo.login_failure_count:Integer.parseInt(countObj.toString());
System.out.println("剩余次数:"+count);
//验证码逻辑
if(count<=0){//需要验证码
Object oldCode = session.getAttribute(Helper.SESSION_CHECKCODE);
if(checkCode==null||oldCode==null){//该登录界面没有验证码字段,但是已经消耗掉了剩余次数,说明该页面是过期页面,需要重新登录
return JSON.toJSONString(new Result(false,"timeout"));//客户端需要重定向到主界面
}
if(checkCode.trim().isEmpty()) return JSON.toJSONString(new Result(false,"请输入验证码"));
if(oldCode.toString().equalsIgnoreCase(checkCode)){
//验证通过,可信客户端,给两次剩余次数
count=2;
session.setAttribute(Helper.SESSION_LOGIN_FAILURE_COUNT,2);
}else{
return JSON.toJSONString(new Result(false,"codeError"));//验证码不正确,客户端需要刷新验证码
}
}
//解密
try {
password = EncryptUtil.aesDecrypt(password,token.toString());//解密后
System.out.println("Decrypt:"+password);
} catch (Exception e) {
e.printStackTrace();
return JSON.toJSONString(new Result(false,"timeout"));//客户端需要重定向到主界面
}
//登录校验
String key = RandomUtil.generateString(16);//重新生成登录令牌,任何登录失败的操作都需要更新登录令牌
ViewSysUser user = sysUserService.selectUserPwd(username,password);
if(user == null){
session.setAttribute(Helper.SESSION_LOGIN_TOKEN,key);
session.setAttribute(Helper.SESSION_LOGIN_FAILURE_COUNT,--count);//剩余次数-1
if(count<=0) return JSON.toJSONString(new Result(false,"checkCode"));//客户端需要重定向到登录界面将验证码显示出来
return JSON.toJSONString(new Result(false,"用户名或密码错误!",key));
}else{
if(user.getUserid()!=ConfigInfo.admin_id && !user.getuStatus().equals(ConfigInfo.user_status_normal)) {
session.setAttribute(Helper.SESSION_LOGIN_TOKEN,key);
return JSON.toJSONString(new Result(false,"登录失败,该账号已被禁止使用!",key));
}
//登录成功
session.removeAttribute(Helper.SESSION_LOGIN_TOKEN);
session.removeAttribute(Helper.SESSION_LOGIN_FAILURE_COUNT);
loginUser = user;
session.setAttribute(Helper.SESSION_USER,loginUser);
sysEventService.insertEventLog(Helper.logTypeSecurity,username+" 登录系统");
return JSON.toJSONString(new Result(true,"登录成功!"));
}
}
生成随机数据
import java.util.Random;
public class RandomUtil {
public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String LETTERCHAR = "abcdefghijkllmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String NUMBERCHAR = "0123456789";
/**
* 返回一个定长的随机字符串(只包含大小写字母、数字)
*
* @param length
* 随机字符串长度
* @return 随机字符串
*/
public static String generateString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(ALLCHAR.charAt(random.nextInt(ALLCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的随机纯字母字符串(只包含大小写字母)
*
* @param length
* 随机字符串长度
* @return 随机字符串
*/
public static String generateMixString(int length) {
StringBuffer sb = new StringBuffer();
Random random = new Random();
for (int i = 0; i < length; i++) {
sb.append(LETTERCHAR.charAt(random.nextInt(LETTERCHAR.length())));
}
return sb.toString();
}
/**
* 返回一个定长的随机纯大写字母字符串(只包含大小写字母)
*
* @param length
* 随机字符串长度
* @return 随机字符串
*/
public static String generateLowerString(int length) {
return generateMixString(length).toLowerCase();
}
/**
* 返回一个定长的随机纯小写字母字符串(只包含大小写字母)
*
* @param length
* 随机字符串长度
* @return 随机字符串
*/
public static String generateUpperString(int length) {
return generateMixString(length).toUpperCase();
}
/**
* 生成一个定长的纯0字符串
*
* @param length
* 字符串长度
* @return 纯0字符串
*/
public static String generateZeroString(int length) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append('0');
}
return sb.toString();
}
/**
* 根据数字生成一个定长的字符串,长度不够前面补0
*
* @param num
* 数字
* @param fixdlenth
* 字符串长度
* @return 定长的字符串
*/
public static String toFixdLengthString(long num, int fixdlenth) {
StringBuffer sb = new StringBuffer();
String strNum = String.valueOf(num);
if (fixdlenth - strNum.length() >= 0) {
sb.append(generateZeroString(fixdlenth - strNum.length()));
} else {
throw new RuntimeException("将数字" + num + "转化为长度为" + fixdlenth
+ "的字符串发生异常!");
}
sb.append(strNum);
return sb.toString();
}
/**
* 每次生成的len位数都不相同
*
* @param param
* @return 定长的数字
*/
public static int getNotSimple(int[] param, int len) {
Random rand = new Random();
for (int i = param.length; i > 1; i--) {
int index = rand.nextInt(i);
int tmp = param[index];
param[index] = param[i - 1];
param[i - 1] = tmp;
}
int result = 0;
for (int i = 0; i < len; i++) {
result = result * 10 + param[i];
}
return result;
}
}
brix-crypto-js-3.1.9-1-0js各种加密.zip
brix-crypto-js-3.1.9-1-0js各种加密.zip
获取url 后面的数据
function getAllUrlParams(url) {
// get query string from url (optional) or window
var queryString = url ? url.split('?')[1] : window.location.search.slice(1);
// we'll store the parameters here
var obj = {};
// if query string exists
if (queryString) {
// stuff after # is not part of query string, so get rid of it
queryString = queryString.split('#')[0];
// split our query string into its component parts
var arr = queryString.split('&');
for (var i = 0; i < arr.length; i++) {
// separate the keys and the values
var a = arr[i].split('=');
// in case params look like: list[]=thing1&list[]=thing2
var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function (v) {
paramNum = v.slice(1, -1);
return '';
});
// set parameter value (use 'true' if empty)
var paramValue = typeof (a[1]) === 'undefined' ? true : a[1];
// if parameter name already exists
if (obj[paramName]) {
// convert value to array (if still string)
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
// if no array index number specified...
if (typeof paramNum === 'undefined') {
// put the value on the end of the array
obj[paramName].push(paramValue);
}
// if array index number specified...
else {
// put the value at that index number
obj[paramName][paramNum] = paramValue;
}
}
// if param name doesn't exist yet, set it
else {
obj[paramName] = paramValue;
}
}
}
return obj;
};
var x = getAllUrlParams('http://127.0.0.1:5000/app/index.html?code=KXMvRUkC92WaJ6n3vELMU3iK2128879&state=').code;
console.log(x);
自定义 js base64加密和后台解密
1.前台javascript
1.在提交的js中这样写
document.form1.username.value=encode64(document.form1.username.value);
document.form1.password.value=encode64(document.form1.password.value);
document.form1.submit();
2.加密js这样写
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;
}
2.后台java代码这样写,比如
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 };
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();
}
2.解密示例:
public final String getUsername() {
//logger.info( "解密前的用户名是 : " + this.username );
decodeusername = decode(this.username);
String decodeuser = new String(decodeusername);
//logger.info( "解密后的用户名是 : " + decodeuser );
return decodeuser;
}
public final String getPassword() {
//logger.info( "解密前密码是 : " + this.password );
decodepassword = decode(this.password);
String decodepass = new String(decodepassword);
//logger.info( "解密后密码是 : " + decodepass );
return decodepass;
}
使用des加密
DES算法 java 后台解密---------------工具类 import org.apache.commons.io.IOUtils; import org.apache.tomcat.util.codec.binary.Base64; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.security.SecureRandom; /** **
* * @author KeepGo Lamar * @email lamar_7950@hotmail.com * @date 2017/4/13 */ public class DesCrypt { private String KEY = "password111111"; private String CODE_TYPE = "UTF-8"; /** * DES加密 * @param datasource * @return */ public String encode(String datasource){ try{ SecureRandom random = new SecureRandom(); DESKeySpec desKey = new DESKeySpec(KEY.getBytes(CODE_TYPE)); //创建一个密匙工厂,然后用它把DESKeySpec转换成 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey securekey = keyFactory.generateSecret(desKey); //Cipher对象实际完成加密操作 Cipher cipher = Cipher.getInstance("DES"); //用密匙初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, random); //现在,获取数据并加密 byte[] temp = Base64.encodeBase64(cipher.doFinal(datasource.getBytes())); return IOUtils.toString(temp,"UTF-8"); }catch(Throwable e){ e.printStackTrace(); return null; } } /** * DES解密 * @return */ public String decode(String src) throws Exception { // DES算法要求有一个可信任的随机数源 SecureRandom random = new SecureRandom(); // 创建一个DESKeySpec对象 DESKeySpec desKey = new DESKeySpec(KEY.getBytes(CODE_TYPE)); // 创建一个密匙工厂 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // 将DESKeySpec对象转换成SecretKey对象 SecretKey securekey = keyFactory.generateSecret(desKey); // Cipher对象实际完成解密操作 Cipher cipher = Cipher.getInstance("DES"); // 用密匙初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, random); // 真正开始解密操作 return IOUtils.toString(cipher.doFinal(Base64.decodeBase64(src)),"UTF-8"); } public String getKEY() { return KEY; } public void setKEY(String KEY) { this.KEY = KEY; } } ---------------------------请求 @RequestMapping(value = "/decrypt",method = RequestMethod.POST) @ResponseBody public String decrypt(@RequestParam("text") String text,@RequestParam("key") String key) throws Exception { DesCrypt crypt = new DesCrypt(); crypt.setKEY(key); return crypt.decode(text); }
