package util;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
public class AESUtil {
private static final String ALGORITHM = "AES";
private final static String charsetName = "UTF-8";
public static SecretKey generateKey() throws NoSuchAlgorithmException {
KeyGenerator secretGenerator = KeyGenerator.getInstance(ALGORITHM);
SecureRandom secureRandom = new SecureRandom();
secretGenerator.init(secureRandom);
SecretKey secretKey = secretGenerator.generateKey();
return secretKey;
}
private static byte[] saveSecretKey(SecretKey secretKey) {
Base64.Encoder en = Base64.getEncoder();
byte[] key = en.encode(secretKey.getEncoded());
return key;
}
private static SecretKey getSavedSecretKey(byte[] key) {
Base64.Decoder de = Base64.getDecoder();
byte[] dekey = de.decode(key);
SecretKey secretKey = new SecretKeySpec(dekey, ALGORITHM);
return secretKey;
}
private static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(mode, secretKey);
byte[] result = cipher.doFinal(contentArray);
return result;
}
public static byte[] encrypt(String content, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
return aes(content.getBytes(), Cipher.ENCRYPT_MODE, secretKey);
}
public static byte[] encrypt(byte[] content, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException {
return aes(content, Cipher.ENCRYPT_MODE, secretKey);
}
public static String decrypt(byte[] contentArray, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException {
byte[] result = aes(contentArray, Cipher.DECRYPT_MODE, secretKey);
return new String(result, charsetName);
}
public static String decrypt(String contentArray, SecretKey secretKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException {
byte[] result = aes(contentArray.getBytes(), Cipher.DECRYPT_MODE, secretKey);
return new String(result, charsetName);
}
public static void saveKey(SecretKey secretKey, String fileName) throws IOException {
OutputStream outputStream = new FileOutputStream(new File(fileName));
byte[] savedKey = saveSecretKey(secretKey);
outputStream.write(savedKey);
}
public static SecretKey getKey(String filename) throws IOException {
byte[] key = readFromFile(filename);
SecretKey secretKey = getSavedSecretKey(key);
return secretKey;
}
public static byte[] readFromFile(String filename) throws IOException {
FileChannel fc = null;
fc = new RandomAccessFile(filename, "r").getChannel();
MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0,
fc.size()).load();
byte[] result = new byte[(int) fc.size()];
if (byteBuffer.remaining() > 0) {
byteBuffer.get(result, 0, byteBuffer.remaining());
}
byteBuffer.clear();
fc.close();
return result;
}
public static void writeToFile(String filename, byte[] data) throws IOException {
OutputStream outputStream = new FileOutputStream(new File(filename));
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
bufferedOutputStream.write(data);
bufferedOutputStream.close();
}
package jwt_demo;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* Java RSA 加密工具类
* 参考: https://blog.csdn.net/qy20115549/article/details/83105736
*/
class RSAUtils {
/**
* 密钥长度 于原文长度对应 以及越长速度越慢
*/
private final static int KEY_SIZE = 1024;
/**
* 用于封装随机产生的公钥与私钥
*/
private static Map<Integer, String> keyMap = new HashMap<Integer, String>();
/**
* 随机生成密钥对
*
* @throws Exception
*/
public static void genKeyPair() throws Exception {
// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密钥对生成器
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
// 生成一个密钥对,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
// 得到私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
// 得到公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
String publicKeyString = encryptBASE64(publicKey.getEncoded());
// 得到私钥字符串
String privateKeyString = encryptBASE64(privateKey.getEncoded());
// 将公钥和私钥保存到Map
//0表示公钥
keyMap.put(0, publicKeyString);
//1表示私钥
keyMap.put(1, privateKeyString);
}
//编码返回字符串
public static String encryptBASE64(byte[] key) throws Exception {
return Base64.getEncoder().encodeToString(key);
}
//解码返回byte
public static byte[] decryptBASE64(String key) throws Exception {
return Base64.getDecoder().decode(key);
}
/**
* RSA公钥加密
*
* @param str 加密字符串
* @param publicKey 公钥
* @return 密文
* @throws Exception 加密过程中的异常信息
*/
public static String encrypt(String str, String publicKey) throws Exception {
//base64编码的公钥
byte[] decoded = decryptBASE64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = encryptBASE64(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/**
* RSA私钥解密
*
* @param str 加密字符串
* @param privateKey 私钥
* @return 明文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(String str, String privateKey) throws Exception {
//64位解码加密后的字符串
byte[] inputByte = decryptBASE64(str);
//base64编码的私钥
byte[] decoded = decryptBASE64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}
public static void main(String[] args) throws Exception {
long temp = System.currentTimeMillis();
//生成公钥和私钥
genKeyPair();
//加密字符串
System.out.println("公钥:" + keyMap.get(0));
System.out.println("私钥:" + keyMap.get(1));
System.out.println("生成密钥消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
String message = "RSA测试aaa";
System.out.println("原文:" + message);
temp = System.currentTimeMillis();
String messageEn = encrypt(message, keyMap.get(0));
System.out.println("密文:" + messageEn);
System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
temp = System.currentTimeMillis();
String messageDe = decrypt(messageEn, keyMap.get(1));
System.out.println("解密:" + messageDe);
System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒");
}
}
}
AES算法加密(Java)简单实现
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.