java 之 加密解密学习示例

本文介绍了一个使用Java实现的AES对称加密与解密的具体案例,包括生成密钥、加密数据并将其保存至文件,以及从文件中读取密钥进行数据解密的全过程。

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

package com.ethan.security;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

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 SecretKeyTest {

	/**
	 * 对称加密---------------》密钥对密钥
	 * key secretKey  
	 * 非对称加密----------------->公钥  私钥
	 * publicKey/PrivateKey
	 * @param args
	 * @throws ClassNotFoundException 
	 * @throws IOException 
	 * @throws BadPaddingException 
	 * @throws IllegalBlockSizeException 
	 * @throws NoSuchPaddingException 
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeyException 
	 */
	public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException, ClassNotFoundException {
		// TODO Auto-generated method stub
		//secretEncrypt();
		secretDecrypt();
	}
	
public static void secretEncrypt() {
	//加密类
	try {
		Cipher cipher = Cipher.getInstance("AES");
		
		//密钥
		SecretKey key = KeyGenerator.getInstance("AES").generateKey();//得到密钥
		
		//1->加密 2->解密 用常量 英文单词表示数字
		cipher.init(Cipher.ENCRYPT_MODE,key);
		
		//把密钥 key写入文件
		FileOutputStream fos = new FileOutputStream("ethan_secret.key");
		ObjectOutputStream oosSecretKey = new ObjectOutputStream(fos);
		oosSecretKey.writeObject(key);
		fos.close();
		
		//把加密结果也写进文件
		
		
		//填充数据
		cipher.update("aaa".getBytes());
		byte[] results = cipher.doFinal();
		
		System.out.println(new String(results));
		
		FileOutputStream fosData = new FileOutputStream("ethan_data.data");
		fosData.write(results);
		fosData.close();
		/*
		 * 直接加密 一句话
		 * cipher.doFinal("aaa".getBytes());
		 */
		
		/*//解密
		cipher.init(Cipher.DECRYPT_MODE, key);
		System.out.println(new String(cipher.doFinal(results)));*/
} catch(Exception e) {
	e.printStackTrace();
}
}

private static void secretDecrypt() throws NoSuchAlgorithmException, NoSuchPaddingException, IOException, ClassNotFoundException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
	//AES 加密的一种算法
	Cipher cipher = Cipher.getInstance("AES");
	
	FileInputStream fisKey = new FileInputStream("ethan_secret.key");
	ObjectInputStream oisKey = new ObjectInputStream(fisKey);

	//读取到 Key 对象 Key-----------is interface
	Key key = (Key) oisKey.readObject();
	 
	oisKey.close();
	fisKey.close();
	
	cipher.init(Cipher.DECRYPT_MODE, key);
	
	//拿到 要解密的内容
	FileInputStream fisDat = new FileInputStream("ethan_data.data");
//	ByteArrayInputStream bais = new ByteArrayInputStream(arg0)
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	copyStream(fisDat,baos);
	/*
	 * 第二种 read 数据的方法
	 * byte[] src = new byte[1024];
	 *int len = fisDat.read(src);
	 * int total = 0;
	 * 下边不能是  while(len!=-1)因为如果read(byte[],offset,len) len=0了,则return 0;
	 * 不等于-1,则进入死循环
	 * while(total<src.length) {
	 * 	total += len;
	 * 从total处 开始接着读 到 src.length-total
	 * 	len = fisDat.read(src,total,src.length-total);
	 *  
	 * }
	 * 
	 * byte[] result = cipher.doFinal(src);
	 * fisDat.close();
	 */
	byte[] result = cipher.doFinal(baos.toByteArray());
	
	//记得关闭流
	fisDat.close();
	baos.close();
	
	System.out.println(new String(result));
}

private static void copyStream(InputStream ips,OutputStream ops) {
	byte[] buffer = new byte[1024];
	int len = 0;
	try {
		while((len=ips.read(buffer))!=-1) {
			ops.write(buffer,0,len);
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}
永远缅怀 张孝祥老师!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值