之前也是在網上找了很久, 但是終不能用, 後來突然發現根本不要這麼複雜, 今天把這個記下, 方便大家參考:
// 代碼由於是公司裏的, 有些不能貼上來, 但是核心代碼是獨立可用的
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
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;
//上面是引用的類
/**
* 加密數據
* @param content 需要加密的內容
* @param password 加密密碼
* @return
*/
public static byte[] encryptForAES(byte[] content, String password) {
if(content == null || content.length == 0 || password == null) return null;
try {//不需要這麼複雜的key
//KeyGenerator kgen = KeyGenerator.getInstance("AES");
//kgen.init(128, new SecureRandom(password.getBytes("utf-8")));
//SecretKey secretKey = kgen.generateKey();
//byte[] enCodeFormat = secretKey.getEncoded();
byte[] enCodeFormat = getBytesForUTF8(password);
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 創建密碼器,ECB模式,PKCS5Padding填充方式 AES/ECB/PKCS5Padding
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化爲加密模式
byte[] result = cipher.doFinal(content);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* 解密數據
* @param content 待解密內容
* @param password 解密密鑰
* @return
*/
public static byte[] decryptForAES(byte[] content, String password) {
if(content == null || content.length == 0 || password == null) return null;
try {//不需要這麼複雜的key
//KeyGenerator kgen = KeyGenerator.getInstance("AES");
//kgen.init(128, new SecureRandom(password.getBytes("utf-8")));
//SecretKey secretKey = kgen.generateKey();
//byte[] enCodeFormat = secretKey.getEncoded();
byte[] enCodeFormat = getBytesForUTF8(password);
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 創建密碼器 AES/ECB/PKCS5Padding
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化爲解密模式
byte[] result = cipher.doFinal(content);
return result; // 解密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}