AES加密和解密
AES?加密解密和?DES?加密解密代碼一樣,只需要修改加密算法就行,拷貝?ESC?代碼
package com.leon.desaes; import com.sun.org.apache.xml.internal.security.utils.Base64;import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec;public class AesDemo {// DES加密算法,key的大小必須是8個字節public static void main(String[] args) throws Exception {String input ="硅谷";// AES加密算法,比較高級,所以key的大小必須是16個字節String key = "1234567812345678";String transformation = "AES"; // 9PQXVUIhaaQ=// 指定獲取密鑰的算法String algorithm = "AES";// 先測試加密,然后在測試解密String encryptDES = encryptDES(input, key, transformation, algorithm);System.out.println("加密:" + encryptDES);String s = dncryptDES(encryptDES, key, transformation, algorithm);System.out.println("解密:" + s);}/*** 使用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;}/*** 使用DES解密** @param input : 密文* @param key : 密鑰* @param transformation : 獲取Cipher對象的算法* @param algorithm : 獲取密鑰的算法* @throws Exception* @return: 原文*/private static String dncryptDES(String input, String key, String transformation, String algorithm) throws Exception {// 1,獲取Cipher對象Cipher cipher = Cipher.getInstance(transformation);// 指定密鑰規則SecretKeySpec sks = new SecretKeySpec(key.getBytes(), algorithm);cipher.init(Cipher.DECRYPT_MODE, sks);// 3. 解密byte[] bytes = cipher.doFinal(Base64.decode(input));return new String(bytes);} }?
總結
 
                            
                        - 上一篇: toString和newString的原
- 下一篇: 加密模式和填充模式
