Home >Java >javaTutorial >Example of AES key generation algorithm implemented in java

Example of AES key generation algorithm implemented in java

高洛峰
高洛峰Original
2017-01-24 11:12:212481browse

The example in this article describes the AES key generation algorithm implemented in java. Share it with everyone for your reference, the details are as follows:

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();
  }
}

I hope this article will be helpful to everyone in java programming.

For more related articles on AES key generation algorithm examples implemented in java, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn