java实现RSA秘钥生成、加解密和签名认证

java实现RSA秘钥生成、加解密和签名认证

  • 实现生成公钥私钥
  • 实现秘钥打印输出
  • 实现加密解密、签名认证
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

/**
* @author 作者 :殇雪话诀别
* @version 创建时间:2019年3月24日 下午3:23:26
* 类说明:
*/

public class RSA {
	//生成公钥、私钥对,传入保存路径和名称
	public static void makekeyfile(String pubkeyfile, String privatekeyfile)
			throws NoSuchAlgorithmException, FileNotFoundException, IOException {
		// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		// 初始化密钥对生成器,密钥大小为1024位
		keyPairGen.initialize(1024);
		// 生成一个密钥对,保存在keyPair中
		KeyPair keyPair = keyPairGen.generateKeyPair();
 
		// 得到私钥
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
 
		// 得到公钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		System.out.println("秘钥生成成功。");
		// 生成私钥文件
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(privatekeyfile));
		oos.writeObject(privateKey);
		oos.flush();
		oos.close();
		System.out.println("成功将私钥保存到:"+privatekeyfile);
		
		// 生成公钥文件
		oos = new ObjectOutputStream(new FileOutputStream(pubkeyfile));
		oos.writeObject(publicKey);
		oos.flush();
		oos.close();
		System.out.println("成功将公钥保存到:"+pubkeyfile);
		//输出秘钥
		printKey(publicKey, privateKey);
 
	}
	//输出公钥秘钥内容
	public static void printKey(RSAPublicKey pubkey,RSAPrivateKey prikey) {
		byte[] publicKeyBytes = pubkey.getEncoded();  
        byte[] privateKeyBytes = prikey.getEncoded();
        String pub=Base64.getEncoder().encodeToString(publicKeyBytes);
        String pri=Base64.getEncoder().encodeToString(privateKeyBytes);
        System.out.println("公钥BASE64内容为:"+pub+"\n");
        System.out.println("公钥内容格式化:\n");
		int sub=64;
		for(int i=0;i<pub.length();i+=sub) {
        	if(i+sub<pub.length()) {
        		pub=pub.substring(0, i+sub)+"\n"+pub.substring(i+sub, pub.length());
        		i++;
        	}else {
        		pub+="\n";
        		break;
        	}
        }
		pub="-----BEGIN PUBLIC KEY-----\n"+pub+"-----END PUBLIC KEY-----\n";
		System.out.println(pub);
        System.out.println("私钥BASE64内容为:"+pri+"\n");
        System.out.println("私钥内容格式化:\n");
		for(int i=0;i<pri.length();i+=sub) {
        	if(i+sub<pri.length()) {
        		pri=pri.substring(0, i+sub)+"\n"+pri.substring(i+sub, pri.length());
        		i++;
        	}else {
        		pri+="\n";
        		break;
        	}
        }
		pri="-----BEGIN PRIVATE KEY-----\n"+pri+"-----END PRIVATE KEY-----\n";
		System.out.println(pri);
        
	}
	//从文件中读取公钥内容
	public static RSAPublicKey pubKeyFile(String pubfile) {
		try {
			//读取公钥
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(pubfile));
			RSAPublicKey pubkey = (RSAPublicKey) ois.readObject();
			ois.close();
			System.out.println("读取公钥成功。");
			return pubkey;
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO 自动生成的 catch 块
			System.out.println("转换成秘钥失败");
			e.printStackTrace();
		}
		return null;
	}
	//从文件中读取私钥内容
	public static RSAPrivateKey priKeyFile(String prifile) {
		try {
			//读取私钥
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(prifile));
			RSAPrivateKey prikey = (RSAPrivateKey) ois.readObject();
			ois.close();
			System.out.println("读取私钥成功。");
			return prikey;
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO 自动生成的 catch 块
			System.out.println("转换成秘钥失败");
			e.printStackTrace();
		}
		return null;
	}
	//从文件读取显示私钥内容
	public static void printKryFile(String pubfile,String prifile) {
		RSAPrivateKey prikey=priKeyFile(prifile);
		RSAPublicKey pubkey=pubKeyFile(pubfile);
		printKey(pubkey, prikey);	//调用输出秘钥方法
	}
	
	/**
	 * 加密解密算法
	 * @param k
	 * @param data
	 * @param encrypt
	 *            1 加密 0解密
	 * @return
	 * @throws NoSuchPaddingException
	 * @throws Exception
	 */
	public static byte[] handleData(Key k, byte[] data, int encrypt)
			throws Exception {
 
		if (k != null) {
 
			Cipher cipher = Cipher.getInstance("RSA");
 
			if (encrypt == 1) {
				cipher.init(Cipher.ENCRYPT_MODE, k);
				byte[] resultBytes = cipher.doFinal(data);
				return resultBytes;
			} else if (encrypt == 0) {
				cipher.init(Cipher.DECRYPT_MODE, k);
				byte[] resultBytes = cipher.doFinal(data);
				return resultBytes;
			} else {
				System.out.println("参数必须为: 1 加密 0解密");
			}
		}
		return null;
	}
	//将String转公钥类型
	public static PublicKey pubStrToKey(String pubStr) {
		byte[] keyby=Base64.getDecoder().decode(pubStr);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyby);
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	        PublicKey publicKey = keyFactory.generatePublic(keySpec);
	        return publicKey;
		} catch (NoSuchAlgorithmException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return null;
	}
	//将String转私钥类型
	public static PrivateKey priStrToKey(String priStr) {
		byte[] keyby=Base64.getDecoder().decode(priStr);
        PKCS8EncodedKeySpec keySpec2 = new PKCS8EncodedKeySpec(keyby);
		try {
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
	        PrivateKey privateKey = keyFactory.generatePrivate(keySpec2);
	        return privateKey;
		} catch (NoSuchAlgorithmException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return null;
	}
	public static void main(String[] args) throws Exception {
		// TODO 自动生成的方法存根
		String pubfile = "d:/pub.key";	//公钥保存路径
		String prifile = "d:/pri.key";	//私钥保存路径
		String enc = "UTF-8";	//加密编码
		String pubstr="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvObsHN17XcOkYNtm25iueGABOgritgo+BRl/nZ300w6H/DqN8YF05jsBA7JYKivM2YbOVitq8g682WY0sB35kTK/YXX20sS6B6Fv+UlxY3zc/SnrAn/EPjDgiJ1w8xeyXYMqC9giOBIK1EZurLpA1dtgJ0nGjWa1gPdiL70LdGwIDAQAB";
		String pristr="MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK85uwc3Xtdw6Rg22bbmK54YAE6CuK2Cj4FGX+dnfTTDof8Oo3xgXTmOwEDslgqK8zZhs5WK2ryDrzZZjSwHfmRMr9hdfbSxLoHoW/5SXFjfNz9KesCf8Q+MOCInXDzF7JdgyoL2CI4EgrURm6sukDV22AnScaNZrWA92IvvQt0bAgMBAAECgYEAjW7JmV+F+9s1KchMHqbWGftBdB1rNxGlBzFog30ywH4PqbGFIAUf+i9Q2pab3NKe0Qw3ScMUHwkjSXkqy5kY2EJtX6YgUKrWawI6h5BSmb9W1CuFNrTftd9xaDkxYE016gTcsK7yJNeZrUB4+dN8ulOdzcyAnkNm9HJISwWRr/ECQQDUQn645hp/x/1ycug0MW6SpWmFrQglkXQFL6AFl/pYHXSzdJL8IWJyW/DtNA98EUtM2iysAxbk3cBTpZyqnsAFAkEA01WKGTR8R34MPoUQh2gbBgRAv8YD2RcWvFHUEkq2hpiUIXEM7Yd8DZXUIZZHZoq70bzkO9IGmHZsdwZgOQhSnwJBAMJYl/roBP9WuALgnyea0ylGdxXEVp8/TMGq15QHkVq4ra/aXvKoBqG6+R/W+Q6aLx4Q7bIZqg6n039DNe0rKZkCQQDP9uFLJGcYQ2XxMCiv1zagmRbOoSGwRBRPhYbX6UXs9cDvl7xNEoJ1K/fwhV4F/ogNQYCnjWqIJiFej5upBBOpAkAjPh4gqvFBmjFTmgZ0/eQLR1wlHgnInJ3Us73dSvhjumx5tuM40QfJFZ9Mi3M4zkF0VmqEHQK7SjAX+wsM33qm";
		String msg="殇雪话诀别";
		//makekeyfile(pubfile,prifile);	//生成秘钥对
		//printKryFile(pubfile, prifile); //从key文件打印秘钥内容
		RSAPublicKey pubkey=(RSAPublicKey) pubStrToKey(pubstr);		//将String转公钥
		RSAPrivateKey prikey= (RSAPrivateKey) priStrToKey(pristr);	//将String转秘钥
		printKey(pubkey, prikey);	//使用key对象打印秘钥内容

		// 使用公钥加密私钥解密
		System.out.println("原文: " + msg);
		byte[] result = handleData(pubkey, msg.getBytes(enc), 1);
		String data=Base64.getEncoder().encodeToString(result);
		System.out.println("公钥加密: " + data);
		byte[] deresult = handleData(prikey, Base64.getDecoder().decode(data), 0);
		System.out.println("私钥解密: " + new String(deresult, enc));
		
		System.out.println("原文: " + msg);
		byte[] result2 = handleData(prikey, msg.getBytes(enc), 1);
		String data2=Base64.getEncoder().encodeToString(result2);
		System.out.println("私钥签名: " + data2);
		byte[] deresult2 = handleData(pubkey, Base64.getDecoder().decode(data2), 0);
		System.out.println("公钥认证: " + new String(deresult2, enc));
		
	}

}

---------本文结束感谢您的阅读---------

评论

 热烈欢迎各位大佬专家莅临玖涯博客指导检查!

 交换友链的朋友请前往友情链接

 热烈欢迎各位大佬专家莅临玖涯博客指导检查!

 交换友链的朋友请前往友情链接

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×