linux生成私钥 prk,自动生成RSA密钥,并进行加密和解密1

/**

* 自动产生RSA512位密钥(可以在512到2048之间)

*/

public static void getA271() throws Exception{

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");

kpg.initialize(512);

KeyPair kp = kpg.genKeyPair();

PublicKey puk = kp.getPublic();

PrivateKey prk = kp.getPrivate();

System.out.println("公钥:"+puk);

System.out.println("私钥:"+prk);

}

/**

* 自动产生RSA1024位密钥;并保持到文件里

*/

public static void getA272() throws Exception{

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");

kpg.initialize(512);

KeyPair kp = kpg.genKeyPair();

PublicKey puk = kp.getPublic();

PrivateKey prk = kp.getPrivate();

FileOutputStream pufos = new FileOutputStream("d:\\rsapublickey.txt");

ObjectOutputStream puoos = new ObjectOutputStream(pufos);

puoos.writeObject(puk);

FileOutputStream prfos = new FileOutputStream("d:\\rsaprivatekey.txt");

ObjectOutputStream proos = new ObjectOutputStream(prfos);

proos.writeObject(prk);

}

/**

* 使用非对称生成的公钥进行加密RSA512

*/

public static void getA281() throws Exception{

FileInputStream fis = new FileInputStream("d:\\rsapublickey.txt");

ObjectInputStream ois = new ObjectInputStream(fis);

RSAPublicKey pbk = (RSAPublicKey)ois.readObject();

BigInteger e = pbk.getPublicExponent();

BigInteger n = pbk.getModulus();

String mingwen = "hello world";//明文

byte[] ptext = mingwen.getBytes("UTF-8");

BigInteger m = new BigInteger(ptext);

BigInteger c = m.modPow(e, n);//因为RSA算法要求整型数m的值必须小于n,所以需要计算

//保存密文

String cs = c.toString();

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:\\rsapublickeyjiamihou.txt")));

bw.write(cs);

bw.flush();

}

/**

* 使用非对称生成的公钥和私钥进行解密RSA512

*/

public static void getA282() throws Exception{

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:\\rsapublickeyjiamihou.txt")));//加密后文件

String ctext = br.readLine();

BigInteger c = new BigInteger(ctext);

FileInputStream fis = new FileInputStream("d:\\rsaprivatekey.txt");

ObjectInputStream ois = new ObjectInputStream(fis);

RSAPrivateKey prk = (RSAPrivateKey)ois.readObject();

BigInteger d = prk.getPrivateExponent();

BigInteger n = prk.getModulus();

BigInteger m = c.modPow(d, n);

byte[] mt = m.toByteArray();

String s = "";

for(int i=0;is+=(char)mt[i];

}

System.out.println(s);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值