package com.yc.utils; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.math.BigInteger; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; public class RSAEncrypt { public static void main(String[] args){ try { String s= RSAEncrypt.Enc_RSA("ss中国要;swgdd"); // System.out.println("s>>>>"+s); String d=RSAEncrypt.Dec_RSA(s); // System.out.println("d>>>>>"+d); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 加密 * path为公钥文件路径 * */ public static String Enc_RSA(String s)throws Exception{ //从文件中读取公钥 s=java.net.URLEncoder.encode(s); FileInputStream f=new FileInputStream("c:/Skey_RSA_pub.dat"); ObjectInputStream b=new ObjectInputStream(f); RSAPublicKey pbk=(RSAPublicKey)b.readObject( ); //RSA算法是使用整数进行加密的,在RSA公钥中包含有两个整数信息:e和n。对于明文数字m,计算密文的公式是m的e次方再与n求模。 BigInteger e=pbk.getPublicExponent(); BigInteger n=pbk.getModulus(); //获取明文的大整数 byte ptext[]=s.getBytes("UTF-8"); BigInteger m=new BigInteger(ptext); //加密明文 BigInteger c=m.modPow(e,n); return c.toString( ); } /** * 解密 * * */ public static String Dec_RSA(String s)throws Exception{ //读取密文 BigInteger c=new BigInteger(s); //获取私钥 FileInputStream f=new FileInputStream("c:/Skey_RSA_priv.dat"); ObjectInputStream b=new ObjectInputStream(f); RSAPrivateKey prk=(RSAPrivateKey)b.readObject( ); //获取私钥的参数d,n BigInteger d=prk.getPrivateExponent(); BigInteger n=prk.getModulus(); // System.out.println("d= "+d); // System.out.println("n= "+n); //解密明文 BigInteger m=c.modPow(d,n); // System.out.println("m= "+m); //计算明文对应的字符串并输出。 byte[] mt=m.toByteArray(); return java.net.URLDecoder.decode(new String(mt)); // for(int i=0;i