1. 程式人生 > >java生成AES祕鑰

java生成AES祕鑰

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Test {
  public static void main(String[] args) {
    getKey();
    getKeyByPass();
  }
  /**
  * 隨機生成祕鑰
  */
  public static void getKey() {
    try {
      KeyGenerator kg = KeyGenerator.getInstance("AES");
      kg.init(128);
      //要生成多少位,只需要修改這裡即可128, 192或256
      SecretKey sk = kg.generateKey();
      byte[] b = sk.getEncoded();
      String s = byteToHexString(b);
      System.out.println(s);
      System.out.println("十六進位制金鑰長度為"+s.length());
      System.out.println("二進位制金鑰的長度為"+s.length()*4);
    }
    catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      System.out.println("沒有此演算法。");
    }
  }
  /**
  * 使用指定的字串生成祕鑰
  */
  public static void getKeyByPass() {
    //生成祕鑰
    String password="testkey";
    try {
      KeyGenerator kg = KeyGenerator.getInstance("AES");
      // kg.init(128);//要生成多少位,只需要修改這裡即可128, 192或256
      //SecureRandom是生成安全隨機數序列,password.getBytes()是種子,只要種子相同,序列就一樣,所以生成的祕鑰就一樣。
      kg.init(128, new SecureRandom(password.getBytes()));
      SecretKey sk = kg.generateKey();
      byte[] b = sk.getEncoded();
      String s = byteToHexString(b);
      System.out.println(s);
      System.out.println("十六進位制金鑰長度為"+s.length());
      System.out.println("二進位制金鑰的長度為"+s.length()*4);
    }
    catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
      System.out.println("沒有此演算法。");
    }
  }
  /**
  * byte陣列轉化為16進位制字串
  * @param bytes
  * @return
  */
  public static String byteToHexString(byte[] bytes) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < bytes.length; i++) {
      String strHex=Integer.toHexString(bytes[i]);
      if(strHex.length() > 3) {
        sb.append(strHex.substring(6));
      } else {
        if(strHex.length() < 2) {
          sb.append("0" + strHex);
        } else {
          sb.append(strHex);
        }
      }
    }
    return sb.toString();
  }
}