Java中使用AES加密的简单示例

本文提供了一个使用AES算法进行加解密的示例代码,并解释了如何配置KeyGenerator和AlgorithmParameterSpec来保护密钥,确保即使密文和算法公开也无法解密。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

整理文件时,发现以前一个例子。加解密经常用到就放到博客上供大家参考。



代码如下,

package com.yq.security;

import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.util.Scanner;

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

public class AESEnDeCrypter {
	public static byte[] iv = new byte[] { 82, 22, 50, 44, -16, 124, -40, -114, -87, -40, 37, 23, -56, 23, -33, 75 };
    
	private static AESEnDeCrypter aes = new AESEnDeCrypter();;
	    
	public static byte[] key1 = new byte[] { -42, 35, 67, -86, 19, 29, -11, 84, 94, 111, 75, -104, 71, 46, 86, -21, -119, 110, -11, -32, -28, 91, -33, -46, 99, 49, 2, 66, -101, -11, -8, 56 };
	    

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Please input plaintext::");
		Scanner scanner = new Scanner(System.in);
		String plaintext = scanner.next();	
		String ciphertext = AESEnDeCrypter.getInstance().encrypt(plaintext);
		
		System.out.print("The ciphertext:");	
		System.out.println(ciphertext);
		
		System.out.print("The decrypted value:");
		System.out.println(AESEnDeCrypter.getInstance().decrypt(ciphertext));
	}

	private AESEnDeCrypter() {

	}

	public static synchronized AESEnDeCrypter getInstance() {
		return aes;
	}
    /*
     * The output of encryption might have some non-text symbol, so convert it to hex. 
     * The final output is like this f3090bd0196b1d4206d78141bd3cb349
     */
	public String encrypt(String plaintext) {

		String str = "";
		try {
		    KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(key1));
			AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
			SecretKey key = kgen.generateKey();
			Cipher ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
			str = asHex(ecipher.doFinal(plaintext.getBytes()));
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		}

		return str;
	}
    
	public String decrypt(String ciphertext) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(key1));
			AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
			SecretKey key = kgen.generateKey();
			Cipher dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
			return new String(dcipher.doFinal(asBin(ciphertext)));
		} catch (BadPaddingException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		}
		return "";
	}

	private String asHex(byte buf[]) {
		StringBuffer strbuf = new StringBuffer(buf.length * 2);
		int i = 0;
        /*
         * 0xFF is 1111,1111,0000,0000. int is 4 bytes. After the & operation, we will know it is larger than 16 or lower then 16
         */
		for (i = 0; i < buf.length; i++) {
			if (((int) buf[i] & 0xff) < 0x10){
				strbuf.append("0");
			}
			strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
		}

		return strbuf.toString();
	}

	private byte[] asBin(String src) {
		if (src.length() < 1){
			return null;
		}

		byte[] encrypted = new byte[src.length() / 2];
		for (int i = 0; i < src.length() / 2; i++) {
			int high = Integer.parseInt(src.substring(i * 2, i * 2 + 1), 16);
			int low = Integer.parseInt(src.substring(i * 2 + 1, i * 2 + 2), 16);

			encrypted[i] = (byte) (high * 16 + low);
		}
		
		return encrypted;
	}
}

注意:你需在配置文件或者hardcode保存你的KeyGenerator,  AlgorithmParameterSpec(这两个就相当于是对称加密算法中的密钥),  一般可以在程序安装时动态生成,然后保存在配置文件中。这样就算得到密文和算法也无法解密出来。

运行效果如下:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值