All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.opencodes.utils.AESUtils Maven / Gradle / Ivy

The newest version!
package cn.opencodes.utils;

import java.security.Security;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class AESUtils {
	
	/**
     * 加密 AES-256
     * @param decryptCode 待加密内容
     * @param key 密钥
     */
	public static String encryptByAES(String content, String password) throws Exception {
		try {  
			SecretKey key = new SecretKeySpec(password.getBytes(), "AES"); 
            Security.addProvider(new BouncyCastleProvider());  
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");  
            cipher.init(Cipher.ENCRYPT_MODE, key);  
            byte[] byteContent = content.getBytes("utf-8");  
            byte[] cryptograph = cipher.doFinal(byteContent);  
            return Base64.getEncoder().encodeToString(cryptograph);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
	}
	
	
    /**
     * 解密 AES-256
     * @param decryptCode 待解密内容
     * @param key 密钥
     * @return
     */
    public static String decryptByAES(String decryptCode, String key) throws Exception {
    	byte[] data = Base64.getDecoder().decode(decryptCode);
    	SecretKey secretKey = new SecretKeySpec(key.getBytes(), "AES");
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        return new String(cipher.doFinal(data), "UTF-8");
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy