package com.zyhao.openec.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class MainTest {
//AES:高级加密标准,新一代标准,加密速度更快,安全性更高(不用说优先选择)
public static void main(String[] args) throws Exception {
String aesKey = getKey();
System.out.println(aesKey);
// //加密
String oriString = "我是加密的原文:hello world|hi!";
byte[] oriText = oriString.getBytes();
byte[] be = getAESEncode(hexStringToBytes(aesKey),oriText);
String encodeString = byteToHexString(be);
System.out.println(encodeString);
//解密
byte[] encodeByte=hexStringToBytes(encodeString);
byte[] bd = getAESDecode(hexStringToBytes(aesKey),encodeByte);
System.out.println(new String(bd));
}
/**
* AES生成密钥
* 自动生成AES128位密钥
* 传入保存密钥文件路径
* filePath 表示文件存储路径加文件名;例如d:\aes.txt
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static byte[] getAutoCreateAESKey() throws NoSuchAlgorithmException, IOException{
KeyGenerator kg = KeyGenerator.getInstance("AES");
kg.init(128);//要生成多少位,只需要修改这里即可128, 192或256
SecretKey sk = kg.generateKey();
byte[] b = sk.getEncoded();
return b;
}
/**
* 加密
* 使用对称密钥进行加密
* keyFilePath 密钥存放路径
* text 要加密的字节数组
* 加密后返回一个字节数组
* @throws IOException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static byte[] getAESEncode(byte[] key,byte[] text) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
byte[] bjiamihou = cipher.doFinal(text);
return bjiamihou;
}
/**
* 解密
* 使用对称密钥进行解密
* keyFilePath 密钥存放路径
* text 要解密的字节数组
* 解密后返回一个字节数组
* @throws IOException
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static byte[] getAESDecode(byte[] key,byte[] text) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
SecretKeySpec sKeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
byte[] bjiemihou = cipher.doFinal(text);
return bjiemihou;
}
/**
* 随机生成秘钥
*/
public static String 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);
return s;
}catch (NoSuchAlgorithmException e) {
e.printStackTrace();
System.out.println("没有此算法。");
}
return null;
}
// /**
// * 使用指定的字符串生成秘钥
// */
// 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();
}
/**
* Convert hex string to byte[]
* @param hexString the hex string
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
* @param c char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。