> For the complete documentation index, see [llms.txt](https://docs.keeper.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.keeper.io/keeperpam/secrets-manager/developer-sdk-library/java-sdk.md).

# Java/Kotlin SDK

Detailed Java and Kotlin SDK docs for Keeper Secrets Manager

<figure><img src="https://762006384-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MJXOXEifAmpyvNVL1to%2Fuploads%2FuEIQqGscYjUYRpNYOExM%2FKSM%20%2B%20Java%20Icon.png?alt=media&#x26;token=5656d181-9c3c-4e3d-8ced-eedbd76478f7" alt=""><figcaption></figcaption></figure>

## Download and Installation

### Install With Maven or Gradle

{% tabs %}
{% tab title="Gradle" %}
{% code title="build.gradle" %}

```gradle
repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.keepersecurity.secrets-manager:core:17.2.0+'
    implementation("org.bouncycastle:bc-fips:2.1.1")
}
```

{% endcode %}
{% endtab %}

{% tab title="Maven" %}
{% code title="pom.xml" %}

```xml
<dependency>
    <groupId>com.keepersecurity.secrets-manager</groupId>
    <artifactId>core</artifactId>
    <version>[17.2.0,)</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bc-fips</artifactId>
    <version>2.1.1</version>
</dependency>
```

{% endcode %}
{% endtab %}
{% endtabs %}

For more information, see <https://central.sonatype.com/artifact/com.keepersecurity.secrets-manager/core>

{% hint style="info" %}
**Cryptographic Provider Note**: The Keeper Secrets Manager SDK does not require BouncyCastle. You can use:

* BouncyCastle FIPS (`bc-fips:2.1.1` - as in the installation instructions above)
* Java's default crypto provider
* Any JCE-compatible cryptographic provider

The examples in this documentation use BouncyCastle FIPS for demonstration purposes.
{% endhint %}

### **Cryptographic Provider**

The Keeper Secrets Manager SDK expects the developer to use their required cryptographic provider. As documented above, Keeper will use the default cryptographic module of the Java runtime unless a specific provider is added. In the examples here in this documentation, we are using the BouncyCastle FIPS provider.

In the source code, ensure that the provider is loaded in the security context:

```
fun main() {
    Security.addProvider(BouncyCastleFipsProvider())
...
```

See the file `CryptoUtilsTest.kt` as shown in this [example](https://github.com/Keeper-Security/secrets-manager/blob/dcd96317304b8ddc2b17a649ac465f5cd408491a/sdk/java/core/src/test/kotlin/com/keepersecurity/secretsManager/core/CryptoUtilsTest.kt#L11) on how to use a custom security provider.

### **Source Code**

Find the Java/Kotlin source code in the [GitHub repository](https://github.com/Keeper-Security/secrets-manager/tree/master/sdk/java/core)

## Using the SDK

### Initialize Storage

{% hint style="info" %}
Using token only to generate a new config (for later usage) requires at least one read operation to bind the token and fully populate `config.json`
{% endhint %}

In order to retrieve secrets, you must first initialize the local storage on your machine.

```java
initializeStorage(storage: KeyValueStorage, oneTimeToken: String, hostName: String? = null)
```

| Parameter      | Type              | Required | Default | Description            |
| -------------- | ----------------- | -------- | ------- | ---------------------- |
| `storage`      | `KeyValueStorage` | Yes      |         | Storage Implementation |
| `oneTimeToken` | String            | Yes      |         | One-time access token  |
| `hostName`     | String            | Optional | null    | Custom hostname        |

#### **Example Usage**

```java
import static com.keepersecurity.secretsManager.core.SecretsManager.initializeStorage;
import com.keepersecurity.secretsManager.core.LocalConfigStorage;
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
import java.security.Security;
import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;

// oneTimeToken is used only once to initialize the storage
// after the first run, subsequent calls will use "ksm-config.txt" file
String oneTimeToken = "[One Time Access Token]";
LocalConfigStorage storage = new LocalConfigStorage("ksm-config.txt");

Security.addProvider(new BouncyCastleFipsProvider());

try {
    initializeStorage(storage, oneTimeToken);
    SecretsManagerOptions options = new SecretsManagerOptions(storage);
    // Using token only to generate a config (for later usage)
    // requires at least one access operation to bind the token
    //getSecrets(options)
 } catch (Exception e) {
    System.out.println(e.getMessage());
 }
```

### Binding Lifecycle

The one-time token is redeemed on the first `getSecrets()` call, not at construction. If you persist config to an external store (AWS Secrets Manager, Azure Key Vault, etc.), read it back only after that call. For the full explanation, see [Binding Lifecycle](/keeperpam/secrets-manager/about/secrets-manager-configuration.md#binding-lifecycle).

```kotlin
import com.keepersecurity.secretsManager.core.*

// First run: storage file contains the one-time token.
val storage = LocalConfigStorage("ksm-config.json")
val options = SecretsManagerOptions(storage)
val secrets = SecretsManager.getSecrets(options)
// Token is redeemed here; ksm-config.json is updated with bound credentials.

// Subsequent runs: no changes needed — storage holds the bound credentials.
val secrets2 = SecretsManager.getSecrets(options)
```

### Retrieve Secrets

```java
getSecrets(options: SecretsManagerOptions, recordsFilter: List<String> = emptyList()): KeeperSecrets
```

<table data-header-hidden><thead><tr><th>Parameter</th><th>Type</th><th width="150">Required</th><th width="150">Default</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Default</td><td>Description</td></tr><tr><td><code>options</code></td><td><code>SecretsManagerOptions</code></td><td>Yes</td><td></td><td>Storage and query configuration</td></tr><tr><td><code>recordsFilter</code></td><td><code>List&#x3C;String></code></td><td>Optional</td><td>Empty List</td><td>Record search filters</td></tr></tbody></table>

**Response**

Type: `KeeperSecrets`

Object containing all Keeper records, or records that match the given filter criteria

**Example Usage**

Retrieve all Secrets

```java
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
import com.keepersecurity.secretsManager.core.SecretsManager;
import com.keepersecurity.secretsManager.core.KeeperRecord;
import com.keepersecurity.secretsManager.core.KeeperSecrets;
import java.security.Security;
import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;

// Ensure security provider is loaded
Security.addProvider(new BouncyCastleFipsProvider());

//get secrets
SecretsManagerOptions options = new SecretsManagerOptions(storage);
KeeperSecrets secrets = SecretsManager.getSecrets(options);

//get records from secrets
List<KeeperRecord> records = secrets.getRecords();
```

Retrieve one secret by UID

```java
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
import com.keepersecurity.secretsManager.core.SecretsManager;
import com.keepersecurity.secretsManager.core.KeeperRecord;
import com.keepersecurity.secretsManager.core.KeeperSecrets;
import java.security.Security;
import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;

// Ensure security provider is loaded
Security.addProvider(new BouncyCastleFipsProvider());

//get secrets
SecretsManagerOptions options = new SecretsManagerOptions(storage);
KeeperSecrets secrets = SecretsManager.getSecrets(options);

// identify one or more record UID to fetch secrets by
List<String> uidFilter = List.of("[XXX]");

// fetch secrets with the filter
KeeperSecrets secrets = SecretsManager.getSecrets(options, uidFilter);

//get records from secrets
List<KeeperRecord> records = secrets.getRecords();
```

### Retrieve Secrets by Title

```java
// get all matching records
getSecretsByTitle(recordTitle: String): List<KeeperRecord>

// get only the first matching record
getSecretByTitle(recordTitle: String): KeeperRecord
```

<table><thead><tr><th width="178.10385756676556">Parameter</th><th width="150">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>recordTitle</code></td><td>String</td><td>Yes</td><td>Record title to search for</td></tr></tbody></table>

**Example Usage**

```java
import com.keepersecurity.secretsManager.core.*;
import java.util.List;

public class KSMSample {
    public static void main(String[] args){

        // Ensure security provider is loaded
        Security.addProvider(new BouncyCastleFipsProvider());

        // get pre-initialized storage
        KeyValueStorage storage = new LocalConfigStorage("ksm-config.json");
        try {
            SecretsManagerOptions options = new SecretsManagerOptions(storage);

            // get all secrets first
            KeeperSecrets secrets = SecretsManager.getSecrets(options);

            // title of the record to fetch
            String recordTitle = "My Credentials";

            // search for record by title
            KeeperRecord myCredentials = secrets.getSecretByTitle(recordTitle);

            // print out record details
            System.out.println("Record UID: " + myCredentials.getRecordUid());
            System.out.println("Title: " + myCredentials.getData().getTitle());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
```

### Retrieve Values From a Secret

#### Retrieve a Password

This shortcut gets the password of a secret once that secret has been retrieved from Keeper Secrets Manager.

{% tabs %}
{% tab title="Get Password" %}

```java
secret.getPassword()
```

{% endtab %}

{% tab title="Example Usage" %}

```java
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
import com.keepersecurity.secretsManager.core.SecretsManager;
import com.keepersecurity.secretsManager.core.KeeperRecord;
import com.keepersecurity.secretsManager.core.KeeperSecrets;
import java.security.Security;
import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;

// Ensure security provider is loaded
Security.addProvider(new BouncyCastleFipsProvider());

//get secrets
SecretsManagerOptions options = new SecretsManagerOptions(storage);
KeeperSecrets secrets = SecretsManager.getSecrets(options);

//get the first record
KeeperRecord firstRecord = secrets.getRecords().get(0);

//get the password from the first record
String password = firstRecord.getPassword();
System.out.println("Password: " + password);
```

{% endtab %}
{% endtabs %}

#### Retrieve Fields

{% tabs %}
{% tab title="Get Field" %}

```java
secret.getData().getField(<FIELD_TYPE>)
```

{% endtab %}

{% tab title="Example Usage" %}

```java
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
import com.keepersecurity.secretsManager.core.SecretsManager;
import com.keepersecurity.secretsManager.core.KeeperRecord;
import com.keepersecurity.secretsManager.core.KeeperSecrets;
import java.security.Security;
import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;

// Ensure security provider is loaded
Security.addProvider(new BouncyCastleFipsProvider());

//get secrets
SecretsManagerOptions options = new SecretsManagerOptions(storage);
KeeperSecrets secrets = SecretsManager.getSecrets(options);

//get the first record
List<KeeperRecord> records = secrets.getRecords();
KeeperRecord firstRecord = secrets.getRecords().get(0);

//get the password from the first record
KeeperRecordField pwd = firstRecord.getData().getField(Password.class)
```

{% endtab %}
{% endtabs %}

To get a field value, you will need to cast the return to the [class](/keeperpam/secrets-manager/developer-sdk-library/java-sdk/record-field-classes.md) of the corresponding field type. For a list of field types see the [Record Types](/keeperpam/secrets-manager/about/field-record-types.md) page.

**Keeper Notation**

{% tabs %}
{% tab title="Get Value" %}

```java
Notation.getValue(secrets, "<query>");
// Query example "<RECORD UID>/field/login"
```

{% endtab %}

{% tab title="Example Usage" %}

```java
import static com.keepersecurity.secretsManager.core.SecretsManager.*
import static com.keepersecurity.secretsManager.core.Notation.*;
import java.security.Security;
import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;

// Ensure security provider is loaded
Security.addProvider(new BouncyCastleFipsProvider());

// get secrets
KeeperSecrets secrets = getSecrets(options);

// get login with dot notation
String login = getValue(secrets, "BediNKCMG21ztm5xGYgNww/field/login");
```

{% endtab %}
{% endtabs %}

{% hint style="info" %}
See [Keeper Notation documentation](/keeperpam/secrets-manager/about/keeper-notation.md) to learn about Keeper Notation format and capabilities
{% endhint %}

| Parameter | Type            | Required | Description                                        |
| --------- | --------------- | -------- | -------------------------------------------------- |
| `secrets` | `KeeperSecrets` | Yes      | Secrets collection to resolve the notation against |
| `query`   | `String`        | Yes      | Dot notation query of desired field                |

#### Get TOTP Code

{% tabs %}
{% tab title="Get TOTP Code" %}

```java
TotpCode.uriToTotpCode(url)
```

{% endtab %}

{% tab title="Example Usage" %}

```java
import static com.keepersecurity.secretsManager.core.Notation.*;
import static com.keepersecurity.secretsManager.core.TotpCode.*;
import java.security.Security;
import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;

...

// get secrets
KeeperSecrets secrets = getSecrets(options);

// get TOTP url from record
String url= getValue(secrets, "BediNKCMG21ztm5xGYgNww/field/oneTimeCode");

// get TOTP code
TotpCode totp = uriToTotpCode(url);
```

{% endtab %}
{% endtabs %}

| Parameter | Type     | Required | Description |
| --------- | -------- | -------- | ----------- |
| `url`     | `String` | Yes      | TOTP Url    |

### PAM Record Types

Use `record.getType()` to identify PAM records.

```kotlin
for (record in secrets.records) {
    when (record.getType()) {
        "pamMachine"  -> { /* host field available */ }
        "pamUser"     -> { /* login field available */ }
        "pamDatabase" -> { /* databaseType field available */ }
    }
}
```

For field schemas of all 11 PAM record types, see [PAM Record Types](/keeperpam/secrets-manager/about/pam-record-types.md).

### Linked Credentials

Pass `requestLinks = true` in `QueryOptions` to retrieve PAM resource records with their linked credentials included. Each link is a `KeeperRecordLink` exposing typed accessors for the target record UID and the link's privileges and permitted operations (`isAdminUser()`, `isLaunchCredential()`, `allowsRotation()`, `allowsConnections()`, …). See [Linked Credentials on PAM Records](/keeperpam/secrets-manager/developer-sdk-library/java-sdk/linked-credentials-on-pam-records.md) for the full reference.

```kotlin
val queryOptions = QueryOptions(requestLinks = true)
val secrets = SecretsManager.getSecrets2(options, queryOptions)

for (record in secrets.records) {
    // links is null when requestLinks was not set, empty when set but none exist
    record.links?.forEach { link ->
        println("link -> ${link.recordUid} (admin=${link.isAdminUser()}, launch=${link.isLaunchCredential()})")
    }
}
```

**QueryOptions Parameters**

| Parameter       | Type           | Required | Default | Description                                                      |
| --------------- | -------------- | -------- | ------- | ---------------------------------------------------------------- |
| `recordsFilter` | `List<String>` | No       | Empty   | Filter by record UIDs                                            |
| `foldersFilter` | `List<String>` | No       | Empty   | Filter by folder UIDs                                            |
| `requestLinks`  | `Boolean?`     | No       | `null`  | Set to `true` to retrieve links; `null`/`false` returns no links |

For the cross-SDK overview of the linked credentials workflow, see [Linked Credentials](/keeperpam/secrets-manager/about/linked-credentials.md).

### **Update Values in a Secret**

{% hint style="warning" %}
Record update commands don't update local record data on success *(esp. updated record revision)* so any consecutive updates to an already updated record will fail due to **revision** mismatch. Make sure to reload all updated records after each update batch.
{% endhint %}

**Update Secret**

{% tabs %}
{% tab title="Update Secret" %}

```java
updateSecret(options: SecretsManagerOptions, recordToUpdate: KeeperRecord);
```

{% endtab %}

{% tab title="Example Usage" %}

```java
import com.keepersecurity.secretsManager.core.KeeperRecord;
import com.keepersecurity.secretsManager.core.KeeperSecrets;
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
import static com.keepersecurity.secretsManager.core.SecretsManager.*;

// Ensure security provider is loaded
Security.addProvider(new BouncyCastleFipsProvider());

// get secrets
SecretsManagerOptions options = SecretsManagerOptions(storage);
KeeperSecrets secrets = getSecrets(options);

// we'll update the first record
KeeperRecord recordToUpdate = secrets.getRecords().get(0);

// update password
recordToUpdate.updatePassword("aP1$t367QOCvL$eM$bG#");

// update title and notes
recordToUpdate.data.title = "New Title"
recordToUpdate.data.notes = "My Notes"

// save changes
updateSecret(options, recordToUpdate);
```

{% endtab %}

{% tab title="Transactional Updates" %}

```java
import com.keepersecurity.secretsManager.core.KeeperRecord;
import com.keepersecurity.secretsManager.core.KeeperSecrets;
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;

import static com.keepersecurity.secretsManager.core.SecretsManager.*;

...

// get secrets
SecretsManagerOptions options = SecretsManagerOptions(storage);
KeeperSecrets secrets = getSecrets(options);

// we'll update the first record
KeeperRecord record = secrets.getRecords().get(0);

// rotate password on the record
record.updatePassword("aP1$t367QOCvL$eM$bG#");

// start a transaction
updateSecret(options, record, transactionType = UpdateTransactionType.GENERAL);

// rotate password on remote host
boolean success = rotateRemoteSshPassword("aP1$t367QOCvL$eM$bG#");

// complete the transaction - commit or rollback
completeTransaction(options, record.recordUid, rollback = !success);
```

{% endtab %}
{% endtabs %}

Update Secret is used to save changes made to a secret. Once updateSecret is performed successfully, the changes are reflected in the Keeper Vault.

{% hint style="info" %}
`KeeperRecord.isEditable` reflects the write permission set on the Secrets Manager application's share. Check it before calling `updateSecret` if you want to detect read-only records before attempting a write. The SDK does not enforce this field — a write to a read-only record fails at the server.
{% endhint %}

<table data-header-hidden><thead><tr><th width="206">Parameter</th><th>Type</th><th>Required</th><th>Description</th></tr></thead><tbody><tr><td>Parameter</td><td>Type</td><td>Required</td><td>Description</td></tr><tr><td><code>options</code></td><td><code>SecretsManagerOptions</code></td><td>Yes</td><td>Storage and query configuration</td></tr><tr><td><code>recordToUpdate</code></td><td><code>KeeperRecord</code></td><td>Yes</td><td>Record to update</td></tr><tr><td><code>transactionType</code></td><td><code>UpdateTransactionType</code></td><td>No</td><td>Set to start a two-phase update; complete it with <code>completeTransaction</code></td></tr></tbody></table>

**Update** **Password**

{% tabs %}
{% tab title="Update Password" %}

```java
recordToUpdate.updatePassword(password: String);

SecretsManager.updateSecret(options, recordToUpdate);
```

{% endtab %}

{% tab title="Example Usage" %}

```java
import static com.keepersecurity.secretsManager.core.SecretsManager;

import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
import com.keepersecurity.secretsManager.core.KeeperRecord;
import com.keepersecurity.secretsManager.core.KeeperSecrets;

// get secrets
SecretsManagerOptions options = SecretsManagerOptions(storage);
KeeperSecrets secrets = getSecrets(options);

// we'll update the first record
KeeperRecord recordToUpdate = secrets.getRecords().get(0);

// update password
recordToUpdate.updatePassword("aP1$t367QOCvL$eM$bG#");

// save changes
SecretsManager.updateSecret(options, recordToUpdate);
```

{% endtab %}
{% endtabs %}

| Parameter  | Type     | Required | Description         |
| ---------- | -------- | -------- | ------------------- |
| `password` | `String` | Yes      | New password to set |

**Update other fields**

{% tabs %}
{% tab title="Set Value" %}

```java
//format
RecordField.getValue().set(index, value)

//example - Login field
recordLogin.getValue().set(0, "New Login");
```

{% endtab %}

{% tab title="Example Usage" %}

```java
// get field to edit
Login recordLogin = (Login) recordToUpdate.getData().getField(Login.class);

// update field value
recordLogin.getValue().set(0, "New Login");

// save changes
SecretsManager.updateSecret(options, recordToUpdate);
```

{% endtab %}
{% endtabs %}

Each record field type is represented by a class. Cast the field to the corresponding class in order to correctly access the field's value. Check the [Record Types](/keeperpam/secrets-manager/about/field-record-types.md) documentation for a list of field types.

Fields can have multiple values, which is accessed in a List. In this example we are updating the login field, which only accepts one value, so we update the one value in the values list.

#### Generate a Random Password

{% tabs %}
{% tab title="Generate Password" %}

```java
generatePassword(
    minLength: Int = 32,
    lowercase: Int? = null,
    uppercase: Int? = null,
    digits: Int? = null,
    specialCharacters: Int? = null,
    specialCharacterSet: String = "\"!@#$%()+;<>=?[]{}^.,"
)
```

{% endtab %}

{% tab title="Example Usage" %}

```java
import com.keepersecurity.secretsManager.core.CryptoUtils;

// Ensure security provider is loaded
Security.addProvider(new BouncyCastleFipsProvider());

// get field to edit
Password recordPassword = (Password) recordToUpdate.getData().getField(Password.class);

// generate a random password
String password = CryptoUtils.generatePassword();

// update field value
recordPassword.getValue().set(0, password);

// save changes
SecretsManager.updateSecret(options, recordToUpdate);
```

{% endtab %}
{% endtabs %}

<table><thead><tr><th width="195.015625">Parameter</th><th width="87.66796875">Type</th><th width="106.421875">Required</th><th width="126.88671875">Default</th><th>Description</th></tr></thead><tbody><tr><td><code>minLength</code></td><td><code>Int</code></td><td>Optional</td><td>32</td><td>Minimum total length of the generated password</td></tr><tr><td><code>lowercase</code></td><td><code>Int</code></td><td>Optional</td><td><code>null</code></td><td>Minimum lowercase letters (treated as an exact count if 0 or negative)</td></tr><tr><td><code>uppercase</code></td><td><code>Int</code></td><td>Optional</td><td><code>null</code></td><td>Minimum uppercase letters (treated as an exact count if 0 or negative)</td></tr><tr><td><code>digits</code></td><td><code>Int</code></td><td>Optional</td><td><code>null</code></td><td>Minimum digits (treated as an exact count if 0 or negative)</td></tr><tr><td><code>specialCharacters</code></td><td><code>Int</code></td><td>Optional</td><td><code>null</code></td><td>Minimum special characters (treated as an exact count if 0 or negative)</td></tr><tr><td><code>specialCharacterSet</code></td><td><code>String</code></td><td>Optional</td><td><code>"!@#$%()+;&#x3C;>=?[]{}^.,</code></td><td>Custom set of special characters to draw from</td></tr></tbody></table>

Each parameter indicates the min number of a type of character to include. For example, 'uppercase' indicates the minimum number of uppercase letters to include.

### Download a File

{% tabs %}
{% tab title="Download File" %}

```java
SecretsManager.downloadFile(file): ByteArray
```

{% endtab %}

{% tab title="Example Usage" %}

```java
import static com.keepersecurity.secretsManager.core.SecretsManager;
import com.keepersecurity.secretsManager.core.KeeperRecord;
import com.keepersecurity.secretsManager.core.KeeperFile;

// Ensure security provider is loaded
Security.addProvider(new BouncyCastleFipsProvider());

// download the first file from the first record
KeeperRecord firstRecord = secrets.getRecords().get(0);
KeeperFile file = firstRecord.getFileByName("acme.cer");
byte[] fileBytes = SecretsManager.downloadFile(file);

// write file to a disk
try (FileOutputStream fos = new FileOutputStream(file.getData().getName())) {
    fos.write(fileBytes);
} catch (IOException ioException){
    ioException.printStackTrace();
}
```

{% endtab %}
{% endtabs %}

| Parameter | Type         | Required | Description      |
| --------- | ------------ | -------- | ---------------- |
| `file`    | `KeeperFile` | Yes      | File to download |

**Response**

Type: `ByteArray`

ByteArray of file for download

### Download a **Thumbnail**

{% tabs %}
{% tab title="Download Thumbnail" %}

```java
SecretsManager.downloadThumbnail(file): ByteArray
```

{% endtab %}

{% tab title="Example Usage" %}

```java
import static com.keepersecurity.secretsManager.core.SecretsManager;
import com.keepersecurity.secretsManager.core.KeeperRecord;
import com.keepersecurity.secretsManager.core.KeeperFile;

// Ensure security provider is loaded
Security.addProvider(new BouncyCastleFipsProvider());

// download the first file from the first record
KeeperRecord firstRecord = secrets.getRecords().get(0);
KeeperFile file = firstRecord.getFileByName("acme.cer");
byte[] fileBytes = SecretsManager.downloadThumbnail(file);

// write file to a disk
try (FileOutputStream fos = new FileOutputStream(file.getData().getName())) {
    fos.write(fileBytes);
} catch (IOException ioException){
    ioException.printStackTrace();
}
```

{% endtab %}
{% endtabs %}

| Parameter | Type         | Required | Description                     |
| --------- | ------------ | -------- | ------------------------------- |
| `file`    | `KeeperFile` | Yes      | File with thumbnail to download |

**Response**

Type: `ByteArray`

ByteArray of thumbnail for download

### Upload a File

Upload File:

```java
uploadFile(options: SecretsManagerOptions, ownerRecord: KeeperRecord, file: KeeperFileUpload): String
```

<table><thead><tr><th width="184.14763231197773">Parameter</th><th width="246.99431983802478">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>options</code></td><td>SecretsManagerOptions</td><td>Yes</td><td>Storage and query configuration</td></tr><tr><td><code>ownerRecord</code></td><td>KeeperRecord</td><td>Yes</td><td>The record to attach the uploaded file to</td></tr><tr><td><code>file</code></td><td>KeeperFileUpload</td><td>Yes</td><td>The File to upload</td></tr></tbody></table>

Creating the Keeper File Upload Object:

```kotlin
KeeperFileUpload(
    val name: String,
    val title: String,
    val type: String?,
    val data: ByteArray
)
```

<table><thead><tr><th width="169">Parameter</th><th width="150">Type</th><th width="150">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>name</code></td><td>string</td><td>Yes</td><td>What the name of the file will be in Keeper once uploaded</td></tr><tr><td><code>title</code></td><td>string</td><td>Yes</td><td>What the title of the file will be in Keeper once uploaded</td></tr><tr><td><code>type</code></td><td>string</td><td>Optional</td><td>The mime type of data in the file. 'application/octet-stream' will be used if nothing is given</td></tr><tr><td><code>data</code></td><td>ByteArray</td><td>Yes</td><td>File data as bytes</td></tr></tbody></table>

**Example Usage**

```java
import com.keepersecurity.secretsManager.core.*;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;

public class KSMSample {
    public static void main(String[] args){

        // Ensure security provider is loaded
        Security.addProvider(new BouncyCastleFipsProvider());

        // get pre-initialized storage
        KeyValueStorage storage = new LocalConfigStorage("ksm-config.json");
        try {
            SecretsManagerOptions options = new SecretsManagerOptions(storage);

            // create a filter with the UID of the record we want
            List<String> uidFilter = List.of("XXX");

            // fetch secrets with the filter
            KeeperSecrets secrets = SecretsManager.getSecrets(options, uidFilter);

            // get the desired secret to upload a file to
            KeeperRecord ownerRecord = secrets.getRecords().get(0);

            // get bytes from file to upload
            File file = new File("./myFile.json");
            FileInputStream fl = new FileInputStream(file);
            byte[] fileBytes = new byte[(int)file.length()];
            fl.read(fileBytes);
            fl.close();

            // create a Keeper File to upload
            KeeperFileUpload myFile = new KeeperFileUpload(
                "myFile.json",
                "My File",
                "application/json",
                fileBytes
            )

            // upload the file to the selected record
            SecretsManager.uploadFile(options, ownerRecord, myFile);

        } catch (Exception e) {
            System.out.println("KSM ran into an problem: " + e.getMessage());
        }
    }
}
```

### Remove Files from a Record <a href="#remove-files-from-a-record" id="remove-files-from-a-record"></a>

> SDK Version Required: 17.1.1 or higher

This feature add the ability to remove file attachments from records using the `UpdateOptions` class with the `linksToRemove` parameter.

**Prerequisites:**

* Record UID or KeeperRecord object containing files
* File UIDs of the files to be removed
* Files must exist on the record to be removed

{% tabs %}
{% tab title="Remove Files" %}

<table><thead><tr><th>Parameter</th><th width="212.59765625">Type</th><th width="109.30078125">Required</th><th>Description</th></tr></thead><tbody><tr><td><code>options</code></td><td>SecretsManagerOptions</td><td>Yes</td><td>Preconfigured options</td></tr><tr><td><code>record</code></td><td>KeeperRecord</td><td>Yes</td><td>The record to update</td></tr><tr><td><code>updateOptions</code></td><td>UpdateOptions</td><td>Yes</td><td>Options containing files to remove</td></tr></tbody></table>
{% endtab %}

{% tab title="UpdateOptions" %}

<table><thead><tr><th width="155.65625">Parameter</th><th>Type</th><th>Required</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td><code>transactionType</code></td><td>UpdateTransactionType</td><td>No</td><td><code>null</code></td><td>Transaction type for batch operations</td></tr><tr><td><code>linksToRemove</code></td><td>List&#x3C;String></td><td>Yes</td><td></td><td>List of file UIDs to remove</td></tr></tbody></table>
{% endtab %}

{% tab title="Example (Java)" %}

```java
// Remove files that start with "teamp_"
List<String> filesToRemove = new ArrayList<>();
for (KeeperFile file : record.getFiles()) {
    if (file.getData().getTitle().startsWith("temp_")) {
        filesToRemove.add(file.getFileUid());
    }
}

if (!filesToRemove.isEmpty()) {
    UpdateOptions updateOptions = new UpdateOptions(null, filesToRemove);
    SecretsManager.updateSecretWithOptions(options, record, updateOptions);
}
```

{% endtab %}

{% tab title="Example (Kotlin)" %}

```kotlin
// Remove files that start with "teamp_"
val filesToRemove = record.files
    ?.filter { it.data?.title?.startsWith("temp_") == true }
    ?.map { it.fileUid }
    ?: emptyList()

if (filesToRemove.isNotEmpty()) {
    updateSecretWithOptions(
        options,
        record,
        UpdateOptions(linksToRemove = filesToRemove)
    )
}
```

{% endtab %}
{% endtabs %}

**Full Example Usage:**

```java
import com.keepersecurity.secretsManager.core.*;
import java.util.*;

// Get record with files
QueryOptions queryOptions = new QueryOptions(
    Arrays.asList(recordUid),
    Collections.emptyList(),
    true  // request files
);

KeeperSecrets secrets = SecretsManager.getSecrets2(options, queryOptions);
KeeperRecord record = secrets.getRecords().get(0);

// Remove specific files
List<String> fileUidsToRemove = Arrays.asList("fileUid1", "fileUid2");

UpdateOptions updateOptions = new UpdateOptions(
    null,              // transactionType
    fileUidsToRemove  // linksToRemove
);

SecretsManager.updateSecretWithOptions(options, record, updateOptions);
```

### Create a Secret

#### Prerequisites:

* Shared folder UID
  * Shared folder must be accessible by the Secrets Manager Application
  * You and the Secrets Manager application must have edit permission
  * There must be at least one record in the shared folder
* Created records and record fields must be formatted correctly
  * See the [documentation](/keeperpam/secrets-manager/about/field-record-types.md) for expected field formats for each record type
* TOTP fields accept only URL generated outside of the KSM SDK
* After record creation, you can upload file attachments using [uploadFile](#upload-a-file)

{% tabs %}
{% tab title="Create a Record" %}

```java
SecretsManager.createSecret(options, folderUid, newRecordData, secrets);
```

<table><thead><tr><th width="201">Parameter</th><th width="230">Type</th><th width="150">Required</th><th>Default</th></tr></thead><tbody><tr><td><code>options</code></td><td>SecretsManagerOptions</td><td>Yes</td><td></td></tr><tr><td><code>folderUid</code></td><td>String</td><td>Yes</td><td></td></tr><tr><td><code>newRecordData</code></td><td>KeeperRecordData</td><td>Yes</td><td></td></tr><tr><td><code>secrets</code></td><td>KeeperSecrets</td><td>Optional</td><td>Freshly fetched list of all secrets from the Keeper servers</td></tr></tbody></table>
{% endtab %}

{% tab title="Create Record in Sub-folder" %}

```java
SecretsManager.createSecret2(options, createOptions, newRecordData, folders);
```

<table><thead><tr><th width="201">Parameter</th><th width="230">Type</th><th width="150">Required</th><th>Default</th></tr></thead><tbody><tr><td><code>options</code></td><td>SecretsManagerOptions</td><td>Yes</td><td></td></tr><tr><td><code>createOptions</code></td><td>CreateOptions</td><td>Yes</td><td></td></tr><tr><td><code>newRecordData</code></td><td>KeeperRecordData</td><td>Yes</td><td></td></tr><tr><td><code>folders</code></td><td>KeeperFolder[]</td><td>Optional</td><td>Freshly fetched list of all folders from the Keeper servers</td></tr></tbody></table>
{% endtab %}

{% tab title="Login Record Example" %}
This example creates a login type record with a login value and a generated password.

{% hint style="info" %}
Replace '`[FOLDER UID]`' in the example with the UID of a shared folder that your Secrets Manager Application has access to.
{% endhint %}

```java
import com.keepersecurity.secretsManager.core.*;

KeeperRecordData newRecordData = new KeeperRecordData(
        "Sample KSM Record: Java",
        "login",
        Arrays.asList(
                new Login("My Username"),
                new Password(CryptoUtils.generatePassword())
        ),
        null,
        "This is a \nmultiline\n\n\tnote"
);

String recordUid = SecretsManager.createSecret(options, folderUid, newRecordData);
```

{% endtab %}

{% tab title="serverCredentials Example" %}
This example creates a `serverCredentials` record — a server login with host, username, and password.

{% hint style="info" %}
Replace `<FOLDER UID>` with the UID of a shared folder your Secrets Manager Application has access to.
{% endhint %}

```java
import com.keepersecurity.secretsManager.core.*;

KeeperRecordData newRecordData = new KeeperRecordData(
        "prod-ssh-server",
        "serverCredentials",
        Arrays.asList(
                new Hosts(new Host("prod.example.com", "22")),
                new Login("admin"),
                new Password(CryptoUtils.generatePassword())
        )
);

String recordUid = SecretsManager.createSecret(options, "<FOLDER UID>", newRecordData);
```

{% endtab %}
{% endtabs %}

#### databaseCredentials Example

This example creates a `databaseCredentials` record — a database login with connection details.

{% hint style="info" %}
Replace `<FOLDER UID>` with the UID of a shared folder your Secrets Manager Application has access to.
{% endhint %}

```java
import com.keepersecurity.secretsManager.core.*;

KeeperRecordData dbRecordData = new KeeperRecordData(
        "prod-mysql",
        "databaseCredentials",
        Arrays.asList(
                new Text("MySQL"),
                new Hosts(new Host("db.example.com", "3306")),
                new Login("db_admin"),
                new Password(CryptoUtils.generatePassword())
        )
);

String recordUid = SecretsManager.createSecret(options, "<FOLDER UID>", dbRecordData);
```

#### sshKeys Example

This example creates an `sshKeys` record — an SSH key pair with host and login.

{% hint style="info" %}
Replace `<FOLDER UID>` with the UID of a shared folder your Secrets Manager Application has access to.
{% endhint %}

```java
import com.keepersecurity.secretsManager.core.*;

KeeperRecordData sshRecordData = new KeeperRecordData(
        "prod-ssh-key",
        "sshKeys",
        Arrays.asList(
                new Login("admin"),
                new KeyPairs(new KeyPair("<PUBLIC KEY>", "<PRIVATE KEY>")),
                new Hosts(new Host("prod.example.com", "22"))
        )
);

String recordUid = SecretsManager.createSecret(options, "<FOLDER UID>", sshRecordData);
```

### Delete a Secret

The Java/Kotlin KSM SDK can delete records in the Keeper Vault.

{% tabs %}
{% tab title="Delete Secret" %}

```java
deleteSecret(smOptions, recordUids);
```

<table><thead><tr><th>Parameter</th><th width="250.66666666666666">Type</th><th align="center">Required</th></tr></thead><tbody><tr><td><code>smOptions</code></td><td><code>SecretsManagerOptions</code></td><td align="center">Yes</td></tr><tr><td><code>recordUids</code></td><td><code>List&#x3C;String></code></td><td align="center">Yes</td></tr></tbody></table>
{% endtab %}

{% tab title="Example" %}

```java
// setup secrets manager
LocalConfigStorage storage = new LocalConfigStorage("ksm-config.json");
//initializeStorage(storage, "<One Time Access Token>")
SecretsManagerOptions smOptions = new SecretsManagerOptions(storage);

// delete a specific secret by record UID
SecretsManager.deleteSecret(smOptions, List.of("EG6KdJaaLG7esRZbMnfbFA"));
```

{% endtab %}
{% endtabs %}

### Caching

To protect against losing access to your secrets when network access is lost, the Java SDK allows caching of secrets to the local machine in an encrypted file.

**Setup and Configure Cache**

In order to setup caching in the Java SDK, include a caching post function as the second argument when instantiating a`SecretsManagerOptions` object.

The Java SDK includes a default caching function `cachingPostFunction` which stores cached queries to a file.

```java
//create options with caching
SecretsManagerOptions options = new SecretsManagerOptions(storage, SecretsManager::cachingPostFunction);

//example get all secrets
SecretsManager.getSecrets(options)
```

### Folders

Folders have full CRUD support - create, read, update and delete operations.

### Read Folders

Downloads full folder hierarchy.

```java
getFolders(options: SecretsManagerOptions): List<KeeperFolder>
```

**Response**

Type: `List<KeeperFolder>`

**Example Usage**

```java
import com.keepersecurity.secretsManager.core.*;
SecretsManagerOptions options = new SecretsManagerOptions(new LocalConfigStorage("ksm-config.json"));
List<KeeperFolder> folders = SecretsManager.getFolders(options);
```

### Create a Folder

Requires `CreateOptions` and folder name to be provided. The folder UID parameter in `CreateOptions` is required - UID of a shared folder, while sub-folder UID is optional and if missing new regular folder is created directly under the parent (shared folder). There's no requirement for the sub-folder to be a direct descendant of the parent shared folder - it could be many levels deep.

```java
createFolder(options: SecretsManagerOptions, createOptions: CreateOptions, folderName: String, folders: List<KeeperFolder> = getFolders(options)): String
```

<table><thead><tr><th width="181.85161529417937">Parameter</th><th width="205.97869483802478">Type</th><th width="107.65234375">Required</th><th width="105.50390625">Default</th><th>Description</th></tr></thead><tbody><tr><td><code>options</code></td><td><code>SecretsManagerOptions</code></td><td>Yes</td><td></td><td>Preconfigured options</td></tr><tr><td><code>createOptions</code></td><td><code>CreateOptions</code></td><td>Yes</td><td></td><td>The parent and sub-folder UIDs</td></tr><tr><td><code>folderName</code></td><td><code>String</code></td><td>Yes</td><td></td><td>The Folder name</td></tr><tr><td><code>folders</code></td><td><code>List&#x3C;KeeperFolder></code></td><td>No</td><td><code>List&#x3C;KeeperFolder></code></td><td>List of folders to use in the search for parent and sub-folder from CreateOptions</td></tr></tbody></table>

```kotlin
data class CreateOptions  constructor(
    val folderUid: String,
    val subFolderUid: String? = null,
)
```

```kotlin
data class KeeperFolder(
    val folderKey: ByteArray,
    val folderUid: String,
    val parentUid: String? = null,
    val name: String
)
```

**Example Usage**

```java
import com.keepersecurity.secretsManager.core.*;
SecretsManagerOptions options = new SecretsManagerOptions(new LocalConfigStorage("ksm-config.json"));
CreateOptions co := new CreateOptions("[PARENT_SHARED_FOLDER_UID]");
String folderUid = SecretsManager.createFolder(options, co, "new_folder");
```

### Update a Folder

Updates the folder metadata - currently folder name only.

```java
updateFolder(options: SecretsManagerOptions, folderUid: String, folderName: String, folders: List<KeeperFolder> = getFolders(options))
```

<table><thead><tr><th width="154.85161529417937">Parameter</th><th width="214.44744483802478">Type</th><th width="110.97265625">Required</th><th width="98.140625">Default</th><th>Description</th></tr></thead><tbody><tr><td><code>options</code></td><td><code>SecretsManagerOptions</code></td><td>Yes</td><td></td><td>Preconfigured options</td></tr><tr><td><code>folderUid</code></td><td><code>String</code></td><td>Yes</td><td></td><td>The folder UID</td></tr><tr><td><code>folderName</code></td><td><code>String</code></td><td>Yes</td><td></td><td>The new folder name</td></tr><tr><td><code>folders</code></td><td><code>List&#x3C;KeeperFolder></code></td><td>No</td><td><code>List&#x3C;KeeperFolder></code></td><td>List of folders to use in the search for parent folder</td></tr></tbody></table>

**Example Usage**

```java
import com.keepersecurity.secretsManager.core.*;
SecretsManagerOptions options = new SecretsManagerOptions(new LocalConfigStorage("ksm-config.json"));
SecretsManager.updateFolder(options, "[FOLDER_UID]", "new_folder_name");
```

### Delete Folders

Removes a list of folders. Use `forceDeletion` flag to remove non-empty folders.

{% hint style="info" %}
When using forceDeletion avoid sending parent with its children folder UIDs. Depending on the delete order you may get an error - *ex.* if parent force-deleted child first. There's no guarantee that list will always be processed in FIFO order.
{% endhint %}

{% hint style="info" %}
Any folder UIDs missing from the vault or not shared with the KSM Application do not throw an exception. Check `responseCode` on each entry in the returned `SecretsManagerDeleteFolderResponse.folders` list to detect a per-folder failure.
{% endhint %}

```java
SecretsManagerDeleteFolderResponse deleteFolder(SecretsManagerOptions options, List<String> folderUids, boolean forceDeletion)
```

**Response**

Type: `SecretsManagerDeleteFolderResponse`

```java
public class SecretsManagerDeleteFolderResponse {
    public List<SecretsManagerDeleteFolderResponseRecord> folders;
}

public class SecretsManagerDeleteFolderResponseRecord {
    public String errorMessage;   // null on success, set on per-item failure
    public String folderUid;
    public String responseCode;   // "ok" on success
}
```

<table><thead><tr><th width="180.85161529417937">Parameter</th><th width="210.41619483802478">Type</th><th width="113.9765625">Required</th><th width="95.515625">Default</th><th>Description</th></tr></thead><tbody><tr><td><code>options</code></td><td><code>SecretsManagerOptions</code></td><td>Yes</td><td></td><td>Preconfigured options</td></tr><tr><td><code>folderUids</code></td><td><code>List&#x3C;String></code></td><td>Yes</td><td></td><td>The folder UID list</td></tr><tr><td><code>forceDeletion</code></td><td><code>Boolean</code></td><td>No</td><td><code>false</code></td><td>Force deletion of non-empty folders</td></tr></tbody></table>

**Example Usage**

```java
import com.keepersecurity.secretsManager.core.*;
SecretsManagerOptions options = new SecretsManagerOptions(new LocalConfigStorage("ksm-config.json"));
SecretsManager.deleteFolder(options, Arrays.asList("[FOLDER_UID1]", "[FOLDER_UID2]"), true);
```

### Record Field Classes

Each record field type is represented by a class. Cast the field to the corresponding class to access the field's value. See the [Record Types](/keeperpam/secrets-manager/about/field-record-types.md) documentation for a list of field types.

```java
List<KeeperRecordField> fields = record.getData().getFields();
for (KeeperRecordField field : fields) {
    if (field instanceof Login) {
        Login loginField = (Login) field;
        String loginValue = loginField.getValue().get(0);
    } else if (field instanceof Password) {
        Password passwordField = (Password) field;
        String passwordValue = passwordField.getValue().get(0);
    }
}
```

### Proxy Support

To route SDK traffic through an HTTP or HTTPS proxy, set `proxyUrl` on `SecretsManagerOptions`.

**Java — static factory (recommended):**

```java
SecretsManagerOptions options = SecretsManagerOptions.withProxy(
    storage, "http://proxy.local:8080");
```

**Kotlin — named parameter:**

```kotlin
val options = SecretsManagerOptions(storage, proxyUrl = "http://proxy.local:8080")
```

**Authenticated proxies** use the `http://user:password@host:port` URL form. Percent-encode reserved characters in the password (for example, `p%40ss` for `p@ss`).

#### Authenticated Proxies and the JVM Flag

Java disables Basic authentication over HTTPS CONNECT tunnels by default. The SDK clears this restriction automatically when proxy credentials are detected, but only if no other HTTP or HTTPS connection has loaded `HttpURLConnection` before the SDK's first call — which application servers and frameworks nearly always do first.

If you use an authenticated proxy, set this JVM flag before your application makes any other HTTP or HTTPS call:

```
-Djdk.http.auth.tunneling.disabledSchemes=
```

Pass it on the command line or via `JDK_JAVA_OPTIONS` (Java 9+). If the flag is not set in time, the SDK throws a `SecretsManagerException` naming this remedy rather than a bare 407 error.

#### Ambient Proxy Settings

When `proxyUrl` is not set, the SDK reads JVM system properties (`https.proxyHost`/`https.proxyPort`) and then the `HTTPS_PROXY`/`https_proxy` environment variables. `NO_PROXY`/`no_proxy` and `http.nonProxyHosts` exclusions are honored.

{% hint style="warning" %}
Starting in 17.4.0, the SDK honors ambient proxy settings that it previously ignored. If your environment sets `HTTPS_PROXY` or `https.proxyHost` for other tools, verify those values before upgrading.
{% endhint %}

#### Connection and Read Timeouts

`SecretsManagerOptions` exposes `connectTimeoutMillis` (default 5,000 ms) and `readTimeoutMillis` (default 30,000 ms). A stalled server raises `SocketTimeoutException` rather than hanging indefinitely. Use Kotlin named parameters to set only the values you need:

```kotlin
val options = SecretsManagerOptions(
    storage,
    connectTimeoutMillis = 10_000,
    readTimeoutMillis = 60_000
)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.keeper.io/keeperpam/secrets-manager/developer-sdk-library/java-sdk.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
