前後端實現AES加解密(一):java後端實現
阿新 • • 發佈:2019-01-27
首先需要匯入一個第三方jsr包,commons-codec.jar
下面是一個寫好的工具類,呼叫該類的方法,實現使用指定金鑰對明文進行加解密:
package util;
import java.io.UnsupportedEncodingException;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AesUtil {
//byte陣列轉字串
public static String byteToString(byte[] byte1)
throws UnsupportedEncodingException {
return new String(byte1);
}
//加密時呼叫方法,三個引數分別是:明文,金鑰,向量,注意向量的長度只能是16byte,而且加密解密時必須使用一致的向量。
public static byte[] AES_CBC_Encrypt(byte[] content, byte[] keyBytes,
byte [] iv) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
//解密方法,三個引數:密文,金鑰,向量
public static byte[] AES_CBC_Decrypt(byte[] content, byte[] keyBytes,
byte[] iv) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
// TODO Auto-generated catchblock
System.out.println("exception:" + e.toString());
}
return null;
}
/**
*將base64型別的字串轉成byte型別
* @param key
* @return
* @throws Exception
*/
public static byte[] decryptBASE64(String key) throws Exception {
return Base64.decodeBase64(key.getBytes());
}
/**
* 將byte型別轉變為base64型別的字串
* @param key
* @return
* @throws Exception
*/
public static String encryptBASE64(byte[] key) throws Exception {
return new String(Base64.encodeBase64(key));
}
/**
* 這個方法在大多數時候是用不到的,可以選擇無視。
* @param src byte陣列
* @return 十六進位制的字串
*/
public static String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* 字串轉二進位制字串
*
* @param str
*/
public String toBinary(String str) {
char[] strChar = str.toCharArray();
String result = "";
for (int i = 0; i < strChar.length; i++) {
result += Integer.toBinaryString(strChar[i]) + "";
}
return result;
}
/**
* 字串轉16進位制字串
* @param s
* @return
*/
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
/**
* 得到一個任意長度隨即金鑰
* @param KeyLength
* @return
*/
public static String KeyCreate(int KeyLength) {
String base = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
Random random = new Random();
StringBuffer Keysb = new StringBuffer();
for (int i = 0; i < KeyLength; i++) // 生成指定位數的隨機祕鑰字串
{
int number = random.nextInt(base.length());
Keysb.append(base.charAt(number));
}
return Keysb.toString();
}
}
直接將上面的工具類複製到專案中,下面demo用來演示加密解密過程:
//明文
String returnMessageContent = "癥結所在";
//aes的key值
String key = AesUtil.KeyCreate(16);
//注意第一個引數-明文轉化為byte陣列的時候,一定要指定是按照utf-8的格式進行轉化的,不然對中文的加密就會出現加密後無法解密的情況。
//第三個引數-向量,一定是16byte長度的,這裡採用金鑰字串的前16位。
byte[] encrypted = AesUtil.AES_CBC_Encrypt(returnMessageContent.getBytes("utf-8"), key.getBytes(), key.substring(0, 16).getBytes());
//將加密後的密文轉成base64格式的字串
String secretWord = AesUtil.encryptBASE64(encrypted);
解密的demo
String chat_content = secretWord;
// 解密,獲得訊息明文
byte[] chat_contentming = AesUtil.AES_CBC_Decrypt(AesUtil.decryptBASE64(chat_content),aesming.getBytes(),aesming.substring(0, 16).getBytes());
//將明文byte按照utf-8的形式轉化為String字串
String messageming = new String(chat_contentming, "utf-8");