Java AES的加密与解密

1 篇文章 0 订阅
1 篇文章 0 订阅



//此工具类可以在linux和windows环境下运行,解决了liunx下中文文件乱码的问题

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
 
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
 
/**
 * 
 * @author Ylca
 * 
 */
public class AesUtilT {
 
	/**
	 * 加密字符串
	 * 
	 * @param content 需要加密的内容
	 * @param password 密码
	 * @return
	 */
	public static byte[] encrypt(String content, String sKey) {
		try {
			// 初始化 加密器
			Cipher cipher = initAESCipher(sKey, Cipher.ENCRYPT_MODE);
			byte[] byteContent = content.getBytes("utf-8");
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}
 
	/**
	 * 解密字符串
	 * 
	 * @param content 
	 * @param password
	 * @return
	 */
	public static byte[] decrypt(byte[] content, String sKey) {
		try {
			// 初始化 加密器
			Cipher cipher = initAESCipher(sKey, Cipher.DECRYPT_MODE);
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}
 
	/**
	 * 对文件进行AES加密
	 * 
	 * @param sourceFile
	 * @param fileType
	 * @param sKey
	 * @return
	 */
	public static File encryptFile(File sourceFile, File encrypfile, String sKey) {
 
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			inputStream = new FileInputStream(sourceFile);
 
			outputStream = new FileOutputStream(encrypfile);
			Cipher cipher = initAESCipher(sKey, Cipher.ENCRYPT_MODE);
			// 以加密流写入文件
			CipherInputStream cipherInputStream = new CipherInputStream(
					inputStream, cipher);
			byte[] cache = new byte[1024];
			int nRead = 0;
			while ((nRead = cipherInputStream.read(cache)) != -1) {
				outputStream.write(cache, 0, nRead);
				outputStream.flush();
			}
			cipherInputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		} catch (IOException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace(); // To change body of catch statement use
										// File | Settings | File Templates.
			}
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace(); // To change body of catch statement use
										// File | Settings | File Templates.
			}
		}
		return encrypfile;
	}
 
 
	/**
	 *  AES方式解密文件
	 * @param sourceFile 要解密的文件路径
	 * @param decryptFile 解密后的文件路径
	 * @param sKey
	 * @return
	 */
	public static File decryptFile(File sourceFile, File decryptFile,
			String sKey) {
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			Cipher cipher = initAESCipher(sKey, Cipher.DECRYPT_MODE);
			inputStream = new FileInputStream(sourceFile);
			outputStream = new FileOutputStream(decryptFile);
			
			
			CipherOutputStream cipherOutputStream = new CipherOutputStream(
					outputStream, cipher);
			byte[] buffer = new byte[1024];
			int r;
			while ((r = inputStream.read(buffer)) >= 0) {
				cipherOutputStream.write(buffer, 0, r);
			}
			cipherOutputStream.close();
		} catch (IOException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		} finally {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace(); // To change body of catch statement use
										// File | Settings | File Templates.
			}
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace(); // To change body of catch statement use
										// File | Settings | File Templates.
			}
		}
		return decryptFile;
	}
 
	/**
	 * 初始化 AES Cipher
	 * 
	 * @param sKey
	 * @param cipherMode
	 * @return
	 */
	public static Cipher initAESCipher(String sKey, int cipherMode) {
		// 创建Key gen
		Cipher cipher = null;
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
        	SecureRandom random=null;
        	try {
        	random = SecureRandom.getInstance("SHA1PRNG","SUN");
        	} catch (NoSuchProviderException e1) {
        	// TODO Auto-generated catch block
        	e1.printStackTrace();
        	}
        	random.setSeed(sKey.getBytes());
        	kgen.init(128, random);
			SecretKey secretKey = kgen.generateKey();
			byte[] codeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(codeFormat, "AES");
			cipher = Cipher.getInstance("AES");
			// 初始化
			cipher.init(cipherMode, key);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		} catch (NoSuchPaddingException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		} catch (InvalidKeyException e) {
			e.printStackTrace(); // To change body of catch statement use File |
									// Settings | File Templates.
		}
		return cipher;
	}
 
