java 非对称加密(公钥加密)

我夕

在实际的应用中单单只有对称加密是不够的,更多的时候是对称加密与非对称加密结合使用,非对称加密(公钥加密)特点速度慢、加密和解密的钥匙不相同,加密的方式是:
 * 公钥加密-私钥解密
 * 私钥加密-公钥解密
这两种,这里给大家演示下第一种方式,剩下一种大家自己测试下。
步骤:
得到keyPairGenerator的实例对象,并调用其generateKeyPair()方法创建KeyPair对象。
调用KeyPair对象的getPrivate和getPublic方法,分别得到PrivateKey对象和PublicKey对象。
得到Cipher的实例对象,并调用其init()方法指定PrivateKey对象或PublicKey对象,并指定要进行加密、还是进行解密操作。
调用Cipher对象的doFinal()方法完成加密或解密操作。

代码如下:

package com.study.security;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;

/**
 * 非对称加密-公钥加密
 * 公钥加密-私钥解密
 * 私钥加密-公钥解密
 * @author 我夕
 *
 */
public class PublicSecret {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		publicEncrypt();
		privatecEncrypt();

	}

	/**
	 * 公钥加密
	 * @throws Exception
	 */
	private static void publicEncrypt() throws Exception{
		Cipher cipher=Cipher.getInstance("RSA");
		//产生钥匙对
		KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance("RSA");
		KeyPair keyPair=keyPairGenerator.generateKeyPair();
		PublicKey publicKey= keyPair.getPublic();
		PrivateKey privateKey=keyPair.getPrivate();
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);

		//前面做加密时都是用默认的编码,如果加密的数据是中文会出现乱码,现在改成中文的数据进行测试以下
		byte[] results=cipher.doFinal("我是要被加密的数据!".getBytes("UTF-8"));
		
		//保存密钥,由于是公钥加密,解密时得用私钥,所以这里要对产生的私钥进行存盘
		saveKey(privateKey, "key_public.key");
		saveData(results, "key_pubData.data");
		System.out.println("加密后的数据:"+new String(results));
		
		
	}
	/**
	 * 私钥解密
	 * @throws Exception
	 */
	private static void privatecEncrypt() throws Exception{
		//读取key与data
		Key privateKey=readKey("key_public.key");
		byte[] results=readData("key_pubData.data");
		
		Cipher cipher=Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		//不要忘记了加编码格式,不然乱码
		System.out.println("解密后的数据:"+new String(cipher.doFinal(results),"UTF-8"));
		
		//===================读数据的另一种写法,如以下========================
		
		FileInputStream fis=new FileInputStream("key_pubData.data");
		CipherInputStream cis=new CipherInputStream(fis,cipher);
		ByteArrayOutputStream arrayOutputStream=new ByteArrayOutputStream();
		int len=0;
		byte[] data=new byte[1024];
		while((len=cis.read(data))!=-1){
			arrayOutputStream.write(data, 0, len);
		}
		byte[] result2=arrayOutputStream.toByteArray();
		arrayOutputStream.close();
		cis.close();
		System.out.println("解密后的数据(读取数据的另一种方式):"+new String(result2,"UTF-8"));
		
	}
	/**
	 * 保存数据的方法
	 * @param results
	 * @param dataName
	 * @throws Exception
	 */
	public static void saveData(byte[] results,String dataName)throws Exception{
		FileOutputStream fosData=new FileOutputStream(dataName);
		fosData.write(results);
		fosData.close();
	}
	/**
	 * 读取数据的方法
	 * @param dataName
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] readData(String dataName)throws Exception{
		FileInputStream fisDat= new FileInputStream(dataName);
		
		//读二进制数据
		ByteArrayOutputStream arrayOutputStream=new ByteArrayOutputStream();
		int len=0;
		byte[] data=new byte[1024];
		while((len=fisDat.read(data))!=-1){
			arrayOutputStream.write(data, 0, len);
		}
		byte[] result=arrayOutputStream.toByteArray();
		arrayOutputStream.close();
		
		fisDat.close();
		return result;
		
	}
	/**
	 * 保存密钥的方法
	 * @param key
	 * @param keyName
	 * @throws Exception
	 */
	public static void saveKey(Key key,String keyName) throws Exception{
		FileOutputStream foskey=new FileOutputStream(keyName);
		ObjectOutputStream oos=new ObjectOutputStream(foskey);
		oos.writeObject(key);
		oos.close();
		foskey.close();
	}
	/**
	 * 读取密钥的方法
	 * @param keyName
	 * @return Key
	 * @throws Exception
	 */
	public static Key readKey(String keyName) throws Exception{
		FileInputStream fiskey=new FileInputStream(keyName);
		ObjectInputStream oiskey=new ObjectInputStream(fiskey);
		Key key=(Key)oiskey.readObject();
		oiskey.close();
		fiskey.close();
		return key;
	}

}


运行结果:

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值