0
点赞
收藏
分享

微信扫一扫

java安全架构____RSA加密解密


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

import javax.crypto.Cipher;


/**
 * @author God
 * RSA 参考IBM社区,参考WIKI百科
 */
public class RSA {

	//rsa算法
    private static final String ALGORITHM_RSA = "RSA";
    private static final String ALGORITHM_SIGNTURE = "MD5withRSA";
    //明文加密涉及模和指数
    private static final int MODEL_ENCRYPT_MAX=117;
	/**
	 * 生成秘钥对写入到文件
	 * @return
	 */
	public static boolean getKeyPairs() {
		try {
			//初始化秘钥管理器
			KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM_RSA);
			keyPairGenerator.initialize(512);
			KeyPair keyPair = keyPairGenerator.genKeyPair();
			//获取秘钥对
			PublicKey publicKey = keyPair.getPublic();
			PrivateKey privateKey = keyPair.getPrivate();
			
			//直接写入公钥
			ObjectOutputStream out_pub = new ObjectOutputStream(new FileOutputStream("publicKey.key"));
				out_pub.writeObject(publicKey);
				out_pub.close();
System.out.println("生成的公钥内容为_____:\n "+publicKey);
				//直接写入私钥	
			ObjectOutputStream out_pri = new ObjectOutputStream(new FileOutputStream("privateKey.key"));
				out_pri.writeObject(privateKey);
				out_pri.close();
System.out.println("生成的私钥内容为_____:\n "+privateKey);			
			System.out.println("\n生成密钥对成功...");
			return true;
		} catch (java.lang.Exception e) {
			e.printStackTrace();
			return false;
		}
	}  
	
	/**
	 * 使用私钥进行签名
	 * @return
	 */
	public static byte[] SignatureData(String  info){
		byte[] signedbytes=null;
		try {
			//1.读取生成的私钥对明文进行签名
			ObjectInputStream in_pri = new ObjectInputStream(new FileInputStream("privateKey.key"));
			PrivateKey privateKey = (PrivateKey) in_pri.readObject();
			in_pri.close();
			//初始化签名 对明文开始签名
			Signature signature = Signature.getInstance(ALGORITHM_SIGNTURE);
				signature.initSign(privateKey);
				signature.update(info.getBytes());
			// 对信息的数字签名
			signedbytes = signature.sign();
			System.out.println("签名为_____:"+new String(signedbytes));	
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("私钥签名失败....");
		}
		return signedbytes;
	}
	/**
	 * 用公钥进行校验
	 * @return
	 */
	public static boolean checkSignature(String info,byte[] signedbytes){
		try {
			//读取公钥
			ObjectInputStream in_pub=new ObjectInputStream(new FileInputStream("publicKey.key"));
			PublicKey publicKey = (PublicKey) in_pub.readObject();
			Signature signature = Signature.getInstance(ALGORITHM_SIGNTURE);
			signature.initVerify(publicKey);
			signature.update(info.getBytes());
			//签名信息校验
			if (signature.verify(signedbytes)) {
				System.out.println("签名的内容为____:" + info);
				System.out.println("签名文件校验正常....");
				return true;
			} else{
				System.out.println("签名校验失败");
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	/**
	 * 私钥加密数据
	 */
	public static byte[] PriEncode(String info){
		byte[] cipherBytes=null;
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
			//读取公钥
			ObjectInputStream in_pri = new ObjectInputStream(new FileInputStream("privateKey.key"));
			PrivateKey privateKey=(PrivateKey) in_pri.readObject();
			Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
			cipher.init(Cipher.ENCRYPT_MODE, privateKey);
			//
			byte[] infoBytes = info.getBytes();
			int infolength = infoBytes.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] temp=null;
			int iter = 0;
			// 对数据分段加密
			while (infolength - offSet > 0) {
				if (infolength - offSet > MODEL_ENCRYPT_MAX) {
					temp = cipher.doFinal(infoBytes, offSet, MODEL_ENCRYPT_MAX);
				} else {
					temp = cipher.doFinal(infoBytes, offSet, infolength - offSet);
				}
				out.write(temp, 0, temp.length);
				iter++;
				offSet = iter * MODEL_ENCRYPT_MAX;
			}
			cipherBytes = out.toByteArray();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cipherBytes;
	}
	
	/**
	 * 公钥解密数据
	 */
	public static byte[] PubDecode(byte[]cipherBytes){
		byte[]clearBytes=null;
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_RSA);
			//读取公钥
			ObjectInputStream in_pub = new ObjectInputStream(new FileInputStream("publicKey.key"));
			PublicKey publicKey = (PublicKey) in_pub.readObject();
			Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
			cipher.init(Cipher.DECRYPT_MODE, publicKey);
			int cipherBytesLength = cipherBytes.length;
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offSet = 0;
			byte[] temp;
			int iter = 0;
			// 对数据分段解密
			while (cipherBytesLength - offSet > 0) {
				if (cipherBytesLength - offSet > MODEL_ENCRYPT_MAX) {
					temp = cipher.doFinal(cipherBytes, offSet,MODEL_ENCRYPT_MAX);
				} else {
					temp = cipher.doFinal(cipherBytes, offSet, cipherBytesLength	- offSet);
				}
				out.write(temp, 0, temp.length);
				iter++;
				offSet = iter * MODEL_ENCRYPT_MAX;
			}
			clearBytes = out.toByteArray();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return clearBytes;
	}
	
	public static void main(String[] args) {
		//生成RSA秘钥对
		getKeyPairs();
		//私钥进行签名
		String info="老司机开车了";
		SignatureData(info);
		//用公钥进行校验签名
		checkSignature(info, SignatureData(info));
		//私钥加密
		PriEncode(info);
		//公钥解密
		PubDecode(PriEncode(info));
		//解密的信息
		System.out.println(new String(PubDecode(PriEncode(info))));
	}
}

//运行结果

java安全架构____RSA加密解密_安全

//

java安全架构____RSA加密解密_java加密算法_02

//

java安全架构____RSA加密解密_加密_03

举报

相关推荐

0 条评论