栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

AES对称加密工具类(GCM)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

AES对称加密工具类(GCM)

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.springframework.security.crypto.keygen.KeyGenerators;
import org.springframework.util.Base64Utils;


public class AESUtils {

	public static byte[] encryptGCM(byte[] data, byte[] key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
	    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
	    GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, key);
	    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
	    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmParameterSpec);
	    byte[] result = cipher.doFinal(data);
	    return result;
	}

	public static byte[] decryptGCM(byte[] data, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException {
	    SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
	    GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, key);
		Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
	    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec);
	    byte[] result = cipher.doFinal(data);
	    return result;
	}

	public static void main(String[] args) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException {
	    String data = "Hello World"; // 待加密的原文
	    byte[] key = KeyGenerators.secureRandom(32).generateKey();
	    byte[] ciphertext = AESUtils.encryptGCM(data.getBytes(), key);
	    System.out.println("GCM 模式加密结果(Base64):" + Base64Utils.encodeToString(ciphertext));
	    byte[] plaintext = AESUtils.decryptGCM(ciphertext, key);
	    System.out.println("解密结果:" + new String(plaintext));
		 
	}
} 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/914833.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号