實現了前端對數據進行加密後傳輸,後端對加密的數據進行解密,而後去數據庫對比。由於要解密因此採用對稱加密算法。不討論哪一個對稱加密算法好,這裏採用DES,在實現的過程當中發現要找一個js版本的DES加密,而且java能DES解密的還真不容易。
加解密思路
因爲是對稱加密,因此加解密的密鑰就很是重要。這裏採用uuid做爲加解密的密鑰,並且每次請求頁面時生成的uuid都不同,保證每次的密鑰都不知道是什麼。
看後端生成密鑰的過程
@RequestMapping(value = "/login.html", method = RequestMethod.GET)
public String login(Model model, HttpSession session) {
logger.info("登陸頁面");
session.setAttribute(SessionParam.LOGIN_KEY, UUIDGenerator.getUUID());
model.addAttribute("title", "用戶登陸");
return "admin/login";
}
在進入login頁面的時候將生成的uuid放進session中。
// 密碼進行兩次md5
var passwordMd5 = CryptoJS.MD5(password);
passwordMd5 = CryptoJS.MD5(passwordMd5);
// console.info("md5:" + passwordMd5);
$(this).val("正在登陸...");
$(this).attr("disabled", true);
// 用戶名des加密
username = encryptByDES(username, key);
// 填充表單並提交表單
$("#postUsername").val(username);
$('#postPassword').val(passwordMd5);
$('#postForm').submit();
// DES加密
function encryptByDES(message, key) {
var keyHex = CryptoJS.enc.Utf8.parse(key);
var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode : CryptoJS.mode.ECB,
padding : CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}
當表單準備好以後,對密碼進行兩次MD5,用戶名則採用DES加密,加密的密鑰就是session中保存的那個uuid
後端再對傳過來的用戶名進行解密,由於數據庫原本就存的是密碼的兩次MD5的值,因此只對用戶名進行加密,由於即便密碼被獲取到,也不知道是什麼。
後端過程
// 獲得加密密鑰
logger.info("-----原始數據:username:{} password:{}-----", username, password);
String key = session.getAttribute(SessionParam.LOGIN_KEY) + "";
logger.info("-----加解密key:{}-----", key);
try {
username = DESUtil.decryption(username, key);
} catch (Exception e) {
logger.info("-----解密出錯:{}-----", e.getMessage());
}
logger.info("解密後:username:{} password:{}", username, password);
截圖
html
JAVA DES
分享一個js前端加密,java後端加密的小程序
package com.jrbac.util;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
/**
* DES加解密工具類
*
* @author 程高偉
*
* @date 2016年6月15日 上午10:02:50
*/
public class DESUtil {
private static final String DES_ALGORITHM = "DES";
/**
* DES加密
*
* @param plainData
* 原始字符串
* @param secretKey
* 加密密鑰
* @return 加密後的字符串
* @throws Exception
*/
public static String encryption(String plainData, String secretKey) throws Exception {
Cipher cipher = null;
try {
cipher = Cipher.getInstance(DES_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, generateKey(secretKey));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
}
try {
// 爲了防止解密時報javax.crypto.IllegalBlockSizeException: Input length must
// be multiple of 8 when decrypting with padded cipher異常,
// 不能把加密後的字節數組直接轉換成字符串
byte[] buf = cipher.doFinal(plainData.getBytes());
return Base64Utils.encode(buf);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
throw new Exception("IllegalBlockSizeException", e);
} catch (BadPaddingException e) {
e.printStackTrace();
throw new Exception("BadPaddingException", e);
}
}
/**
* DES解密
*
* @param secretData
* 密碼字符串
* @param secretKey
* 解密密鑰
* @return 原始字符串
* @throws Exception
*/
public static String decryption(String secretData, String secretKey) throws Exception {
Cipher cipher = null;
try {
cipher = Cipher.getInstance(DES_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, generateKey(secretKey));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new Exception("NoSuchAlgorithmException", e);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
throw new Exception("NoSuchPaddingException", e);
} catch (InvalidKeyException e) {
e.printStackTrace();
throw new Exception("InvalidKeyException", e);
}
try {
byte[] buf = cipher.doFinal(Base64Utils.decode(secretData.toCharArray()));
return new String(buf);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
throw new Exception("IllegalBlockSizeException", e);
} catch (BadPaddingException e) {
e.printStackTrace();
throw new Exception("BadPaddingException", e);
}
}
/**
* 得到祕密密鑰
*
* @param secretKey
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws InvalidKeyException
*/
private static SecretKey generateKey(String secretKey)
throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES_ALGORITHM);
DESKeySpec keySpec = new DESKeySpec(secretKey.getBytes());
keyFactory.generateSecret(keySpec);
return keyFactory.generateSecret(keySpec);
}
static private class Base64Utils {
static private char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
.toCharArray();
static private byte[] codes = new byte[256];
static {
for (int i = 0; i < 256; i++)
codes[i] = -1;
for (int i = 'A'; i <= 'Z'; i++)
codes[i] = (byte) (i - 'A');
for (int i = 'a'; i <= 'z'; i++)
codes[i] = (byte) (26 + i - 'a');
for (int i = '0'; i <= '9'; i++)
codes[i] = (byte) (52 + i - '0');
codes['+'] = 62;
codes['/'] = 63;
}
/**
* 將原始數據編碼爲base64編碼
*/
static private String encode(byte[] data) {
char[] out = new char[((data.length + 2) / 3) * 4];
for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
boolean quad = false;
boolean trip = false;
int val = (0xFF & (int) data[i]);
val <<= 8;
if ((i + 1) < data.length) {
val |= (0xFF & (int) data[i + 1]);
trip = true;
}
val <<= 8;
if ((i + 2) < data.length) {
val |= (0xFF & (int) data[i + 2]);
quad = true;
}
out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
val >>= 6;
out[index + 1] = alphabet[val & 0x3F];
val >>= 6;
out[index + 0] = alphabet[val & 0x3F];
}
return new String(out);
}
/**
* 將base64編碼的數據解碼成原始數據
*/
static private byte[] decode(char[] data) {
int len = ((data.length + 3) / 4) * 3;
if (data.length > 0 && data[data.length - 1] == '=')
--len;
if (data.length > 1 && data[data.length - 2] == '=')
--len;
byte[] out = new byte[len];
int shift = 0;
int accum = 0;
int index = 0;
for (int ix = 0; ix < data.length; ix++) {
int value = codes[data[ix] & 0xFF];
if (value >= 0) {
accum <<= 6;
shift += 6;
accum |= value;
if (shift >= 8) {
shift -= 8;
out[index++] = (byte) ((accum >> shift) & 0xff);
}
}
}
if (index != out.length)
throw new Error("miscalculated data length!");
return out;
}
}
}
CryptoJS DES和MD5
!前端