Java如何實現對稱加密
Java對稱加密
Cipher實現對稱加密
public class EncrypDES { // 字符串默認鍵值 private static String strDefaultKey = "asdasdasdasdzcxczxczx"; //加密工具 private Cipher encryptCipher = null; // 解密工具 private Cipher decryptCipher = null; /** * 默認構造方法,使用默認密鑰 */ public EncrypDES() throws Exception { this(strDefaultKey); } /** * 指定密鑰構造方法 * @param strKey 指定的密鑰 * @throws Exception */ public EncrypDES(String strKey) throws Exception { // Security.addProvider(new com.sun.crypto.provider.SunJCE()); Key key = getKey(strKey.getBytes()); encryptCipher = Cipher.getInstance("DES"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher = Cipher.getInstance("DES"); decryptCipher.init(Cipher.DECRYPT_MODE, key); } /** * 將byte數組轉換為表示16進制值的字符串, 如:byte[]{8,18}轉換為:0813,和public static byte[] * * hexStr2ByteArr(String strIn) 互為可逆的轉換過程 * * @param arrB 需要轉換的byte數組 * @return 轉換後的字符串 * @throws Exception 本方法不處理任何異常,所有異常全部拋出 */ public static String byteArr2HexStr(byte[] arrB) throws Exception { int iLen = arrB.length; // 每個byte用2個字符才能表示,所以字符串的長度是數組長度的2倍 StringBuffer sb = new StringBuffer(iLen * 2); for (int i = 0; i < iLen; i++) { int intTmp = arrB[i]; // 把負數轉換為正數 while (intTmp < 0) { intTmp = intTmp + 256; } // 小於0F的數需要在前面補0 if (intTmp < 16) { sb.append("0"); } sb.append(Integer.toString(intTmp, 16)); } return sb.toString(); } /** * 將表示16進制值的字符串轉換為byte數組,和public static String byteArr2HexStr(byte[] arrB) * 互為可逆的轉換過程 * @param strIn 需要轉換的字符串 * @return 轉換後的byte數組 */ public static byte[] hexStr2ByteArr(String strIn) throws Exception { byte[] arrB = strIn.getBytes(); int iLen = arrB.length; // 兩個字符表示一個字節,所以字節數組長度是字符串長度除以2 byte[] arrOut = new byte[iLen / 2]; for (int i = 0; i < iLen; i = i + 2) { String strTmp = new String(arrB, i, 2); arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16); } return arrOut; } /** * * 加密字節數組 * @param arrB 需加密的字節數組 * @return 加密後的字節數組 */ public byte[] encrypt(byte[] arrB) throws Exception { return encryptCipher.doFinal(arrB); } /** * 加密字符串 * @param strIn 需加密的字符串 * @return 加密後的字符串 */ public String encrypt(String strIn) throws Exception { return byteArr2HexStr(encrypt(strIn.getBytes())); } /** * 解密字節數組 * @param arrB 需解密的字節數組 * @return 解密後的字節數組 */ public byte[] decrypt(byte[] arrB) throws Exception { return decryptCipher.doFinal(arrB); } /** * 解密字符串 * @param strIn 需解密的字符串 * @return 解密後的字符串 */ public String decrypt(String strIn) throws Exception { return new String(decrypt(hexStr2ByteArr(strIn))); } /** * 從指定字符串生成密鑰,密鑰所需的字節數組長度為8位 不足8位時後面補0,超出8位隻取前8位 * @param arrBTmp 構成該字符串的字節數組 * @return 生成的密鑰 */ private Key getKey(byte[] arrBTmp) throws Exception { // 創建一個空的8位字節數組(默認值為0) byte[] arrB = new byte[8]; // 將原始字節數組轉換為8位 for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } // 生成密鑰 Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); return key; } public static void main(String[] args) { try { String msg1 = "hello Cipher"; EncrypDES des1 = new EncrypDES();// 使用默認密鑰 System.out.println("加密前的字符:" + msg1); System.out.println("加密後的字符:" + des1.encrypt(msg1)); System.out.println("解密後的字符:" + des1.decrypt(des1.encrypt(msg1))); } catch (Exception e) { e.printStackTrace(); } } }
運行main方法後得出結果是:
base64加解密
public class EncryptUtil { /** * BASE64解密 * @throws Exception */ public static byte[] decryptBASE64(String key) throws Exception { return (new BASE64Decoder()).decodeBuffer(key); } /** * BASE64加密 */ public static String encryptBASE64(byte[] key) throws Exception { return (new BASE64Encoder()).encodeBuffer(key); } public static void main(String[] args) throws Exception { String ss = "9899b43bbde94982b71efad47eed9f82-234234324-123456"; String encryptBASE64 = encryptBASE64(ss.getBytes()); System.out.println(encryptBASE64); byte[] bytes = decryptBASE64(encryptBASE64); System.out.println(new String(bytes)); } }
運行main方法得出的:
對稱加密與非對稱加密
加密方式大致分為兩種,對稱加密和非對稱加密。對稱加密是最快速、最簡單的一種加密方式,加密(encryption)與解密(decryption)用的是同樣的密鑰(secret key)。非對稱加密為數據的加密與解密提供瞭一個非常安全的方法,它使用瞭一對密鑰,公鑰(public key)和私鑰(private key)。私鑰隻能由一方安全保管,不能外泄,而公鑰則可以發給任何請求它的人。因此安全性大大提高。
對稱加密
所謂對稱加密算法即:加密和解密使用相同密鑰的算法。常見的有DES、3DES、AES、PBE等加密算法,這幾種算法安全性依次是逐漸增強的。
DES加密
DES是一種對稱加密算法,是一種非常簡便的加密算法,但是密鑰長度比較短。DES加密算法出自IBM的研究,後來被美國正式采用,之後開始廣泛流傳,但是近些年使用越來越少,因為DES使用56位密鑰,以現代計算能力,24小時內即可被破解。雖然如此,在某些簡單應用中,我們還是可以使用DES加密算法.簡單的DES加密算法實現:
import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class DESUtil { private static final String KEY_ALGORITHM = "DES"; private static final String DEFAULT_CIPHER_ALGORITHM = "DES/ECB/PKCS5Padding";// 默認的加密算法 /** * DES 加密操作 * * @param content * 待加密內容 * @param key * 加密密鑰 * @return 返回Base64轉碼後的加密數據 */ public static String encrypt(String content, String key) { try { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 創建密碼器 byte[] byteContent = content.getBytes("utf-8"); //初始化為加密模式的密碼器 //方法一 //cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); //方法二 cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(key)); byte[] result = cipher.doFinal(byteContent);// 加密 return Base64.encodeBase64String(result);// 通過Base64轉碼返回 } catch (Exception ex) { Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * DES 解密操作 * * @param content * @param key * @return */ public static String decrypt(String content, String key) { try { // 實例化 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); // 使用密鑰初始化,設置為解密模式 //方法一 //cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); //方法二 cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(key)); // 執行操作 byte[] result = cipher.doFinal(Base64.decodeBase64(content)); return new String(result, "utf-8"); } catch (Exception ex) { Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * 生成加密秘鑰 * * @return */ private static SecretKey getSecretKey(final String key) { try { SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM); SecretKey sk = SecretKeyFactory.getInstance(KEY_ALGORITHM).generateSecret(keySpec); return sk; } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } /** * 生成加密秘鑰 * * @return */ private static SecretKeySpec getSecretKeySpec(final String key) { // 返回生成指定算法密鑰生成器的 KeyGenerator 對象 KeyGenerator kg = null; try { kg = KeyGenerator.getInstance(KEY_ALGORITHM); // DES 要求密鑰長度為 56 kg.init(56, new SecureRandom(key.getBytes())); // 生成一個密鑰 SecretKey secretKey = kg.generateKey(); return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 轉換為DES專用密鑰 } catch (NoSuchAlgorithmException ex) { Logger.getLogger(DESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static void main(String[] args) { String content = "hello,您好"; String key = "sde@5f98H*^hsff%dfs$r344&df8543*er"; System.out.println("content:" + content); String s1 = DESUtil.encrypt(content, key); System.out.println("s1:" + s1); System.out.println("s2:" + DESUtil.decrypt(s1, key)); } }
3DES加密
3DES是一種對稱加密算法,在 DES 的基礎上,使用三重數據加密算法,對數據進行加密,它相當於是對每個數據塊應用三次 DES 加密算法。由於計算機運算能力的增強,原版 DES 密碼的密鑰長度變得容易被暴力 破 解;3DES 即是設計用來提供一種相對簡單的方法,即通過增加 DES 的密鑰長度來避免類似的攻擊,而不是設計一種全新的塊密碼算法這樣來說,破解的概率就小瞭很多。缺點由於使用瞭三重數據加密算法,可能會比較耗性能。簡單的3DES加密算法實現:
import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class TripDESUtil { private static final String KEY_ALGORITHM = "DESede"; private static final String DEFAULT_CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";// 默認的加密算法 /** * DESede 加密操作 * * @param content * 待加密內容 * @param key * 加密密鑰 * @return 返回Base64轉碼後的加密數據 */ public static String encrypt(String content, String key) { try { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 創建密碼器 byte[] byteContent = content.getBytes("utf-8"); //初始化為加密模式的密碼器 //方法一 //cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); //方法二 cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(key)); byte[] result = cipher.doFinal(byteContent);// 加密 return Base64.encodeBase64String(result);// 通過Base64轉碼返回 } catch (Exception ex) { Logger.getLogger(TripDESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * DESede 解密操作 * * @param content * @param key * @return */ public static String decrypt(String content, String key) { try { // 實例化 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); // 使用密鑰初始化,設置為解密模式 //方法一 //cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); //方法二 cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(key)); // 執行操作 byte[] result = cipher.doFinal(Base64.decodeBase64(content)); return new String(result, "utf-8"); } catch (Exception ex) { Logger.getLogger(TripDESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * 生成加密秘鑰 * * @return */ private static SecretKey getSecretKey(final String key) { try { SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM); SecretKey sk = SecretKeyFactory.getInstance(KEY_ALGORITHM).generateSecret(keySpec); return sk; } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } /** * 生成加密秘鑰 * * @return */ private static SecretKeySpec getSecretKeySpec(final String key) { // 返回生成指定算法密鑰生成器的 KeyGenerator 對象 KeyGenerator kg = null; try { kg = KeyGenerator.getInstance(KEY_ALGORITHM); // DESede kg.init(new SecureRandom(key.getBytes())); // 生成一個密鑰 SecretKey secretKey = kg.generateKey(); return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 轉換為DESede專用密鑰 } catch (NoSuchAlgorithmException ex) { Logger.getLogger(TripDESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static void main(String[] args) { String content = "hello,您好"; String key = "sde@5f98H*^hsff%dfs$r344&df8543*er"; System.out.println("content:" + content); String s1 = TripDESUtil.encrypt(content, key); System.out.println("s1:" + s1); System.out.println("s2:" + TripDESUtil.decrypt(s1, key)); } }
AES加密
AES是一種對稱加密算法,在 DES 的基礎上,使用三重數據加密算法,對數據進行加密,它相當於是對每個數據塊應用三次 DES 加密算法。由於計算機運算能力的增強,原版 DES 密碼的密鑰長度變得容易被暴力 破解;3DES 即是設計用來提供一種相對簡單的方法,即通過增加 DES 的密鑰長度來避免類似的攻擊,而不是設計一種全新的塊密碼算法這樣來說,破解的概率就小瞭很多。缺點由於使用瞭三重數據加密算法,可能會比較耗性能。簡單的AES加密算法實現:
import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.spec.InvalidKeySpecException; import java.util.logging.Level; import java.util.logging.Logger; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; public class AESUtil { private static final String KEY_ALGORITHM = "AES"; private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默認的加密算法 /** * AES 加密操作 * * @param content 待加密內容 * @param key 加密密鑰 * @return 返回Base64轉碼後的加密數據 */ public static String encrypt(String content, String key) { try { Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 創建密碼器 byte[] byteContent = content.getBytes("utf-8"); //初始化為加密模式的密碼器 //方法一 //cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); //方法二 cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(key)); byte[] result = cipher.doFinal(byteContent);// 加密 return Base64.encodeBase64String(result);//通過Base64轉碼返回 } catch (Exception ex) { Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * AES 解密操作 * * @param content * @param key * @return */ public static String decrypt(String content, String key) { try { //實例化 Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); // 使用密鑰初始化,設置為解密模式 //方法一 //cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key)); //方法二 cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(key)); //執行操作 byte[] result = cipher.doFinal(Base64.decodeBase64(content)); return new String(result, "utf-8"); } catch (Exception ex) { Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } /** * 生成加密秘鑰 * * @return */ private static SecretKey getSecretKey(final String key) { try { SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), KEY_ALGORITHM); SecretKey sk = SecretKeyFactory.getInstance(KEY_ALGORITHM).generateSecret(keySpec); return sk; } catch (InvalidKeySpecException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } /** * 生成加密秘鑰 * * @return */ private static SecretKeySpec getSecretKeySpec(final String key) { //返回生成指定算法密鑰生成器的 KeyGenerator 對象 KeyGenerator kg = null; try { kg = KeyGenerator.getInstance(KEY_ALGORITHM); //AES 要求密鑰長度為 128 kg.init(128, new SecureRandom(key.getBytes())); //生成一個密鑰 SecretKey secretKey = kg.generateKey(); return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 轉換為AES專用密鑰 } catch (NoSuchAlgorithmException ex) { Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex); } return null; } public static void main(String[] args) { String content = "hello,您好"; String key = "sde@5f98H*^hsff%dfs$r344&df8543*er"; System.out.println("content:" + content); String s1 = AESUtil.encrypt(content, key); System.out.println("s1:" + s1); System.out.println("s2:"+AESUtil.decrypt(s1, key)); } }
非對稱加密
非對稱加密算法需要兩個密鑰:公開密鑰(publickey)和私有密鑰(privatekey)。公開密鑰與私有密鑰是一對,如果用公開密鑰對數據進行加密,隻有用對應的私有密鑰才能解密;如果用私有密鑰對數據進行加密,那麼隻有用對應的公開密鑰才能解密。一般公鑰是公開的,私鑰是自己保存。因為加密和解密使用的是兩個不同的密鑰,所以這種算法叫作非對稱加密算法。安全性相對對稱加密來說更高,是一種高級加密方式。
RSA加密
RSA是一種非對稱加密算法.RSA有兩個密鑰,一個是公開的,稱為公開密鑰;一個是私密的,稱為私密密鑰。公開密鑰是對大眾公開的,私密密鑰是服務器私有的,兩者不能互推得出。用公開密鑰對數據進行加密,私密密鑰可解密;私密密鑰對數據加密,公開密鑰可解密。速度較對稱加密慢。簡單的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.Signature; 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 javax.crypto.Cipher; /** * <p> * RSA公鑰/私鑰/簽名工具包 * </p> * <p> * 字符串格式的密鑰在未在特殊說明情況下都為BASE64編碼格式<br/> * 由於非對稱加密速度極其緩慢,一般文件不使用它來加密而是使用對稱加密,<br/> * 非對稱加密算法可以用來對對稱加密的密鑰加密,這樣保證密鑰的安全也就保證瞭數據的安全 * </p> * */ public class RSAUtils { /** * 加密算法RSA */ public static final String KEY_ALGORITHM = "RSA"; /** * 簽名算法 */ public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; /** * 獲取公鑰的key */ private static final String PUBLIC_KEY = "RSAPublicKey"; /** * 獲取私鑰的key */ private static final String PRIVATE_KEY = "RSAPrivateKey"; /** * RSA最大加密明文大小 */ private static final int MAX_ENCRYPT_BLOCK = 117; /** * RSA最大解密密文大小 */ private static final int MAX_DECRYPT_BLOCK = 128; /** * <p> * 生成密鑰對(公鑰和私鑰) * </p> * * @return * @throws Exception */ public static Map<String, Object> genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, Object> keyMap = new HashMap<String, Object>(2); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** * <p> * 用私鑰對信息生成數字簽名 * </p> * * @param data 已加密數據 * @param privateKey 私鑰(BASE64編碼) * * @return * @throws Exception */ public static String sign(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(privateK); signature.update(data); return Base64Utils.encode(signature.sign()); } /** * <p> * 校驗數字簽名 * </p> * * @param data 已加密數據 * @param publicKey 公鑰(BASE64編碼) * @param sign 數字簽名 * * @return * @throws Exception * */ public static boolean verify(byte[] data, String publicKey, String sign) throws Exception { byte[] keyBytes = Base64Utils.decode(publicKey); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicK = keyFactory.generatePublic(keySpec); Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicK); signature.update(data); return signature.verify(Base64Utils.decode(sign)); } /** * <P> * 私鑰解密 * </p> * * @param encryptedData 已加密數據 * @param privateKey 私鑰(BASE64編碼) * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, privateK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對數據分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /** * <p> * 公鑰解密 * </p> * * @param encryptedData 已加密數據 * @param publicKey 公鑰(BASE64編碼) * @return * @throws Exception */ public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception { byte[] keyBytes = Base64Utils.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, publicK); int inputLen = encryptedData.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對數據分段解密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_DECRYPT_BLOCK) { cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); } else { cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_DECRYPT_BLOCK; } byte[] decryptedData = out.toByteArray(); out.close(); return decryptedData; } /** * <p> * 公鑰加密 * </p> * * @param data 源數據 * @param publicKey 公鑰(BASE64編碼) * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64Utils.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 對數據加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對數據分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } /** * <p> * 私鑰加密 * </p> * * @param data 源數據 * @param privateKey 私鑰(BASE64編碼) * @return * @throws Exception */ public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception { byte[] keyBytes = Base64Utils.decode(privateKey); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 對數據分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; } /** * <p> * 獲取私鑰 * </p> * * @param keyMap 密鑰對 * @return * @throws Exception */ public static String getPrivateKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PRIVATE_KEY); return Base64Utils.encode(key.getEncoded()); } /** * <p> * 獲取公鑰 * </p> * * @param keyMap 密鑰對 * @return * @throws Exception */ public static String getPublicKey(Map<String, Object> keyMap) throws Exception { Key key = (Key) keyMap.get(PUBLIC_KEY); return Base64Utils.encode(key.getEncoded()); } } import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import com.sun.org.apache.xml.internal.security.utils.Base64; public class Base64Utils { /** * 文件讀取緩沖區大小 */ private static final int CACHE_SIZE = 1024; /** * <p> * BASE64字符串解碼為二進制數據 * </p> * * @param base64 * @return * @throws Exception */ public static byte[] decode(String base64) throws Exception { return Base64.decode(base64.getBytes()); } /** * <p> * 二進制數據編碼為BASE64字符串 * </p> * * @param bytes * @return * @throws Exception */ public static String encode(byte[] bytes) throws Exception { return new String(Base64.encode(bytes)); } /** * <p> * 將文件編碼為BASE64字符串 * </p> * <p> * 大文件慎用,可能會導致內存溢出 * </p> * * @param filePath * 文件絕對路徑 * @return * @throws Exception */ public static String encodeFile(String filePath) throws Exception { byte[] bytes = fileToByte(filePath); return encode(bytes); } /** * <p> * BASE64字符串轉回文件 * </p> * * @param filePath * 文件絕對路徑 * @param base64 * 編碼字符串 * @throws Exception */ public static void decodeToFile(String filePath, String base64) throws Exception { byte[] bytes = decode(base64); byteArrayToFile(bytes, filePath); } /** * <p> * 文件轉換為二進制數組 * </p> * * @param filePath * 文件路徑 * @return * @throws Exception */ public static byte[] fileToByte(String filePath) throws Exception { byte[] data = new byte[0]; File file = new File(filePath); if (file.exists()) { FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(2048); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); data = out.toByteArray(); } return data; } /** * <p> * 二進制數據寫文件 * </p> * * @param bytes * 二進制數據 * @param filePath * 文件生成目錄 */ public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { InputStream in = new ByteArrayInputStream(bytes); File destFile = new File(filePath); if (!destFile.getParentFile().exists()) { destFile.getParentFile().mkdirs(); } destFile.createNewFile(); OutputStream out = new FileOutputStream(destFile); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); } }
以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。