码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA_RSA密钥生成

时间:2015-07-31 19:51:35      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

在网上找了下RSA的密钥的创建,结果全是用java序列化PublicKey和PrivateKey来保存,就自己写了个RSA公钥和私钥的创建,及进行Base64编码后保存。

这里用到了 bcprov-jdk16-1.4.5.jar ,可以在 http://www.bouncycastle.org/ 官方主页上下载.

public static void createKeyPairs() throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    // create the keys
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "BC");
    generator.initialize(512, new SecureRandom());
    KeyPair pair = generator.generateKeyPair();
    PublicKey pubKey = pair.getPublic();
    PrivateKey privKey = pair.getPrivate();
    byte[] pk = pubKey.getEncoded();
    byte[] privk = privKey.getEncoded();
    String strpk = new String(Base64.encodeBase64(pk));
    String strprivk = new String(Base64.encodeBase64(privk));

    System.out.println("公钥:" + Arrays.toString(pk));
    System.out.println("私钥:" + Arrays.toString(privk));
    System.out.println("公钥Base64编码:" + strpk);
    System.out.println("私钥Base64编码:" + strprivk);

    X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(Base64.decodeBase64(strpk.getBytes()));
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(strprivk.getBytes()));

    KeyFactory keyf = KeyFactory.getInstance("RSA", "BC");
    PublicKey pubkey2 = keyf.generatePublic(pubX509);
    PrivateKey privkey2 = keyf.generatePrivate(priPKCS8);

    System.out.println(pubKey.equals(pubkey2));
    System.out.println(privKey.equals(privkey2));
  }

 

JAVA_RSA密钥生成

标签:

原文地址:http://www.cnblogs.com/gisblogs/p/4692835.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!