JAVA_RSA密钥生成

在网上找了下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));
  }

 

posted @ 2015-07-31 17:51  GisClub  阅读(1942)  评论(0编辑  收藏  举报