JAVA實現AES機密解密算法

package com.cn.ssm.test;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;

public class AESTest {
	
	static final String ALGORITHM = "AES";
	static final String CHARSET_NAME = "utf-8";
	static Charset charset = Charset.forName(CHARSET_NAME);
	
	public static SecretKey generateKay() throws NoSuchAlgorithmException {
		
		KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
		SecureRandom secureRandom = new SecureRandom();
		keyGenerator.init(secureRandom);
		SecretKey secretKey = keyGenerator.generateKey();
		
		return secretKey;
		
	}
	
	public static byte[] encrypt(String content, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
		return aes(content.getBytes(charset), Cipher.ENCRYPT_MODE, secretKey);
		
	}
	
	public static String decrypt(byte[] contentArray, SecretKey secretKey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
		
		byte[] result = aes(contentArray, Cipher.DECRYPT_MODE, secretKey);
		return new String(result,CHARSET_NAME);
		
	}
	
	public static byte[] aes(byte[] contentArray, int mode, SecretKey secretKey) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		Cipher cipher = Cipher.getInstance(ALGORITHM);
		cipher.init(mode, secretKey);
		byte[] result = cipher.doFinal(contentArray);
		
		return result;
		
	}
	
	public static void main(String[] args) {
		
		String content = "hshj加密解密你好啊377843843";
		try {
			
			SecretKey secretKey = generateKay();
			byte[] encryptResult = encrypt(content, secretKey);
			String decryptResult = decrypt(encryptResult, secretKey);
			
			System.out.println("加密後的結果==》"+encryptResult);
			System.out.println("解密後的結果==》"+decryptResult);
			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
	}
	
	

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章