Serialize and Deserialize an RSA public key

后端 未结 3 1248
耶瑟儿~
耶瑟儿~ 2021-02-08 13:48
KeyPairGenerator kpg = KeyPairGenerator.getInstance(\"RSA\");
kpg.initialize(1024);
KeyPair kp = kpg.genKeyPair();
Key publicKey = kp.getPublic();
Key privateKey = kp.ge         


        
相关标签:
3条回答
  • 2021-02-08 14:13

    I use the following code to convert a PubliKey to PEM Base64 format

    String publicKeyString = javax.xml.bind.DatatypeConverter.printBase64Binary(publicKey.getEncoded());
    

    I hope it helps.

    0 讨论(0)
  • 2021-02-08 14:16

    Depends on what do you want to do with the serialized representation. If the consumer is no one but your own program, feel free to roll your own implementation. A public RSA key consists of two integers - exponent and modulus. Modulus is large - around 1024 bits, exponent is typically on the order of 17 bits. Both are available as BigInteger objects if you cast your public key object to RSAPublicKey.

    So, to recap:

    RSAPublicKey publicKey = (RSAPublicKey)kp.getPublic();
    return publicKey.getModulus().toString() + "|" +
        publicKey.getPublicExponent().toString();
    

    That's sufficient to restore the key. To deserialize:

    String []Parts = MyKeyString.split("\\|");
    RSAPublicKeySpec Spec = new RSAPublicKeySpec(
            new BigInteger(Parts[0]),
            new BigInteger(Parts[1]));
    return KeyFactory.getInstance("RSA").generatePublic(Spec);
    

    If the key needs to be passed to third party software, you better serialize to a standard format - PEM or DER.

    0 讨论(0)
  • 2021-02-08 14:17

    Asymmetric keys like those from RSA are usually stored in X509 format. Therefor you can use X509EncodedKeySpecinstead.

    A simple example is already in the Java 7 JavaDoc (just replace DSA with RSA): http://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html

    X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec);
    

    If you need to deserialize the private from byte[], I've found that you must use PKCS8EncodedKeySpec.

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