自动生成AES密钥,并使用生成的进行加密解密1


/**
* 自动生成AES128位密钥
*/
public static void getA221(){
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("没有此算法。");
}
}

/**
* 二进制byte[]转十六进制string
*/
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();
}

/**
* 十六进制string转二进制byte[]
*/
public static byte[] hexStringToByte(String s) {
byte[] baKeyword = new byte[s.length() / 2];
for (int i = 0; i < baKeyword.length; i++) {
try {
baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
System.out.println("十六进制转byte发生错误!!!");
e.printStackTrace();
}
}
return baKeyword;
}

/**
* 使用对称密钥进行加密
*/
public static void getA231() throws Exception{
String keys = "c0e9fcff59ecc3b8b92939a1a2724a44"; //密钥
byte[] keyb = hexStringToByte(keys);
String mingwen = "hello word!"; //明文
SecretKeySpec sKeySpec = new SecretKeySpec(keyb, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
byte[] bjiamihou = cipher.doFinal(mingwen.getBytes());
System.out.println(byteToHexString(bjiamihou)); //加密后数据为ecf0a6bc80dbaf657eac9b06ecd92962
}

/**
* 使用对称密钥进行解密
*/
public static void getA232() throws Exception{
String keys = "c0e9fcff59ecc3b8b92939a1a2724a44"; //密钥
byte[] keyb = hexStringToByte(keys);
String sjiami = "ecf0a6bc80dbaf657eac9b06ecd92962"; //密文
byte[] miwen = hexStringToByte(sjiami);
SecretKeySpec sKeySpec = new SecretKeySpec(keyb, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
byte[] bjiemihou = cipher.doFinal(miwen);
System.out.println(new String(bjiemihou));
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值