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

09:03上午 十二月 15, 2008 in category 程式設計 by H.C. Morris

單純做個筆記...


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
    byte[] keyRaw = key.getEncoded(); //取得encoded key

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

    byte [] pText = str.getBytes(); // 可指定文字編碼
    byte [] cText = cp.doFinal(pText); //加密

    System.out.println(new String(cText)); // 加密過後的String

    由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

迴響[0]

迴響:

發表迴響:
  • HTML 語法: 關閉