RSA是非对称加密算法,客户端生成一对密匙秘钥,公钥用于加密,私钥用于解密
package RSA;
import java.io.File;
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.io.UnsupportedEncodingException;
import java.math.BigInteger;
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.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
public class RS1 {
String string="admin";
byte ptext[];
public RS1(String ss ) throws IOException, ClassNotFoundException, NoSuchAlgorithmException, InvalidKeySpecException {
//
/*
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
PublicKey pbkey = kp.getPublic();
PrivateKey prkey = kp.getPrivate();
System.out.println(pbkey);
*/
KeyPairGenerator keyPair = KeyPairGenerator.getInstance("RSA");
keyPair.initialize(1024);
KeyPair kp = keyPair.generateKeyPair();
X509EncodedKeySpec keySpec=new X509EncodedKeySpec(kp.getPublic().getEncoded());
KeyFactory keyFactory=KeyFactory.getInstance("RSA");
PublicKey publickey=keyFactory.generatePublic(keySpec);
System.out.println(publickey);
System.out.println("###################################");
// TODO Auto-generated constructor stub
FileOutputStream f1 = new FileOutputStream("D:"+File.separator+"search"+File.separator+"bb"+File.separator+"pubkey.dat");
ObjectOutputStream b1 = new ObjectOutputStream(f1);
b1.writeObject(publickey);
b1.close();
FileInputStream f = new FileInputStream("D:"+File.separator+"search"+File.separator+"bb"+File.separator+"pubkey.dat");
ObjectInputStream b = new ObjectInputStream(f);
RSAPublicKey pbk = (RSAPublicKey) b.readObject();
BigInteger e = pbk.getPublicExponent();
BigInteger n = pbk.getModulus();
System.out.println("e= " + e);
System.out.println("n= " + n);
try {
ptext = string.getBytes("UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BigInteger m = new BigInteger(ptext);
// 计算密文c
BigInteger c = m.modPow(e, n);
System.out.println("c= " + c);
// 保存密文
String cs = c.toString();
System.out.print(cs);
b.close();
}
public static void main(String[] args) throws ClassNotFoundException, IOException, NoSuchAlgorithmException, InvalidKeySpecException {
// TODO Auto-generated method stub
RS1 rs=new RS1("C02A0C475D31142C25BC1EB8000462B502447FBE76FC48F3609BF7D714116AA08AF117F53FDEBF6E06AB8FCB74BBB892CCAF28A13B7EA83718DA44B3648107007D4609C684F67028D4F9E170126544A3281CDA4C6941E4ADB112497D0C739A9296DA3A6FC849C15116B3CFEFFF0B1F515530CCA3A0E9296B2F02ADEB207B4451");
}
public void encrypt() throws UnsupportedEncodingException{
}
}