How to Change PDF Password with Java

Learn how to change a PDF password with pdfRest Encrypt PDF API Tool using Java
Share this page

Change an Existing PDF Password with Java

Password changes are often part of a document's lifecycle rather than a one-time security step. A PDF may use an internal password while it moves through a review process and require a different password before it is delivered to a customer, partner, or archive. The pdfRest Encrypt PDF API Tool changes the open password through the /encrypted-pdf endpoint when the request supplies both the document's current password and the new password.

pdfRest applies AES 256-bit encryption using Adobe PDF Library technology. The source PDF remains unchanged, and the API returns a newly encrypted PDF, allowing an application to validate and store the result before replacing an earlier version. Because the existing password is required, this workflow changes authorized access without bypassing the document's current protection.

For example, a Java-based benefits portal can receive an encrypted enrollment package from an internal system, replace its temporary processing password with a recipient-specific delivery password, and then store the new PDF for secure distribution. The password transition happens as part of the automated workflow, so staff do not need to open and resave sensitive documents manually.

This example uses OkHttp to upload the protected PDF as multipart form data and send the current and replacement passwords in the same request.

Java Password-Change Code Example

Add OkHttp, java-dotenv, and JSON-java to the project. Set PDFREST_API_KEY in an environment variable or .env file, then replace the input path, current password, and new password placeholders. Do not commit passwords or API keys to source control.

import io.github.cdimascio.dotenv.Dotenv;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
import org.json.JSONObject;

public class EncryptedPDF {

  // By default, we use the US-based API service. This is the primary endpoint for global use.
  private static final String API_URL = "https://api.pdfrest.com";

  // For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
  // service by commenting out the URL above and uncommenting the URL below.
  // For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
  // private static final String API_URL = "https://eu-api.pdfrest.com";

  // Specify the path to your file here, or as the first argument when running the program.
  private static final String DEFAULT_FILE_PATH = "/path/to/file.pdf";

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {
    final boolean DELETE_SENSITIVE_FILES = false; // toggle deletion (default: false)
    File inputFile;
    if (args.length > 0) {
      inputFile = new File(args[0]);
    } else {
      inputFile = new File(DEFAULT_FILE_PATH);
    }

    final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    final RequestBody inputFileRequestBody =
        RequestBody.create(inputFile, MediaType.parse("application/pdf"));
    RequestBody requestBody =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", inputFile.getName(), inputFileRequestBody)
            .addFormDataPart("current_open_password", "current-password")
            .addFormDataPart("new_open_password", "new-password")
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url(API_URL + "/encrypted-pdf")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client =
          new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
        String respStr = response.body().string();
        System.out.println(prettyJson(respStr));

        // All files uploaded or generated are automatically deleted based on the
        // File Retention Period as shown on https://pdfrest.com/pricing.
        // For immediate deletion of files, particularly when sensitive data
        // is involved, an explicit delete call can be made to the API.
        //
        // Deletes all files in the workflow, including outputs. Save all desired files before
        // enabling this step.

        if (DELETE_SENSITIVE_FILES) {
          org.json.JSONObject parsed = new org.json.JSONObject(respStr);
          String inputId = parsed.getString("inputId");
          String outputId = parsed.getString("outputId");
          String deleteJson = String.format("{ \"ids\":\"%s, %s\" }", inputId, outputId);
          RequestBody deleteBody =
              RequestBody.create(deleteJson, MediaType.parse("application/json"));
          Request deleteRequest =
              new Request.Builder()
                  .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
                  .url(API_URL + "/delete")
                  .post(deleteBody)
                  .build();
          try (Response deleteResp =
              new OkHttpClient()
                  .newBuilder()
                  .readTimeout(60, TimeUnit.SECONDS)
                  .build()
                  .newCall(deleteRequest)
                  .execute()) {
            if (deleteResp.body() != null) {
              System.out.println(prettyJson(deleteResp.body().string()));
            }
          }
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);
  }
}

Source: pdfRest Encrypt PDF multipart Java sample

Supply the Current and New Passwords

The multipart file part contains the encrypted PDF. The current_open_password field proves that the application is authorized to open and re-encrypt it, while new_open_password sets the password that will be required for the output. The optional output field assigns a predictable base filename to the generated PDF.

An open password controls access to the document. A permissions password controls whether users can modify restrictions such as printing or editing. If the input PDF has relevant edit restrictions, the request may also need current_permissions_password. Keep these values distinct and obtain them through secure application input or a secret-management process rather than hard-coding them.

The sample defaults to the US Cloud API and exposes the EU base URL as a configuration option. Keeping the base URL outside the request logic lets deployment environments select the appropriate processing region without changing the workflow.

Use the Result in a Larger Workflow

A successful response identifies the newly encrypted PDF. Download its output URL when the application needs to store the file, or pass its resource ID directly to another compatible pdfRest API Tool. Resource-ID chaining avoids downloading and re-uploading intermediate files when the password change is followed by another operation.

Check the HTTP status before parsing success fields, and treat an incorrect current password as a request failure rather than retrying indefinitely. Production code should also use appropriate connection and read timeouts, handle network failures separately from API validation errors, and avoid writing passwords or sensitive response data to logs.

If the PDF has already been uploaded, the request can be sent as JSON with its resource ID instead of another multipart upload. See the official Encrypt PDF JSON-payload Java sample for that request pattern. Use API Lab to test password combinations, and consult the Encrypt PDF API reference for the current fields and response schema.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.