public static void writeKeyset(
      KeysetHandle handle,
      OutputStream outputStream,
      String outFormat,
      String masterKeyUri,
      String credentialPath)
      throws GeneralSecurityException, IOException {
    if (masterKeyUri != null) {
      Aead masterKey =
          KmsClientsFactory.globalInstance()
              .newClientFor(masterKeyUri)
              .withCredentials(credentialPath)
              .getAead(masterKeyUri);
      if (isJson(outFormat)) {
        outputStream.write(
            TinkJsonProtoKeysetFormat.serializeEncryptedKeyset(handle, masterKey, new byte[] {})
                .getBytes(UTF_8));
        return;
      } else {
        outputStream.write(
            TinkProtoKeysetFormat.serializeEncryptedKeyset(handle, masterKey, new byte[] {}));
        return;
      }
    }
    if (isJson(outFormat)) {
      outputStream.write(
          TinkJsonProtoKeysetFormat.serializeKeyset(handle, InsecureSecretKeyAccess.get())
              .getBytes(UTF_8));
      return;
    }
    outputStream.write(
        TinkProtoKeysetFormat.serializeKeyset(handle, InsecureSecretKeyAccess.get()));
    return;
  }
Writes the keyset managed by {@code handle} to {@code outputStream} with format {@code
outFormat}. Maybe encrypt it with {@code masterKeyUri} and {@code credentialPath}.
tools/tinkey/src/main/java/com/google/crypto/tink/tinkey/TinkeyUtil.java