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)簡單實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.