Required to encrypt passwords on the client side (Java applet). The password must be encrypted with a private key, and the public one must be sent to the database, which would then get it and decrypt it. The key pair is generated as follows:

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); 

And with such keys, encryption and the reverse action occur without problems, but in order to store the key in the database, the toString () method converts it to a string. And how to make the same line of type PublicKey?

    1 answer 1

    Original answer . I admit that the blob of your key is stored in base64.

     byte[] publicBytes = Base64.decodeBase64(publicK); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PublicKey pubKey = keyFactory.generatePublic(keySpec); 
    • Yes thank you. I saw the same solution, but Eclipse was cursing, it turns out that the Base64 class needed to be imported from commons-codec-1.10, and not from the standard .util package - user2858470
    • @ user2858470 in java 8 has a built-in solution for base64 , but with a slightly different interface - Temka too