1. 程式人生 > >Java AES256加密解密工具類

Java AES256加密解密工具類

package com.firebug.util;

import it.sauronsoftware.base64.Base64;  

import java.security.MessageDigest;  
import java.security.NoSuchAlgorithmException;  
import java.security.SecureRandom;  
import java.security.Security;  
 
import javax.crypto.Cipher;  
import javax.crypto.KeyGenerator;  
import javax.crypto.SecretKey;  
import javax.crypto.spec.SecretKeySpec;  
 
import org.bouncycastle.jce.provider.BouncyCastleProvider;  

public class AES256Util {

    public static byte[] encrypt(String content, String password) {  
        try {  
            //"AES":請求的金鑰演算法的標準名稱  
            KeyGenerator kgen = KeyGenerator.getInstance("AES");  
            //256:金鑰生成引數;securerandom:金鑰生成器的隨機源  
            SecureRandom securerandom = new SecureRandom(tohash256Deal(password));  
            kgen.init(256, securerandom);  
            //生成祕密(對稱)金鑰  
            SecretKey secretKey = kgen.generateKey();  
            //返回基本編碼格式的金鑰  
            byte[] enCodeFormat = secretKey.getEncoded();  
            //根據給定的位元組陣列構造一個金鑰。enCodeFormat:金鑰內容;"AES":與給定的金鑰內容相關聯的金鑰演算法的名稱  
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  
            //將提供程式新增到下一個可用位置  
            Security.addProvider(new BouncyCastleProvider());  
            //建立一個實現指定轉換的 Cipher物件,該轉換由指定的提供程式提供。  
            //"AES/ECB/PKCS7Padding":轉換的名稱;"BC":提供程式的名稱  
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");  
 
            cipher.init(Cipher.ENCRYPT_MODE, key);  
            byte[] byteContent = content.getBytes("utf-8");  
            byte[] cryptograph = cipher.doFinal(byteContent);  
            return Base64.encode(cryptograph);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
 
    public static String decrypt(byte[] cryptograph, String password) {  
        try {  
            KeyGenerator kgen = KeyGenerator.getInstance("AES");  
            SecureRandom securerandom = new SecureRandom(tohash256Deal(password));  
            kgen.init(256, securerandom);  
            SecretKey secretKey = kgen.generateKey();  
            byte[] enCodeFormat = secretKey.getEncoded();  
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");  
            Security.addProvider(new BouncyCastleProvider());  
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");  
 
            cipher.init(Cipher.DECRYPT_MODE, key);  
            byte[] content = cipher.doFinal(Base64.decode(cryptograph));  
            return new String(content);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
 
    private static String parseByte2HexStr(byte buf[]) {  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < buf.length; i++) {  
            String hex = Integer.toHexString(buf[i] & 0xFF);  
            if (hex.length() == 1) {  
                hex = '0' + hex;  
            }  
            sb.append(hex.toUpperCase());  
        }  
        return sb.toString();  
    }  
      
    private static byte[] tohash256Deal(String datastr) {  
        try {  
            MessageDigest digester=MessageDigest.getInstance("SHA-256");  
            digester.update(datastr.getBytes());  
            byte[] hex=digester.digest();  
            return hex;   
        } catch (NoSuchAlgorithmException e) {  
            throw new RuntimeException(e.getMessage());    
        }  
    }  
      
    public static void main(String[] args) {  
 
        String content = "我是待加密的文字";  
        String password = "123456";  
        System.out.println("明文:" + content);  
        System.out.println("key:" + password);  
          
        byte[] encryptResult = AES256Util.encrypt(content, password);  
        System.out.println("密文:" + AES256Util.parseByte2HexStr(encryptResult));  
          
        String decryptResult = AES256Util.decrypt(encryptResult, password);  
        System.out.println("解密:" + decryptResult);  
    }

}

//refer: https://blog.csdn.net/z69183787/article/details/78043762

//原始碼及其所需jar包下載:https://download.csdn.net/download/qq_37122091/10513591