import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class AESHelper {
? ? /**
? ? * AES加密
? ? *
? ? * @param value 明文
? ? * @param key? 密鑰
? ? * @return 密文
? ? */
? ? public static String encrypt(String value, String key) {
? ? ? ? try {
? ? ? ? ? ? KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
? ? ? ? ? ? keyGenerator.init(128, new SecureRandom(key.getBytes()));
? ? ? ? ? ? SecretKey secretKey = keyGenerator.generateKey();
? ? ? ? ? ? byte[] enCodeFormat = secretKey.getEncoded();
? ? ? ? ? ? SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
? ? ? ? ? ? Cipher cipher = Cipher.getInstance("AES");
? ? ? ? ? ? cipher.init(Cipher.ENCRYPT_MODE, keySpec);
? ? ? ? ? ? return new String(cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? return null;
? ? }
? ? /**
? ? * AES解密
? ? *
? ? * @param value 密文
? ? * @param key? 密鑰
? ? * @return 明文
? ? */
? ? public static String decrypt(String value, String key) {
? ? ? ? try {
? ? ? ? ? ? KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
? ? ? ? ? ? keyGenerator.init(128, new SecureRandom(key.getBytes()));
? ? ? ? ? ? SecretKey secretKey = keyGenerator.generateKey();
? ? ? ? ? ? byte[] enCodeFormat = secretKey.getEncoded();
? ? ? ? ? ? SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
? ? ? ? ? ? Cipher cipher = Cipher.getInstance("AES");
? ? ? ? ? ? cipher.init(Cipher.DECRYPT_MODE, keySpec);
? ? ? ? ? ? return new String(cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? return null;
? ? }
}
AES加解密方法
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 密碼學(xué)中的高級加密標(biāo)準(zhǔn)(Advanced Encryption Standard,AES),又稱Rijndael加...
- 1、不安全的隨機(jī)數(shù)生成,在CSRF TOKEN生成、password reset token生成等,會(huì)造成toke...
- 今天上午讓做一個(gè)ase的加密,從網(wǎng)上找了好多都是支持windows的,在Linux下運(yùn)行時(shí)解密時(shí),總是出現(xiàn)報(bào)這個(gè)異...
- 伴隨著密碼學(xué),計(jì)算機(jī)技術(shù),互聯(lián)網(wǎng)絡(luò),商業(yè),經(jīng)濟(jì)學(xué),博弈論,金融,法律,社會(huì)學(xué)等多學(xué)科融合,BTC經(jīng)過半個(gè)多世紀(jì)的孕...