//	public static void main(String[] args) throws Exception {
//		
//		String cKey = "00b09e37363e596e1f25b23c78e49939238b";
//		//未加密文件路径
//		File oldfile = new File("C:\\Users\\Administrator\\Desktop\\1.mp4");
//		//加密后的文件路径
//		File encrypfile = new File("C:\\Users\\Administrator\\Desktop\\encryp.mp4");
//		//解密后的文件路径
//		File decrypfile  = new File("C:\\Users\\Administrator\\Desktop\\decryp.mp4");
//		//加密文件
//		encryptFile(oldfile,encrypfile,cKey);
//		//解密文件
//		decryptFile(encrypfile, decrypfile,cKey);
//	}
	}

感谢以下作者的支持:

AES 文件加密和字符串加密 JAVA版_Ylca Csdn Blog-CSDN博客

AES加密解密Windows下跟linux下结果不同的解决方案_自爆的糖果-CSDN博客

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用javax.crypto包中的类来进行AES加密解密。具体实现步骤如下: 1. 生成一个AES密钥 ``` KeyGenerator keygen = KeyGenerator.getInstance("AES"); keygen.init(128); SecretKey key = keygen.generateKey(); ``` 2. 创建Cipher对象,并初始化为加密模式或解密模式 ``` Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key); ``` 3. 加密/解密数据 ``` byte[] ciphertext = cipher.doFinal(plaintext); byte[] plaintext = cipher.doFinal(ciphertext); ``` 完整代码示例: ``` import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class AESUtil { private static final String CHARSET_NAME = "UTF-8"; private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding"; /** * 随机生成AES密钥 * * @param keySize 密钥长度,单位:位 * @return 生成的密钥 * @throws NoSuchAlgorithmException 异常 */ public static byte[] generateKey(int keySize) throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(keySize); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } /** * AES加密 * * @param plaintext 明文 * @param key 密钥 * @param iv 初始化向量 * @return 密文 * @throws NoSuchPaddingException 异常 * @throws NoSuchAlgorithmException 异常 * @throws InvalidAlgorithmParameterException 异常 * @throws InvalidKeyException 异常 * @throws BadPaddingException 异常 * @throws IllegalBlockSizeException 异常 */ public static byte[] encrypt(byte[] plaintext, byte[] key, byte[] iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(iv)); return cipher.doFinal(plaintext); } /** * AES解密 * * @param ciphertext 密文 * @param key 密钥 * @param iv 初始化向量 * @return 明文 * @throws NoSuchPaddingException 异常 * @throws NoSuchAlgorithmException 异常 * @throws InvalidAlgorithmParameterException 异常 * @throws InvalidKeyException 异常 * @throws BadPaddingException 异常 * @throws IllegalBlockSizeException 异常 */ public static byte[] decrypt(byte[] ciphertext, byte[] key, byte[] iv) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance(AES_ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(iv)); return cipher.doFinal(ciphertext); } /** * 生成随机的初始化向量 * * @param ivSize 初始化向量长度,单位:位 * @return 生成的初始化向量 */ public static byte[] generateIv(int ivSize) { byte[] iv = new byte[ivSize / 8]; new SecureRandom().nextBytes(iv); return iv; } /** * 将字节数组换为十六进制字符串 * * @param bytes 字节数组 * @return 十六进制字符串 */ public static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(bytes.length * 2); for (byte b : bytes) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); } /** * 将十六进制字符串换为字节数组 * * @param hexString 十六进制字符串 * @return 字节数组 */ public static byte[] toByteArray(String hexString) { int len = hexString.length() / 2; byte[] bytes = new byte[len]; for (int i = 0; i < len; i++) { int index = i * 2; bytes[i] = (byte) Integer.parseInt(hexString.substring(index, index + 2), 16); } return bytes; } public static void main(String[] args) throws Exception { // 随机生成16字节的AES密钥和16字节的初始化向量 byte[] key = generateKey(128); byte[] iv = generateIv(128); String plaintextStr = "hello, AES!"; byte[] plaintext = plaintextStr.getBytes(CHARSET_NAME); // AES加密 byte[] ciphertext = encrypt(plaintext, key, iv); String ciphertextHex = toHexString(ciphertext); System.out.println("密文:" + ciphertextHex); // AES解密 byte[] ciphertextBytes = toByteArray(ciphertextHex); byte[] decrypted = decrypt(ciphertextBytes, key, iv); String decryptedStr = new String(decrypted, CHARSET_NAME); System.out.println("明文:" + decryptedStr); } } 相关问题:

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值