Java笔记-对称加密AES的使用
生活随笔
收集整理的這篇文章主要介紹了
Java笔记-对称加密AES的使用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
AES加密庫(kù)的使用:
? ? ·根據(jù)AES密鑰創(chuàng)建Secret密鑰向量;
? ? ·生成初始化參數(shù)向量;
? ? ·獲取AES Cipher;
? ? ·執(zhí)行加密;
? ? ·Base64編碼(建議)
程序運(yùn)行截圖如下:
?調(diào)用如下:
public static void main(String[] args) throws UnsupportedEncodingException {String content = "123456";AES aes = new AES();byte[] encrypted = aes.encrypt(content);System.out.println(new String(encrypted));............ }AES.java
package cn.it1995.tool;import javax.crypto.*; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom;//AES沒(méi)有公鑰和私鑰之分 public class AES {private SecretKey mKey;public AES(){try {KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");//創(chuàng)建隨機(jī)密碼,并設(shè)置種子SecureRandom secureRandom = new SecureRandom();secureRandom.setSeed(System.currentTimeMillis());//初始化密鑰對(duì)象keyGenerator.init(128, secureRandom);mKey = keyGenerator.generateKey();}catch (NoSuchAlgorithmException e) {e.printStackTrace();}}public byte[] encrypt(String content){if(mKey == null){return new byte[]{-1};}try {Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.ENCRYPT_MODE, mKey);return cipher.doFinal(content.getBytes());}catch (NoSuchAlgorithmException e) {e.printStackTrace();}catch (NoSuchPaddingException e) {e.printStackTrace();}catch (BadPaddingException e) {e.printStackTrace();}catch (IllegalBlockSizeException e) {e.printStackTrace();}catch (InvalidKeyException e) {e.printStackTrace();}return new byte[]{-1};}public byte[] decrypt(byte[] content){if(mKey == null){return new byte[]{-1};}try {Cipher cipher = Cipher.getInstance("AES");cipher.init(Cipher.DECRYPT_MODE, mKey);return cipher.doFinal(content);}catch (NoSuchAlgorithmException e) {e.printStackTrace();}catch (NoSuchPaddingException e) {e.printStackTrace();}catch (BadPaddingException e) {e.printStackTrace();}catch (IllegalBlockSizeException e) {e.printStackTrace();}catch (InvalidKeyException e) {e.printStackTrace();}return new byte[]{-1};} }總結(jié)
以上是生活随笔為你收集整理的Java笔记-对称加密AES的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 信息安全工程师-AES密码技术及XOR图
- 下一篇: Qt文档阅读笔记-Threaded Fo