AES256-GCM-NOPADDING安全加密解密
import org.apache.commons.codec.binary.Hex;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.GCMParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Set;
/**
* @author: mek
* Date: 2023-2-6
* Time: 8:40
* vx: 250023777
* Description: AES_256/GCM/NOPADDING加解密
* @version: 1.0
*/
public class AES256GCMUtil {
private final static String ALGO = "AES_256/GCM/NOPADDING";
public static final int AES_KEY_SIZE = 256;
public static final int GCM_IV_LENGTH = 12;
public static final int TLEN = 128;
static {
Set<String> algorithms = Security.getAlgorithms("Cipher");
if (!algorithms.contains(ALGO)) {
throw new IllegalArgumentException("AES256加解密系统不可用");
}
}
public String encrypt(String txt, String pwd) throws Exception {
Cipher cipher = Cipher.getInstance(ALGO);
byte[] iv = new byte[GCM_IV_LENGTH];
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextBytes(iv);
cipher.init(Cipher.ENCRYPT_MODE, generateKey(pwd), new GCMParameterSpec(TLEN, iv));
//iv和加密后的字节数组进行组合(用于解密时获取iv和加密内容)
byte[] txtBytes = txt.getBytes(StandardCharsets.UTF_8);
byte[] enctyptBytes = cipher.doFinal(txtBytes);
byte[] message = new byte[GCM_IV_LENGTH + enctyptBytes.length];
System.arraycopy(iv, 0, message, 0, GCM_IV_LENGTH);
System.arraycopy(enctyptBytes, 0, message, GCM_IV_LENGTH, enctyptBytes.length);
return Hex.encodeHexString(message);
}
public String decrypt(String txt, String pwd) throws Exception {
//分离iv和加密内容
byte[] txtBytes = Hex.decodeHex(txt.toCharArray());
byte[] iv = new byte[GCM_IV_LENGTH];
byte[] content = new byte[txtBytes.length - GCM_IV_LENGTH];
System.arraycopy(txtBytes, 0, iv, 0, GCM_IV_LENGTH);
System.arraycopy(txtBytes, GCM_IV_LENGTH, content, 0, content.length);
Cipher cipher = Cipher.getInstance(ALGO);
GCMParameterSpec params = new GCMParameterSpec(TLEN, iv);
cipher.init(Cipher.DECRYPT_MODE, generateKey(pwd), params);
return new String(cipher.doFinal(content), StandardCharsets.UTF_8);
}
public Key generateKey(String keystr) throws Exception {
KeyGenerator kg = KeyGenerator.getInstance("AES");
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG", "SUN");
secureRandom.setSeed(keystr.getBytes(StandardCharsets.UTF_8));
kg.init(AES_KEY_SIZE, secureRandom);
return kg.generateKey();
}
public static void main(String[] args) throws Exception {
//test
AES256GCMUtil app = new AES256GCMUtil();
String content = "小白痴,stupid:666+-*/";
String encryptStr = app.encrypt(content, "aaaa");
System.out.println("原始内容:" + content);
System.out.println("加密内容:" + encryptStr);
System.out.println("解密内容:" + app.decrypt(encryptStr, "aaaa"));
}
}
- 运行结果
原始内容:小白痴,stupid:666+-*/
加密内容:0d1cb615a90a174d9a7d27fdd697c22f9e620c07914768a570b86c67132299749122d2d6fb38d0d34bcf1d56d1fb4431b51524d8adf7
解密内容:小白痴,stupid:666+-*/
感觉有帮助的就点个赞呗。