java 加密工具類(MD5、RSA、AES等加密方式)
阿新 • • 發佈:2019-02-17
MD5加密
import org.apache.commons.codec.digest.DigestUtils; /** * MD5加密元件 * * @version 1.0 * @since 1.0 */ public abstract class MD5Util { /** * MD5加密 * * @param data * 待加密資料 * @return byte[] 訊息摘要 * * @throws Exception */ public static byte[] encodeMD5(String data) throws Exception { // 執行訊息摘要 return DigestUtils.md5(data); } /** * MD5加密 * * @param data * 待加密資料 * @return byte[] 訊息摘要 * * @throws Exception */ public static String encodeMD5Hex(String data) { // 執行訊息摘要 return DigestUtils.md5Hex(data); } }
AES加密和解密:
import java.io.IOException; 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 sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class AESUtil { private static final String encryptEncodeRules = "rxxg";// 定義預設加密規則 /** * @param content * @return string @Description: Aes加密流程: 1.構造金鑰生成器 2.根據ecnodeRules規則初始化金鑰生成器 * 3.產生金鑰 4.建立和初始化密碼器 * 5.內容加密 6.返回字串 */ public static String invokeEncryptEncode(String content) { String resultEncode = ""; try { // [1].利用KeyGenerator構造金鑰生成器,指定為AES演算法,不區分大小寫 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); // [2].根據encryptEncodeRules規則初始化金鑰生成器,生成一個128位的隨機源,根據傳入的位元組陣列,實現隨機數演算法 SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(encryptEncodeRules.getBytes()); keyGenerator.init(128, random); // [3].產生原始對稱金鑰 SecretKey originalKey = keyGenerator.generateKey(); // [4].獲得原始對稱金鑰的位元組陣列 byte[] rawByte = originalKey.getEncoded(); // [5].根據位元組陣列生成AES金鑰 SecretKey secretKey = new SecretKeySpec(rawByte, "AES"); // [6].根據指定演算法AES自成密碼器 Cipher cipher = Cipher.getInstance("AES"); // [7].初始化密碼器,第一個引數為加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二個引數為使用的KEY cipher.init(Cipher.ENCRYPT_MODE, secretKey); // [8].獲取加密內容的位元組陣列(這裡要設定為utf-8)不然內容中如果有中文和英文混合中文就會解密為亂碼 byte[] byteEncode = content.getBytes("utf-8"); // [9].根據密碼器的初始化方式--加密:將資料加密 byte[] bytesAes = cipher.doFinal(byteEncode); // [10].將加密後的資料轉換為字串 // 這裡用Base64Encoder中會找不到包 // 解決辦法: // 在專案的Build path中先移除JRE System Library,再新增庫JRE System Library,重新編譯後就一切正常了。 resultEncode = new String(new BASE64Encoder().encode(bytesAes)); // [11].將字串返回 return resultEncode; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } catch (NoSuchPaddingException exception) { exception.printStackTrace(); } catch (InvalidKeyException exception) { exception.printStackTrace(); } catch (UnsupportedEncodingException exception) { exception.printStackTrace(); } catch (IllegalBlockSizeException exception) { exception.printStackTrace(); } catch (BadPaddingException exception) { exception.printStackTrace(); } return resultEncode; } /** * @param content * @return String @Description:解密流程: * 1.同加密1-4步 2.將加密後的字串反紡成byte[]陣列 3.將加密內容解密 */ public static String invokeDecryptEncode(String content) { String resultEncode = ""; try { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(encryptEncodeRules.getBytes()); keyGenerator.init(128, random); SecretKey originalKey = keyGenerator.generateKey(); byte[] byteArray = originalKey.getEncoded(); SecretKey secretKey = new SecretKeySpec(byteArray, "AES"); Cipher cipher = Cipher.getInstance("AES"); // [7]將加密並編碼後的內容解碼成位元組陣列 cipher.init(Cipher.DECRYPT_MODE, secretKey); // [8]解密密文 byte[] byteContent = new BASE64Decoder().decodeBuffer(content); byte[] byteEncode = cipher.doFinal(byteContent); resultEncode = new String(byteEncode, "utf-8"); return resultEncode; } catch (NoSuchAlgorithmException exception) { exception.printStackTrace(); } catch (NoSuchPaddingException exception) { exception.printStackTrace(); } catch (InvalidKeyException exception) { exception.printStackTrace(); } catch (UnsupportedEncodingException exception) { exception.printStackTrace(); } catch (IllegalBlockSizeException exception) { exception.printStackTrace(); } catch (BadPaddingException exception) { exception.printStackTrace(); } catch (IOException exception) { exception.printStackTrace(); } return resultEncode; } public static void main(String[] args) { String[] keys = { "123456", "123abc" }; System.out.println("測試加密:"); for (String key : keys) { System.out.print("原始密文key:[" + key + "],"); String encryptString = invokeEncryptEncode(key); System.out.print("加密encryptString:[" + encryptString + "],"); String decryptString = invokeDecryptEncode(encryptString); System.out.println("解密decryptString:[" + decryptString + "]"); } } }
Base64加密:
import org.apache.commons.codec.binary.Base64; /** * Base64元件 * * @version 1.0 * @since 1.0 */ public abstract class Base64Util { /** * 字元編碼 */ public final static String ENCODING = "UTF-8"; /** * Base64編碼 * * @param data 待編碼資料 * @return String 編碼資料 * @throws Exception */ public static String encode(String data) throws Exception { // 執行編碼 byte[] b = Base64.encodeBase64(data.getBytes(ENCODING)); return new String(b, ENCODING); } /** * Base64安全編碼<br> * 遵循RFC 2045實現 * * @param data * 待編碼資料 * @return String 編碼資料 * * @throws Exception */ public static String encodeSafe(String data) throws Exception { // 執行編碼 byte[] b = Base64.encodeBase64(data.getBytes(ENCODING), true); return new String(b, ENCODING); } /** * Base64解碼 * * @param data 待解碼資料 * @return String 解碼資料 * @throws Exception */ public static String decode(String data) throws Exception { // 執行解碼 byte[] b = Base64.decodeBase64(data.getBytes(ENCODING)); return new String(b, ENCODING); } }
DES加密:
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
* DES安全編碼元件
*
* @version 1.0
*/
public abstract class DESUtil {
static{
Security.insertProviderAt(new BouncyCastleProvider(), 1);
}
/**
* 金鑰演算法 <br>
* Java 6 只支援56bit金鑰 <br>
* Bouncy Castle 支援64bit金鑰
*/
public static final String KEY_ALGORITHM = "DES";
/**
* 加密/解密演算法 / 工作模式 / 填充方式
*/
public static final String CIPHER_ALGORITHM = "DES/ECB/PKCS5PADDING";
/**
* 轉換金鑰
*
* @param key
* 二進位制金鑰
* @return Key 金鑰
* @throws Exception
*/
private static Key toKey(byte[] key) throws Exception {
// 例項化DES金鑰材料
DESKeySpec dks = new DESKeySpec(key);
// 例項化祕密金鑰工廠
SecretKeyFactory keyFactory = SecretKeyFactory
.getInstance(KEY_ALGORITHM);
// 生成祕密金鑰
SecretKey secretKey = keyFactory.generateSecret(dks);
return secretKey;
}
/**
* 解密
*
* @param data
* 待解密資料
* @param key
* 金鑰
* @return byte[] 解密資料
* @throws Exception
*/
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
// 還原金鑰
Key k = toKey(key);
// 例項化
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 初始化,設定為解密模式
cipher.init(Cipher.DECRYPT_MODE, k);
// 執行操作
return cipher.doFinal(data);
}
/**
* 加密
*
* @param data
* 待加密資料
* @param key
* 金鑰
* @return byte[] 加密資料
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 還原金鑰
Key k = toKey(key);
// 例項化
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
// 初始化,設定為加密模式
cipher.init(Cipher.ENCRYPT_MODE, k);
// 執行操作
return cipher.doFinal(data);
}
/**
* 生成金鑰 <br>
* Java 6 只支援56bit金鑰 <br>
* Bouncy Castle 支援64bit金鑰 <br>
*
* @return byte[] 二進位制金鑰
* @throws Exception
*/
public static byte[] initKey() throws Exception {
/*
* 例項化金鑰生成器
*
* 若要使用64bit金鑰注意替換 將下述程式碼中的KeyGenerator.getInstance(CIPHER_ALGORITHM);
* 替換為KeyGenerator.getInstance(CIPHER_ALGORITHM, "BC");
*/
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
/*
* 初始化金鑰生成器 若要使用64bit金鑰注意替換 將下述程式碼kg.init(56); 替換為kg.init(64);
*/
kg.init(56, new SecureRandom());
// 生成祕密金鑰
SecretKey secretKey = kg.generateKey();
// 獲得金鑰的二進位制編碼形式
return secretKey.getEncoded();
}
public static byte[] initKey(String seed) throws Exception {
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom secureRandom = new SecureRandom(new Base64().decode(seed));
kg.init(secureRandom);
SecretKey secretKey = kg.generateKey();
return secretKey.getEncoded();
}
}
RSA加密:
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.crypto.Cipher;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
/**
* RSA安全編碼元件
*
* @version 1.0
*/
public class RSAUtil {
/**
* 非對稱加密金鑰演算法
*/
public static final String KEY_ALGORITHM_RSA = "RSA";
/**
* 公鑰
*/
private static final String RSA_PUBLIC_KEY = "RSAPublicKey";
/**
* 私鑰
*/
private static final String RSA_PRIVATE_KEY = "RSAPrivateKey";
/**
* RSA金鑰長度
* 預設1024位,
* 金鑰長度必須是64的倍數,
* 範圍在512至65536位之間。
*/
private static final int KEY_SIZE = 1024;
static{
Security.insertProviderAt(new BouncyCastleProvider(), 1);
}
/**
* 私鑰解密
*
* @param data
* 待解密資料
* @param key
* 私鑰
* @return byte[] 解密資料
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
throws Exception {
// 取得私鑰
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
// 生成私鑰
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 對資料解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateKey);
int blockSize = cipher.getBlockSize();
if(blockSize>0){
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (data.length - j * blockSize > 0) {
bout.write(cipher.doFinal(data, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
}
return cipher.doFinal(data);
}
/**
* 公鑰解密
*
* @param data
* 待解密資料
* @param key
* 公鑰
* @return byte[] 解密資料
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] data, byte[] key)
throws Exception {
// 取得公鑰
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
// 生成公鑰
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// 對資料解密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
/**
* 公鑰加密
*
* @param data
* 待加密資料
* @param key
* 公鑰
* @return byte[] 加密資料
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, byte[] key)
throws Exception {
// 取得公鑰
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
// 對資料加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
int blockSize = cipher.getBlockSize();
if(blockSize>0){
int outputSize = cipher.getOutputSize(data.length);
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0,remainSize=0;
while ((remainSize = data.length - i * blockSize) > 0) {
int inputLen = remainSize > blockSize?blockSize:remainSize;
cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
i++;
}
return raw;
}
return cipher.doFinal(data);
}
/**
* 私鑰加密
*
* @param data
* 待加密資料
* @param key
* 私鑰
* @return byte[] 加密資料
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, byte[] key)
throws Exception {
// 取得私鑰
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
// 生成私鑰
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
// 對資料加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
int blockSize = cipher.getBlockSize();
if(blockSize>0){
int outputSize = cipher.getOutputSize(data.length);
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
: data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0,remainSize=0;
while ((remainSize = data.length - i * blockSize) > 0) {
int inputLen = remainSize > blockSize?blockSize:remainSize;
cipher.doFinal(data, i * blockSize, inputLen, raw, i * outputSize);
i++;
}
return raw;
}
return cipher.doFinal(data);
}
/**
* 取得私鑰
*
* @param keyMap
* 金鑰Map
* @return key 私鑰
* @throws Exception
*/
public static Key getPrivateKey(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PRIVATE_KEY);
}
/**
* 取得私鑰
*
* @param keyMap
* 金鑰Map
* @return byte[] 私鑰
* @throws Exception
*/
public static byte[] getPrivateKeyByte(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PRIVATE_KEY).getEncoded();
}
/**
* 取得公鑰
*
* @param keyMap
* 金鑰Map
* @return key 公鑰
* @throws Exception
*/
public static Key getPublicKey(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PUBLIC_KEY);
}
/**
* 取得公鑰
*
* @param keyMap
* 金鑰Map
* @return byte[] 公鑰
* @throws Exception
*/
public static byte[] getPublicKeyByte(Map<String, Key> keyMap)
throws Exception {
return keyMap.get(RSA_PUBLIC_KEY).getEncoded();
}
/**
* 初始化金鑰
* @param byte[] seed 種子
* @return Map 金鑰Map
* @throws Exception
*/
public static Map<String,Key> initKey(byte[] seed)throws Exception{
// 例項化金鑰對生成器
KeyPairGenerator keyPairGen = KeyPairGenerator
.getInstance(KEY_ALGORITHM_RSA);
// 初始化金鑰對生成器
keyPairGen.initialize(KEY_SIZE, new SecureRandom(seed) );
// 生成金鑰對
KeyPair keyPair = keyPairGen.generateKeyPair();
// 公鑰
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// 私鑰
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 封裝金鑰
Map<String, Key> keyMap = new HashMap<String, Key>(2);
keyMap.put(RSA_PUBLIC_KEY, publicKey);
keyMap.put(RSA_PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* 初始化金鑰
* @param seed 種子
* @return Map 金鑰Map
* @throws Exception
*/
public static Map<String,Key> initKey(String seed)throws Exception{
return initKey(seed.getBytes());
}
/**
* 初始化金鑰
*
* @return Map 金鑰Map
* @throws Exception
*/
public static Map<String, Key> initKey() throws Exception {
return initKey(UUID.randomUUID().toString().getBytes());
}
public static PublicKey getPublicRSAKey(String key) throws Exception {
X509EncodedKeySpec x509 = new X509EncodedKeySpec(Base64.decode(key));
KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
return kf.generatePublic(x509);
}
public static PrivateKey getPrivateRSAKey(String key) throws Exception {
PKCS8EncodedKeySpec pkgs8 = new PKCS8EncodedKeySpec(Base64.decode(key));
KeyFactory kf = KeyFactory.getInstance(KEY_ALGORITHM_RSA);
return kf.generatePrivate(pkgs8);
}
}