網頁

2008年12月15日 星期一

[筆記] Java crypto & How to restore the key object

單純做個筆記...

import javax.crypto.KeyGenerator;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AES {
  public static void main(String[] args) throws Exception{
    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(128); //初始化
    SecretKey key = kg.generateKey(); //生成key
    //取得encoded key
    byte[] keyRaw = key.getEncoded();

    Cipher cp = Cipher.getInstance("AES");
    // 初始化為加密模式
    cp.init(Cipher.ENCRYPT_MODE, key);
    String str = "天譴寶寶吃肉... ";

    byte [] pText = str.getBytes(); // 可指定文字編碼
    byte [] cText = cp.doFinal(pText); //加密
    // 加密過後的String
    System.out.println(new String(cText));

    // 由encoded key,轉為key Object
    SecretKeySpec keySpec = new SecretKeySpec(keyRaw, "AES");
     // 重新初始化為解密模式
    cp.init(Cipher.DECRYPT_MODE, keySpec);
    pText = cp.doFinal(cText); // 解密
     // 需配合加密端指定文字編碼,沒有就聽天由命
    String str2 = new String(pText);
    System.out.println(str2);
  }
}


參考資料:
1. blog.csdn.net/xjtuse_mal/archive/2007/11/08/1874869.aspx
2. forums.sun.com/thread.jspa?threadID=760082

沒有留言:

張貼留言