歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 自寫AES加密解密工具類

自寫AES加密解密工具類

日期:2017/3/1 9:12:30   编辑:Linux編程

此類主要用於加密與解密,采用128位ECB模式,PKCS5Padding填充補位。

可使用方法為加密返回二進制encryptBin(content, key)、加密返回十六進制encryptHex(content, key)、二進制內容解密decryptBin(content, key)、十六進制內容解密decryptHex(content, key)。

content是需要加密的字符串,key是密鑰,隨意一個字符串。

package com.test;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AESCode {

private static final String algorithm = "AES";
private static final String transformation = "AES/ECB/PKCS5Padding";
private static final String charset = "utf-8";

private static final Log _log = LogFactory.getLog(AESCode.class);

/**
* 獲取key 填充密匙 獲取加密的密匙數據
*
* @paramString key
* @return byte[] enCodeFormat;
* @author panjianghong 2016-8-29
* */
private static byte[] getEnCodeFormat(String key){

try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
return enCodeFormat;
} catch (NoSuchAlgorithmException e) {
_log.error("獲取密匙數據失敗!");
}
return null;
}



/**
* 獲取加密數據的二進制字符串數據
*
* @param content
* @param enCodeFormat
* @return String
* @author panjianghong 2016-8-29
* */
public static String encryptBin(String content, String key){

try {
byte[] byteConten = encrypt(content, key);
return byte2BinString(byteConten);
} catch (Exception e) {
_log.error("獲取二進制加密數據失敗!");
}
return null;
}



/**
* 獲取加密數據的十六進制字符串數據
*
* @param content
* @param enCodeFormat
* @return String
* @author panjianghong 2016-8-29
* */
public static String encryptHex(String content, String key){

try {
byte[] byteConten = encrypt(content, key);
return byte2HexString(byteConten);
} catch (Exception e) {
_log.error("獲取十六進制加密數據失敗!");
}
return null;
}

/**
* 獲取文件的加密數據
* 返回加密數據的字節數組 byte[]
*
* @param content
* @param enCodeFormat
* @return byte[] byteResoult
* @author panjianghong 2016-8-29
* */
private static byte[] encrypt(String content, String key){

try {
SecretKeySpec secretyKey = new SecretKeySpec(getEnCodeFormat(key), algorithm);
Cipher cipher = Cipher.getInstance(transformation);
byte[] byteContent = content.getBytes(charset);
cipher.init(Cipher.ENCRYPT_MODE, secretyKey);
byte[] byteResoult = cipher.doFinal(byteContent);
return byteResoult;
} catch (InvalidKeyException e) {
_log.error("獲取加密數據的字節數組失敗!");
} catch (NoSuchAlgorithmException e) {
_log.error("獲取加密數據的字節數組失敗!");
} catch (NoSuchPaddingException e) {
_log.error("獲取加密數據的字節數組失敗!");
} catch (UnsupportedEncodingException e) {
_log.error("獲取加密數據的字節數組失敗!");
} catch (IllegalBlockSizeException e) {
_log.error("獲取加密數據的字節數組失敗!");
} catch (BadPaddingException e) {
_log.error("獲取加密數據的字節數組失敗!");
}

return null;
}

/**
* 以二進制字符串數據進行解密
*
* @param content
* @param enCodeFormat
* @return String
* @author panjianghong 2016-8-29
* */

public static String decryptBin(String binContent, String key){

try {
SecretKeySpec secretyKey = new SecretKeySpec(getEnCodeFormat(key), algorithm);
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, secretyKey);
byte[] byteResoult = cipher.doFinal(binString2Byte(binContent));
try {
return new String(byteResoult,"utf-8");
} catch (UnsupportedEncodingException e) {
_log.error("解密二進制數據失敗!");
return null;
}
} catch (InvalidKeyException e) {
_log.error("解密二進制數據失敗!");
} catch (NoSuchAlgorithmException e) {
_log.error("解密二進制數據失敗!");
} catch (NoSuchPaddingException e) {
_log.error("解密二進制數據失敗!");
} catch (IllegalBlockSizeException e) {
_log.error("解密二進制數據失敗!");
} catch (BadPaddingException e) {
_log.error("解密二進制數據失敗!");
}

