使用AES完成对字符串的加密

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.KeyGenerator;
import javax.crypto.Cipher;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

public class AESTest {
	static final String ALGORITHM = "AES";
	public static SecretKey secretKey() throws NoSuchAlgorithmException{
		KeyGenerator  keygenerator = KeyGenerator.getInstance(ALGORITHM);
		SecureRandom  securerandom = new SecureRandom();
		keygenerator.init(securerandom); //对密钥生成器进行初始化,将随机数生成器传进去
		SecretKey secretkey = keygenerator.generateKey(); //生成key
		return secretkey;
	}
	//final static String charsetName = "UTF-8";
    //static Charset charset = Charset.forName("UTF-8");
	public static byte[] encrypt(String content,SecretKey secretkey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
		return aes(content.getBytes(),Cipher.ENCRYPT_MODE,secretkey);
	}
	public static String decrypt(byte[] contentArray,SecretKey secretkey) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
		byte[] result2 = aes(contentArray,Cipher.DECRYPT_MODE,secretkey);
		return new String(result2);
	}
	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 = "123";
		try {
			SecretKey key = secretKey();
			byte[] encryptResult = encrypt(content,key);
			System.out.println("加密后的结果为:"+new String(encryptResult));
			String decryptResult = decrypt(encryptResult,key);
			System.out.println("解密后的结果为:"+decryptResult);
		} catch (NoSuchAlgorithmException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成 catch 块
			e.printStackTrace();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/aaqian1/article/details/89413668