0


AES256-GCM-NOPADDING加密解密(java)

AES256-GCM-NOPADDING安全加密解密

importorg.apache.commons.codec.binary.Hex;importjavax.crypto.Cipher;importjavax.crypto.KeyGenerator;importjavax.crypto.spec.GCMParameterSpec;importjava.nio.charset.StandardCharsets;importjava.security.Key;importjava.security.SecureRandom;importjava.security.Security;importjava.util.Set;/**
 * @author: mek
 * Date: 2023-2-6
 * Time: 8:40
 * vx: 250023777
 * Description: AES_256/GCM/NOPADDING加解密
 * @version: 1.0
 */publicclassAES256GCMUtil{privatefinalstaticStringALGO="AES_256/GCM/NOPADDING";publicstaticfinalintAES_KEY_SIZE=256;publicstaticfinalintGCM_IV_LENGTH=12;publicstaticfinalintTLEN=128;static{Set<String> algorithms =Security.getAlgorithms("Cipher");if(!algorithms.contains(ALGO)){thrownewIllegalArgumentException("AES256加解密系统不可用");}}publicStringencrypt(String txt,String pwd)throwsException{Cipher cipher =Cipher.getInstance(ALGO);byte[] iv =newbyte[GCM_IV_LENGTH];SecureRandom secureRandom =newSecureRandom();
        secureRandom.nextBytes(iv);
        cipher.init(Cipher.ENCRYPT_MODE,generateKey(pwd),newGCMParameterSpec(TLEN, iv));//iv和加密后的字节数组进行组合(用于解密时获取iv和加密内容)byte[] txtBytes = txt.getBytes(StandardCharsets.UTF_8);byte[] enctyptBytes = cipher.doFinal(txtBytes);byte[] message =newbyte[GCM_IV_LENGTH+ enctyptBytes.length];System.arraycopy(iv,0, message,0,GCM_IV_LENGTH);System.arraycopy(enctyptBytes,0, message,GCM_IV_LENGTH, enctyptBytes.length);returnHex.encodeHexString(message);}publicStringdecrypt(String txt,String pwd)throwsException{//分离iv和加密内容byte[] txtBytes =Hex.decodeHex(txt.toCharArray());byte[] iv =newbyte[GCM_IV_LENGTH];byte[] content =newbyte[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 =newGCMParameterSpec(TLEN, iv);
        cipher.init(Cipher.DECRYPT_MODE,generateKey(pwd), params);returnnewString(cipher.doFinal(content),StandardCharsets.UTF_8);}publicKeygenerateKey(String keystr)throwsException{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();}publicstaticvoidmain(String[] args)throwsException{//testAES256GCMUtil app =newAES256GCMUtil();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+-*/

感觉有帮助的就点个赞呗。

标签: java 安全

本文转载自: https://blog.csdn.net/mek1986/article/details/128903537
版权归原作者 if...else... 所有, 如有侵权,请联系我们删除。

“AES256-GCM-NOPADDING加密解密(java)”的评论:

还没有评论