AES128加密解密算法


package com.zq.service;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
* @Author: Roylion
* @Description: AES算法封裝
* @Date: Created in 9:46 2018/8/9
*/
public class Demo{

/**
* 加密算法
*/
private static final String ENCRY_ALGORITHM = "AES";

/**
* 加密算法/加密模式/填充類型
* 本例采用AES加密,ECB加密模式,PKCS5Padding填充
*/
private static final String CIPHER_MODE = "AES/ECB/PKCS5Padding";

/**
* 設置iv偏移量
* 本例采用ECB加密模式,不需要設置iv偏移量
*/
private static final String IV_ = null;

/**
* 設置加密字符集
* 本例采用 UTF-8 字符集
*/
private static final String CHARACTER = "UTF-8";

/**
* 設置加密密碼處理長度。
* 不足此長度補0;
*/
private static final int PWD_SIZE = 16;

/**
* 密碼處理方法
* 如果加解密出問題,
* 請先查看本方法,排除密碼長度不足填充0字節,導致密碼不一致
* @param password 待處理的密碼
* @return
* @throws UnsupportedEncodingException
*/
private static byte[] pwdHandler(String password) throws UnsupportedEncodingException {
byte[] data = null;
if (password != null) {
byte[] bytes = password.getBytes(CHARACTER);
if (password.length() < PWD_SIZE) {
System.arraycopy(bytes, 0, data = new byte[PWD_SIZE], 0, bytes.length);
} else {
data = bytes;
}
}
return data;
}

//======================>原始加密<======================

/**
* 原始加密
* @param clearTextBytes 明文字節數組,待加密的字節數組
* @param pwdBytes 加密密碼字節數組
* @return 返回加密后的密文字節數組,加密錯誤返回null
*/
public static byte[] encrypt(byte[] clearTextBytes, byte[] pwdBytes) {
try {
// 1 獲取加密密鑰
SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);

// 2 獲取Cipher實例
Cipher cipher = Cipher.getInstance(CIPHER_MODE);

// 查看數據塊位數 默認為16(byte) * 8 =128 bit
// System.out.println("數據塊位數(byte):" + cipher.getBlockSize());

// 3 初始化Cipher實例。設置執行模式以及加密密鑰
cipher.init(Cipher.ENCRYPT_MODE, keySpec);

// 4 執行
byte[] cipherTextBytes = cipher.doFinal(clearTextBytes);

// 5 返回密文字符集
return cipherTextBytes;

} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 原始解密
* @param cipherTextBytes 密文字節數組,待解密的字節數組
* @param pwdBytes 解密密碼字節數組
* @return 返回解密后的明文字節數組,解密錯誤返回null
*/
public static byte[] decrypt(byte[] cipherTextBytes, byte[] pwdBytes) {

try {
// 1 獲取解密密鑰
SecretKeySpec keySpec = new SecretKeySpec(pwdBytes, ENCRY_ALGORITHM);

// 2 獲取Cipher實例
Cipher cipher = Cipher.getInstance(CIPHER_MODE);

// 查看數據塊位數 默認為16(byte) * 8 =128 bit
// System.out.println("數據塊位數(byte):" + cipher.getBlockSize());

// 3 初始化Cipher實例。設置執行模式以及加密密鑰
cipher.init(Cipher.DECRYPT_MODE, keySpec);

// 4 執行
byte[] clearTextBytes = cipher.doFinal(cipherTextBytes);

// 5 返回明文字符集
return clearTextBytes;

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 解密錯誤 返回null
return null;
}

//======================>BASE64<======================

/**
* BASE64加密
* @param clearText 明文,待加密的內容
* @param password 密碼,加密的密碼
* @return 返回密文,加密后得到的內容。加密錯誤返回null
*/
public static String encryptBase64(String clearText, String password) {
try {
// 1 獲取加密密文字節數組
byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));

// 2 對密文字節數組進行BASE64 encoder 得到 BASE6輸出的密文
BASE64Encoder base64Encoder = new BASE64Encoder();
String cipherText = base64Encoder.encode(cipherTextBytes);

// 3 返回BASE64輸出的密文
return cipherText;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 加密錯誤 返回null
return null;
}

/**
* BASE64解密
* @param cipherText 密文,帶解密的內容
* @param password 密碼,解密的密碼
* @return 返回明文,解密后得到的內容。解密錯誤返回null
*/
public static String decryptBase64(String cipherText, String password) {
try {
// 1 對 BASE64輸出的密文進行BASE64 decodebuffer 得到密文字節數組
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] cipherTextBytes = base64Decoder.decodeBuffer(cipherText);

// 2 對密文字節數組進行解密 得到明文字節數組
byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));

// 3 根據 CHARACTER 轉碼,返回明文字符串
return new String(clearTextBytes, CHARACTER);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 解密錯誤返回null
return null;
}

//======================>HEX<======================

/**
* HEX加密
* @param clearText 明文,待加密的內容
* @param password 密碼,加密的密碼
* @return 返回密文,加密后得到的內容。加密錯誤返回null
*/
public static String encryptHex(String clearText, String password) {
try {
// 1 獲取加密密文字節數組
byte[] cipherTextBytes = encrypt(clearText.getBytes(CHARACTER), pwdHandler(password));

// 2 對密文字節數組進行 轉換為 HEX輸出密文
String cipherText = byte2hex(cipherTextBytes);

// 3 返回 HEX輸出密文
return cipherText;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 加密錯誤返回null
return null;
}

/**
* HEX解密
* @param cipherText 密文,帶解密的內容
* @param password 密碼,解密的密碼
* @return 返回明文,解密后得到的內容。解密錯誤返回null
*/
public static String decryptHex(String cipherText, String password) {
try {
// 1 將HEX輸出密文 轉為密文字節數組
byte[] cipherTextBytes = hex2byte(cipherText);

// 2 將密文字節數組進行解密 得到明文字節數組
byte[] clearTextBytes = decrypt(cipherTextBytes, pwdHandler(password));

// 3 根據 CHARACTER 轉碼,返回明文字符串
return new String(clearTextBytes, CHARACTER);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 解密錯誤返回null
return null;
}

/*字節數組轉成16進制字符串 */
public static String byte2hex(byte[] bytes) { // 一個字節的數,
StringBuffer sb = new StringBuffer(bytes.length * 2);
String tmp = "";
for (int n = 0; n < bytes.length; n++) {
// 整數轉成十六進制表示
tmp = (java.lang.Integer.toHexString(bytes[n] & 0XFF));
if (tmp.length() == 1) {
sb.append("0");
}
sb.append(tmp);
}
return sb.toString().toUpperCase(); // 轉成大寫
}

/*將hex字符串轉換成字節數組 */
private static byte[] hex2byte(String str) {
if (str == null || str.length() < 2) {
return new byte[0];
}
str = str.toLowerCase();
int l = str.length() / 2;
byte[] result = new byte[l];
for (int i = 0; i < l; ++i) {
String tmp = str.substring(2 * i, 2 * i + 2);
result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
}
return result;
}

public static void main(String[] args) {
String test = encryptHex("test", "passwdkey");
System.out.println(test);

System.out.println(decryptHex(test, "passwdkey"));
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM