先用KeyGenerator去選擇演算法,並且生成Key。可以參考KeyGenerator有提到一些概要
This class provides the functionality of a secret (symmetric) key generator. Key generators are constructed using one of the getInstance class methods of this class. KeyGenerator objects are reusable, i.e., after a key has been generated, the same KeyGenerator object can be re-used to generate further keys. There are two ways to generate a key: in an algorithm-independent manner, and in an algorithm-specific manner. The only difference between the two is the initialization of the object:
在透過SecretKey去取得Key,SecretKey本身是Interface,且可以觀察到實做類別為Key, Serializable
可以看得到Key被實做的類別分別有KerberosKey及SecretKeySpec,這兩個類別分別有實做出
getEncoded()。
getEncoded()這個方法可以取得到Key的位元組,因為SecretKey繼承Serializable,所以我們又可以透過ObjectOutputStream和ObjectInputStream將Key儲存成一個檔案。
在用SecretKeySpec去檢查Key的規範是否有符合標準,如果沒有則會噴錯
Cipher這個類別提供加解密的功能,可以運用Cipher的init去選擇要加密還是解密
加密是用Cipher.ENCRYPT_MODE,解密是用Cipher.DECRYPT_MODE
解碼的時候在透過ObjectInputStream將檔案讀近來,不過在這邊我尚未實做
僅只於分析而已,源碼都是來自於『Java AES Encrypt & Decrypt Example(加解密)』
import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; 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; public class AES { public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { // 欲加密的字串 String msg = "This is a message."; System.out.println("原始字串:" + new String(msg)); // 設定要使用的加密演算法 KeyGenerator keyG = KeyGenerator.getInstance("AES"); // 設定key的長度 keyG.init(128); // 產生SecretKey SecretKey secuK = keyG.generateKey(); // 取得要用來加密的key(解密也需使用這把key) byte[] key = secuK.getEncoded(); System.out.println("key:" + new String(key)); SecretKeySpec spec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); // 設定為加密模式 cipher.init(Cipher.ENCRYPT_MODE, spec); // 將字串加密,並取得加密後的資料 byte[] encryptData = cipher.doFinal(msg.getBytes()); System.out.println("加密後字串:" + new String(encryptData)); // 使用剛剛用來加密的key進行解密 spec = new SecretKeySpec(key, "AES"); cipher = Cipher.getInstance("AES"); // 設定為解密模式 cipher.init(Cipher.DECRYPT_MODE, spec); byte[] original = cipher.doFinal(encryptData); System.out.println("解密後字串:" + new String(original)); } }
參考資料:
http://cooking-java.blogspot.tw/2010/03/java-aes-encrypt.html
http://docs.oracle.com/javase/6/docs/api/javax/crypto/KeyGenerator.html