des加解密(JavaScript&Java)
阿新 • • 發佈:2019-02-09
前言:剛學h5沒多久,感覺吧比android難多了啊,特別是適配,真尼瑪苦逼啊,不過h5的大牛還是很多的,畢竟這麼多年了,隨便一搜就一大堆,正是因為這樣,今天剛好後臺需要用des對稱加密傳輸資料,然後就上網一搜,真尼瑪一大堆啊,最後找到了一個叫crypto-js的庫,down下來的時候不會用,尼瑪尷尬了,於是就當筆記記下來了,大牛勿噴~!
先附上官方git連結:
看了官網的demo,然後發現了這麼多庫:
我尼瑪只要des加密啊,於是找到這麼一個檔案:
然後照著官方demo敲了一下,發現中文加密解密出來是亂碼,又尷尬了:
結果:
好吧,我已經知道我很水了/苦笑,最後搗騰了半天,終於是搞好了。
全部程式碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- CryptoJS -->
<script src="./core.js"></script>
<script src="./cipher-core.js"></script>
<script src="./tripledes.js" ></script>
<script src="./mode-ecb.js"></script>
<script>
window.onload = function () {
//需要加密的內容
let str1 = encryptByDES('helloworld');
let str2 = decryptByDESModeEBC(str1);
console.log(str1.toString())
console.log(str2)
}
//加密的私鑰
var key = '12345678';
// DES加密
function encryptByDES(message) {
//把私鑰轉換成16進位制的字串
var keyHex = CryptoJS.enc.Utf8.parse(key);
//模式為ECB padding為Pkcs7
var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
//加密出來是一個16進位制的字串
return encrypted.ciphertext.toString();
}
//DES ECB模式解密
function decryptByDESModeEBC(ciphertext) {
//把私鑰轉換成16進位制的字串
var keyHex = CryptoJS.enc.Utf8.parse(key);
//把需要解密的資料從16進位制字串轉換成字元byte陣列
var decrypted = CryptoJS.DES.decrypt({
ciphertext: CryptoJS.enc.Hex.parse(ciphertext)
}, keyHex, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
//以utf-8的形式輸出解密過後內容
var result_value = decrypted.toString(CryptoJS.enc.Utf8);
return result_value;
}
</script>
</head>
<body>
</body>
</html>
好啦!寫到這裡我們要測試一下了,當我們輸入一個:
window.onload = function () {
//需要加密的內容
let str1 = encryptByDES('helloworld');
let str2 = decryptByDESModeEBC(str1);
console.log(str1.toString())
console.log(str2)
}
我們看到控制檯列印結果:
des-test.html:16 a2f0132f740e4262a1d16893aa19126e
des-test.html:17 helloworld
可以看到我們的內容被加密成了一個16進位制字串形式
然後我們java伺服器端怎麼解密呢?
/**
* 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/ECB/NoPadding");
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(hexStr2Bytes(secretData));
return new String(buf,"utf-8");
} catch (Exception e) {
e.printStackTrace();
throw new Exception("IllegalBlockSizeException", e);
}
}
public static byte[] hexStr2Bytes(String src){
/*對輸入值進行規範化整理*/
src = src.trim().replace(" ", "").toUpperCase(Locale.US);
//處理值初始化
int m=0,n=0;
int iLen=src.length()/2; //計算長度
byte[] ret = new byte[iLen]; //分配儲存空間
for (int i = 0; i < iLen; i++){
m=i*2+1;
n=m+1;
ret[i] = (byte)(Integer.decode("0x"+ src.substring(i*2, m) + src.substring(m,n)) & 0xFF);
}
return ret;
}
/**
* 獲得祕密金鑰
*
* @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);
}
因為我們在js端用到加密的時候,加密過後變成了一個16進位制的字串形式,所以我們需要把16進位制的字串轉換成string位元組陣列
byte[] buf = cipher.doFinal(hexStr2Bytes(secretData));
當然,通常我們都是加密出來之後用base64再次加密一次,所以解密的時候得先解出base64,然後再解密。
最後貼上java des加解密的程式碼(跟js加解密方式一樣):
package com.yasin.html5;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Locale;
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;
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 str2HexStr(new String(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/ECB/NoPadding");
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(hexStr2Bytes(secretData));
return new String(buf,"utf-8");
} catch (Exception e) {
e.printStackTrace();
throw new Exception("IllegalBlockSizeException", e);
}
}
public static byte[] hexStr2Bytes(String src){
/*對輸入值進行規範化整理*/
src = src.trim().replace(" ", "").toUpperCase(Locale.US);
//處理值初始化
int m=0,n=0;
int iLen=src.length()/2; //計算長度
byte[] ret = new byte[iLen]; //分配儲存空間
for (int i = 0; i < iLen; i++){
m=i*2+1;
n=m+1;
ret[i] = (byte)(Integer.decode("0x"+ src.substring(i*2, m) + src.substring(m,n)) & 0xFF);
}
return ret;
}
/**
* 獲得祕密金鑰
*
* @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);
}
/**
* 字串轉換成十六進位制字串
* @param str String 待轉換的ASCII字串
* @return String 每個Byte之間空格分隔,如: [61 6C 6B]
*/
private final static char[] mChars = "0123456789ABCDEF".toCharArray();
public static String str2HexStr(String str){
StringBuilder sb = new StringBuilder();
byte[] bs = str.getBytes();
for (int i = 0; i < bs.length; i++){
sb.append(mChars[(bs[i] & 0xFF) >> 4]);
sb.append(mChars[bs[i] & 0x0F]);
sb.append(' ');
}
return sb.toString().trim();
}
static 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 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 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;
}
}
}
最後,本篇純屬個人筆記,大牛勿噴~!!!!