return null;
}

/**
* 以十六進制字符串數據進行解密
*
* @param content
* @param enCodeFormat
* @return String
* @author panjianghong 2016-8-29
* */
public static String decryptHex(String binContent, String key){

try {
SecretKeySpec secretyKey = new SecretKeySpec(getEnCodeFormat(key), algorithm);
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, secretyKey);
byte[] byteResoult = cipher.doFinal(hexString2Byte(binContent));
try {
return new String(byteResoult,"utf-8");
} catch (UnsupportedEncodingException e) {
_log.error("解密十六進制數據失敗!");
return null;
}
} catch (InvalidKeyException e) {
_log.error("解密十六進制數據失敗!");
} catch (NoSuchAlgorithmException e) {
_log.error("解密十六進制數據失敗!");
} catch (NoSuchPaddingException e) {
_log.error("解密十六進制數據失敗!");
} catch (IllegalBlockSizeException e) {
_log.error("解密十六進制數據失敗!");
} catch (BadPaddingException e) {
_log.error("解密十六進制數據失敗!");
}

return null;
}




/**
* 字節數組轉化成二進制數
* @param content
* @return string
* @author panjianghong 2016-8-29
* */
private static String byte2BinString(byte[] content){
if(null == content){
_log.error("需要轉換的參數為空!");
return null;
}

return hexString2BinString(byte2HexString(content));
}

/**
* 字節數組轉化成十六進制數的小寫形式
* @param content
* @return string
* @author panjianghong 2016-8-29
* */
private static String byte2HexString(byte[] content){
if(null == content){
_log.error("需要轉換的參數為空!");
return null;
}

StringBuffer sb = new StringBuffer();
for (int i = 0; i < content.length; i++) {
String hex = Integer.toHexString(content[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toLowerCase());
}

return sb.toString();
}

/**
* 十六進制數轉化成二進制數
* @param content
* @return string
* @author panjianghong 2016-8-29
* */
private static String hexString2BinString(String content){

if (null == content || content.length() % 2 != 0) {
_log.error("需要轉換的參數為空或者參數長度不是2的倍數!");
return null;
}

StringBuffer bString = new StringBuffer();
StringBuffer tmp = new StringBuffer();
for (int i = 0; i < content.length(); i++)
{
tmp.append("0000").append(Integer.toBinaryString(Integer.parseInt(content.substring(i, i + 1), 16)));
bString.append(tmp.toString().substring(tmp.toString().length() - 4));
tmp.delete(0, tmp.toString().length());
}
return bString.toString();
}
/**
* 二進制數轉化成十六進制數
* @param content
* @return string
* @author panjianghong 2016-8-29
* */
private static String BinString2hexString(String content){

if (null == content || content.equals("") || content.length() % 8 != 0){
_log.error("需要轉換的參數為空或者參數長度不是8的倍數!");
return null;
}

StringBuffer tmp = new StringBuffer();
int iTmp = 0;
for (int i = 0; i < content.length(); i += 4)
{
iTmp = 0;
for (int j = 0; j < 4; j++)
{
iTmp += Integer.parseInt(content.substring(i + j, i + j + 1)) << (4 - j - 1);
}
tmp.append(Integer.toHexString(iTmp));
}
return tmp.toString();
}


/**
* 16進制數轉化成字節數組
* @param content
* @return string
* @author panjianghong 2016-8-29
* */
private static byte[] hexString2Byte(String content){
if (content.length() < 1){
_log.error("需要轉換的參數為空或者參數長度<1!");
return null;
}

byte[] byteRresult = new byte[content.length() / 2];
for (int i = 0; i < content.length() / 2; i++) {
int high = Integer.parseInt(content.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(content.substring(i * 2 + 1, i * 2 + 2), 16);
byteRresult[i] = (byte) (high * 16 + low);
}
return byteRresult;
}

/**
* 二進制數轉化成字節數組
* @param content
* @return string
* @author panjianghong 2016-8-29
* */
private static byte[] binString2Byte(String content){
if (content.length() < 1){
_log.error("需要轉換的參數為空或者參數長度<1!");
return null;
}

return hexString2Byte(BinString2hexString(content));
}

}

Copyright © Linux教程網 All Rights Reserved