java實現AES的簡單加密解密
阿新 • • 發佈:2018-12-25
AESUtil
package com.zhuyun.aes; import java.io.IOException; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; public class AESUtil { //生成AES祕鑰,然後Base64編碼 public static String genKeyAES() throws Exception{ KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey key = keyGen.generateKey(); String base64Str = byte2Base64(key.getEncoded()); return base64Str; } //將Base64編碼後的AES祕鑰轉換成SecretKey物件 public static SecretKey loadKeyAES(String base64Key) throws Exception{ byte[] bytes = base642Byte(base64Key); SecretKeySpec key = new SecretKeySpec(bytes, "AES"); return key; } //位元組陣列轉Base64編碼 public static String byte2Base64(byte[] bytes){ BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(bytes); } //Base64編碼轉位元組陣列 public static byte[] base642Byte(String base64Key) throws IOException{ BASE64Decoder decoder = new BASE64Decoder(); return decoder.decodeBuffer(base64Key); } //加密 public static byte[] encryptAES(byte[] source, SecretKey key) throws Exception{ Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(source); } //解密 public static byte[] decryptAES(byte[] source, SecretKey key) throws Exception{ Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(source); } }
TestAES
package com.zhuyun.test; import javax.crypto.SecretKey; import org.junit.Test; import com.zhuyun.aes.AESUtil; public class TestAES { @Test public void testAES(){ try { //=================客戶端================= //hello, i am infi, good night!加密 String message = "hello, i am infi, good night!"; //生成AES祕鑰,並Base64編碼 String base64Str = AESUtil.genKeyAES(); System.out.println("AES祕鑰Base64編碼:" + base64Str); //將Base64編碼的字串,轉換成AES祕鑰 SecretKey aesKey = AESUtil.loadKeyAES(base64Str); //加密 byte[] encryptAES = AESUtil.encryptAES(message.getBytes(), aesKey); //加密後的內容Base64編碼 String byte2Base64 = AESUtil.byte2Base64(encryptAES); System.out.println("加密並Base64編碼的結果:" + byte2Base64); //############## 網路上傳輸的內容有Base64編碼後的祕鑰 和 Base64編碼加密後的內容 ################# //===================服務端================ //將Base64編碼的字串,轉換成AES祕鑰 SecretKey aesKey2 = AESUtil.loadKeyAES(base64Str); //加密後的內容Base64解碼 byte[] base642Byte = AESUtil.base642Byte(byte2Base64); //解密 byte[] decryptAES = AESUtil.decryptAES(base642Byte, aesKey2); //解密後的明文 System.out.println("解密後的明文: " + new String(decryptAES)); } catch (Exception e) { e.printStackTrace(); } } }
測試結果為:
AES祕鑰Base64編碼:UrlSOS8igqefseqoeJUwbg==
加密並Base64編碼的結果:7QXSwDckiqIWz1SfpAG48++ex3Zcjv92Uhl5zppqjTQ=
解密後的明文: hello, i am infi, good night!