AES加密解密
AES加密解密
AES?加密解密和?DES?加密解密代碼一樣,只需要修改加密算法就行,拷貝?ESC?代碼
AesDemo.java
package com.atguigu.desaes;import com.sun.org.apache.xml.internal.security.utils.Base64;import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec;/*** DesAesDemo* 對稱加密*/ public class AesDemo {public static void main(String[] args) throws Exception{// 原文String input = "止兮666";// 定義key// 如果使用des進行加密,那么密鑰必須是8個字節// 如果使用的是AES加密,那么密鑰必須是16個字節String key = "1234567812345678";// 算法String transformation = "AES";// 加密類型String algorithm = "AES";// 指定獲取密鑰的算法String encryptDES = encryptDES(input, key, transformation, algorithm);System.out.println("加密:" + encryptDES);// String s = decryptDES(encryptDES, key, transformation, algorithm); // System.out.println("解密:" + s);}/*** 解密* @param encryptDES 密文* @param key 密鑰* @param transformation 加密算法* @param algorithm 加密類型* @return*/private static String decryptDES(String encryptDES, String key, String transformation, String algorithm) throws Exception{Cipher cipher = Cipher.getInstance(transformation);SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(),algorithm);//Cipher.DECRYPT_MODE:表示解密// 解密規則cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);// 解密,傳入密文byte[] bytes = cipher.doFinal(Base64.decode(encryptDES));return new String(bytes);}/*** 使用DES加密數據** @param input : 原文* @param key : 密鑰(DES,密鑰的長度必須是8個字節)* @param transformation : 獲取Cipher對象的算法* @param algorithm : 獲取密鑰的算法* @return : 密文* @throws Exception*/private static String encryptDES(String input, String key, String transformation, String algorithm) throws Exception {// 獲取加密對象Cipher cipher = Cipher.getInstance(transformation);// 創建加密規則// 第一個參數key的字節// 第二個參數表示加密算法SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);// ENCRYPT_MODE:加密模式// DECRYPT_MODE: 解密模式// 初始化加密模式和算法cipher.init(Cipher.ENCRYPT_MODE,sks);// 加密byte[] bytes = cipher.doFinal(input.getBytes());// 輸出加密后的數據String encode = Base64.encode(bytes);return encode;} } 《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: toString()与new Strin
- 下一篇: 加密模式||填充模式