Java Retrieve the actual value of the public key from the KeyPair object

前端 未结 3 937
梦谈多话
梦谈多话 2020-12-18 15:00

I wanted to ask how to retrieve the actual values of the private and public keys from the KeyPair object because i need to export them and save in a database.



        
相关标签:
3条回答
  • 2020-12-18 15:21

    It's probably easiest to use keypair.getPublic.getEncoded() or keypair.getPrivate.getEncoded():

    RSA private keys are encoded in PKCS#8 format, and public keys are encoded in X.509 format.

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair keyPair = kpg.generateKeyPair();
    PublicKey pub = keyPair.getPublic();
    PrivateKey prv = keyPair.getPrivate();
    
    byte[] pubBytes = pub.getEncoded();
    byte[] prvBytes = prv.getEncoded();
    
    // now save pubBytes or prvBytes
    
    // to recover the key
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey prv_recovered = kf.generatePrivate(new PKCS8EncodedKeySpec(prvBytes));
    PublicKey pub_recovered = kf.generatePublic(new X509EncodedKeySpec(pubBytes));
    
    System.out.println("Private Key: \n" + prv_recovered.toString());
    System.out.println("Public Key: \n" + pub_recovered.toString());
    
    0 讨论(0)
  • 2020-12-18 15:27

    You can simply downcast to RSAPrivateKey and RSAPublicKey. Once you've done that you can access the methods of these classes.

    RSAPublicKey pubKey = (RSAPublicKey) keyPair.getPublic());
    BigInteger modulus = pubKey.getModulus();
    

    etc.

    0 讨论(0)
  • 2020-12-18 15:34

    Have you looked into the docs?

    Try the following :

    getModulus

    getPublicExponent

    getPrivateExponent

    They all return BigInteger

    than can in turn be stored.

    Also see if the raw encoded format is of help.

    0 讨论(0)
提交回复
热议问题