Serialize and Deserialize an RSA public key

后端 未结 3 1244
耶瑟儿~
耶瑟儿~ 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: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.

提交回复
热议问题