java实现AES密钥生成

转自: https://www.jb51.net/article/102128.htm

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();
  }
}
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是Java实现AES加密和解密并生成随机密钥的简要代码: ```java import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class AESUtil { private static final String KEY_ALGORITHM = "AES"; private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding"; /** * 生成随机密钥 * * @return 密钥 */ public static String generateKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM); keyGenerator.init(128); SecretKey secretKey = keyGenerator.generateKey(); byte[] encoded = secretKey.getEncoded(); return Base64.getEncoder().encodeToString(encoded); } /** * AES加密 * * @param content 需要加密的字符串 * @param key 密钥 * @return 加密后的字符串 */ public static String encrypt(String content, String key) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encrypted = cipher.doFinal(content.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(encrypted); } /** * AES解密 * * @param content 需要解密的字符串 * @param key 密钥 * @return 解密后的字符串 */ public static String decrypt(String content, String key) throws Exception { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec secretKeySpec = new SecretKeySpec(Base64.getDecoder().decode(key), KEY_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec); byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(content)); return new String(decrypted, StandardCharsets.UTF_8); } } ``` 使用示例: ```java public class Test { public static void main(String[] args) throws Exception { String content = "Hello, world!"; // 生成随机密钥 String key = AESUtil.generateKey(); System.out.println("生成密钥:" + key); // 加密 String encrypted = AESUtil.encrypt(content, key); System.out.println("加密后的字符串:" + encrypted); // 解密 String decrypted = AESUtil.decrypt(encrypted, key); System.out.println("解密后的字符串:" + decrypted); } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值