I have, for example, a generated publicKey . I used the .toString() method to make a string variable from it. How can I make an object of type publicKey out of it (the opposite effect to the .toString(); ) method This is what the string variable looks like. You need to make publicKey out of it publicKey

1:23:08 PM Anonymous: Sun RSA public key, 2048 bits modulus: public exponent: 65537

    2 answers 2

    The toString() method is not a certificate serialization method. You need to use deserializers and serializers:

     //дСсСриализация ΠΈΠ· массива Π±Π°ΠΉΡ‚ bobEncodedPubKey X509EncodedKeySpec bobPubKeySpec = new X509EncodedKeySpec(bobEncodedPubKey); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey bobPubKey = keyFactory.generatePublic(bobPubKeySpec); //сСриализация Π² массив Π±Π°ΠΉΡ‚ byte[] result = bobPubKey.getEncoded() 

    Original answer

      The RSA public key consists of a module and an exponent, which are specified as BigInteger , respectively, for serialization, you need to remove the module and the exponent, save them somewhere, and then, for deserialization, generate the public key back from the module and exponents, such as:

       //ΠΈΠ·Π²Π»Π΅Ρ‡Π΅Π½ΠΈΠ΅ Π·Π½Π°Ρ‡Π΅Π½ΠΈΠΉ ΠΊΠ»ΡŽΡ‡Π° RSAPublicKey publicKey; BigInteger modulus=publicKey.getModulus(); BigInteger exponent=publicKey.getPublicExponent(); //сСриализация Π·Π½Π°Ρ‡Π΅Π½ΠΈΠΉ ΠΊΠ»ΡŽΡ‡Π° String modulusString=modulus.toString(); String exponentString=exponent.toString(); //восстановлСниС ΠΊΠ»ΡŽΡ‡Π° RSAPublicKeySpec Spec = new RSAPublicKeySpec(new BigInteger(modulusString), new BigInteger(exponentString)); RSAPublicKey newPublicKey=KeyFactory.getInstance("RSA").generatePublic(Spec);