javaencryptionrsapaddingpublic-key-encryption

How to encode a text with rsa/ecb/pkcs1 padding mode with a given public key in java?


I want to encode a string with rsa/ecb/pkcs1 padding mode with a given public key (the public key is a string) in java.

I also want to present the results in UTF-8 Format how to do it?


Solution

  • Assuming you're using a valid RSA key, you'll need to:

    1. Convert your public key from a string to an actual public key object

      //This code is incorrect. You'll need bouncy castle for PKCS1
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
      byte[] keyBytes = Base64().getDecoder.decode(publicKey.getBytes()); //assuming base64 encoded key
      PKCS1EncodedKeySpec KeySpec = new PKCS1EncodedKeySpec(keyBytes);
      RSAPublicKey publicKey = (RSAPublicKey)keyFactory.generatePublic(KeySpec);
      
    2. Get the bytes of your plain text

    3. Encrypt using your public key
    4. Encode to a readable format.

    Check out this answer for steps 1-3: RSA Encrypt/Decrypt in Java. Remember to use the correct algorithm spec, in your case PKCS1

    Chances are your cipher text will not use only UTF-8 characters so you'll probably want to use Base 64 encoded text to display your cipher text. Base 64 is able to display all those wonky characters as ascii values.

    Simply use: Base64.getEncoder().encodeToString(cipherTextBytes)