Developer SDKs

Sample code and SDK integration instructions for Keeper Secrets Manager

Overview

The Keeper Secrets Manager SDKs are purpose-built to provide extremely simple, fast and efficient access to Secrets Management functionality from all popular languages.

Installation

Reference the maven repository for snapshots: repositories { mavenCentral() maven { url "https://s01.oss.sonatype.org/content/groups/public/" } }

Add the following dependency to your project:

  • com.keepersecurity.secrets-manager:core:16.0.1-SNAPSHOT

The Java SDK supports JDK version 8 through 13.02+8

Authentication

The Secrets Manager SDK authenticates to the Keeper Vault using either the One Time Access Token or using the generated keys within the local configuration file. To generate one or more One Time Access Tokens from Commander CLI use the secrets-manager client add command.

$ keeper shell

... login ...

My Vault> secrets-manager client add --app MyApplication --unlock-ip

Initialization

Secrets Manager SDKs utilize a configuration file to hold connection tokens and settings. The following code samples show how to create a configuration file with the SDKs and an One-Time Access Token:

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

public class KSMSample {

    public static void main(String[] args){
        // oneTimeToken is used only once to initialize the storage
        // after the first run, subsequent calls will use ksm-config.json
        String oneTimeToken = "[ONE TIME TOKEN]";
        KeyValueStorage storage = new LocalConfigStorage("ksm-config.json");
        try {
            // after the first run, this line can be removed
            initializeStorage(storage, oneTimeToken);

            SecretsManagerOptions options = new SecretsManagerOptions(storage);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        
        // Rest of the code using `options`
    }
}

After a config file has been initialized, the One-Time Access Token should be removed from code

This initialization code will create a JSON configuration file on the device local storage with the following keys:

Key

Description

hostname

The destination host where your Enterprise tenant is located:

  • keepersecurity.com

  • keepersecurity.eu

  • keepersecurity.com.au

  • govcloud.keepersecurity.us

clientID

The hashed clientKey where clientKey is the Unique Client Device Identifier

privateKey

Client Device Private Key

serverPublicKeyId

Keeper Infrastructure's Public Key ID

appKey

Application Private Key

appOwnerPublicKey

Application Owner's Public Key

The following is an example of a generated configuration file:

ksm-config.json
{
  "hostname": "keepersecurity.com",
  "clientId": "ab2x3z/Acz0QFTiilm8UxIlqNLlNa25KMj=TpOqznwa4Si-h9tY7n3zvFwlXXDoVWkIs3xrMjcLGwgu3ilmq7Q==",
  "privateKey": "MLSHAgABCDEFGyqGSM49AEGCCqGSM49AwEHBG0wawIWALTARgmcnWx/DH+r7cKh4kokasdasdaDbvHmLABstNbqDwaCWhRANCAARjunta9SJdZE/LVXfVb22lpIfK4YMkJEDaFMOAyoBt0BrQ8aEhvrHN5/Z1BgZ/WpDm9dMR7E5ASIQuYUiAw0t9",
  "serverPublicKeyId": "10",
  "appKey": "RzhSIyKxbpjNu045TUrKaNREYIns+Hk9Kn8YtT+CtK0=",
  "appOwnerPublicKey": "Sq1W1OAnTwi8V/Vs/lhsin2sfSoaRfOwwDDBqoP+EO9bsBMWCzQdl9ClauDiKLXGmlmyx2xmSAdH+hlxvBRs6kU="
}

For information on other ways to create a config file, see the Config File documentation.

Retrieve All Secrets

import com.keepersecurity.secretsManager.core.*;
import static com.keepersecurity.secretsManager.core.SecretsManager.*;
import java.io.FileOutputStream;

public class KSMSample {
  
  public static void main(String[] args){
    // get pre-initialized storage
    KeyValueStorage storage = new LocalConfigStorage("ksm-config.json");
    try { 
        SecretsManagerOptions options = new SecretsManagerOptions(storage);
        
        // get all available secrets
        KeeperSecrets secrets = SecretsManager.getSecrets(options);
        
        // print out record details
        System.out.println(secrets.getRecords());
      } catch (Exception e) {
        System.out.println(e.getMessage());
      } 
    }
}

These examples assumes a Secrets Manager config file has already been initialized.

See the Initialization section for how to initialize a config file.

Retrieve One Individual Secret

Get Secrets By Record Title

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

public class KSMSample {
    public static void main(String[] args){
        // get pre-initialized storage
        KeyValueStorage storage = new LocalConfigStorage("ksm-config.json");
        try {
            SecretsManagerOptions options = new SecretsManagerOptions(storage);

            // title of the record to fetch
            String recordTitle = "My Credentials";
            
            // search for record by title
            KeeperRecord myCredentials = secrets.getRecords().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());
        }
    }
}

Get Secrets By Record UID

In this example, the Record UID is XXX

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

public class KSMSample {
    public static void main(String[] args){
        // 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 from the fetch results
            KeeperRecord myCredentials = secrets.getRecords().get(0);

            // 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());
        }
    }
}

These examples assumes a Secrets Manager config file has already been initialized.

See the Initialization section for how to initialize a config file.

Retrieve a Password

Example to retrieve an individual record password field.

In this example, the Record UID is XXX

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

public class KSMSample {
    public static void main(String[] args){
        // 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 from the fetch results
            KeeperRecord myCredentials = secrets.getRecords().get(0);

            // get and print out password
            String pwd = myCredentials.getPassword();
            System.out.println("Password from Keeper: " + pwd);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

These examples assumes a Secrets Manager config file has already been initialized.

See the Initialization section for how to initialize a config file.

Download a File Attachment

import com.keepersecurity.secretsManager.core.*;

import java.io.FileOutputStream;
import java.util.List;

public class KSMSample {
    public static void main(String[] args){
        // 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 from the fetch results
            KeeperRecord myCredentials = secrets.getRecords().get(0);

            // get a file reference by filename from the record
            KeeperFile file = myCredentials.getFileByName("acme.cer");

            // download the file
            byte[] fileBytes = SecretsManager.downloadFile(file);
            String filename = file.getData().getName();
            FileOutputStream fos = new FileOutputStream(filename);
            fos.write(fileBytes);
            System.out.println("Downloaded File: " + filename);
        } catch (Exception e) {
            System.out.println("KSM ran into an problem: " + e.getMessage());
        }
    }
}

These examples assumes a Secrets Manager config file has already been initialized.

See the Initialization section for how to initialize a config file.

Upload a File Attachment

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){
        // 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());
        }
    }
}

These examples assumes a Secrets Manager config file has already been initialized

See the Initialization section for how to initialize a config file.

Retrieve TOTP Codes

import com.keepersecurity.secretsManager.core.*;

public class KSMSample {
    public static void main(String[] args){
        // get pre-initialized storage
        KeyValueStorage storage = new LocalConfigStorage("ksm-config.json");
        try {
            SecretsManagerOptions options = new SecretsManagerOptions(storage);

            // fetch secrets
            KeeperSecrets secrets = SecretsManager.getSecrets(options);

            // get the totp url from the desired secret
            String totpUrl = Notation.getValue(secrets, "XXX/field/oneTimeCode");

            // get TOTP code
            TotpCode totpCode = TotpCode.uriToTotpCode(totpUrl);
            System.out.println("TOTP: " + totpCode.getCode());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

These examples assumes a Secrets Manager config file has already been initialized.

See the Initialization section for how to initialize a config file.

Update a Password

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

public class KSMSample {
    public static void main(String[] args){
        // 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 from the fetch results
            KeeperRecord myCredentials = secrets.getRecords().get(0);

            //update the password and save changes to the record
            myCredentials.updatePassword("aP1$t367QOCvL$eM$bG#");
            SecretsManager.updateSecret(options, myCredentials);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Generate a Password

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

public class KSMSample {
    public static void main(String[] args){
        // 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 = Arrays.asList("XXX");

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

            // get the desired secret from the fetch results
            KeeperRecord myCredentials = secrets.getRecords().get(0);

            // create a new password
            String password = CryptoUtils.generatePassword();

            // set new password to the record
            myCredentials.updatePassword(password);
            
            // save password to Keeper
            SecretsManager.updateSecret(options, myCredentials);

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

These examples assumes a Secrets Manager config file has already been initialized.

See the Initialization section for how to initialize a config file.

Create a Secret

The Secrets Manager SDKs provide the ability to create records in the Keeper vault.

The UID of a shared folder that your Secrets Manager Application has access to is required to create records. You must also have edit permissions in the shared folder, and there must be at least one other record in the folder. The new record will be placed in that folder. In the examples below, replace [FOLDER UID] with the shared folder's UID.

import com.keepersecurity.secretsManager.core.*;

import java.util.List;

public class KSMSample {
    // Folder where the new record will be stored
    static String folderUid = "[FOLDER UID]";

    public static void addLoginRecord(){
        LocalConfigStorage storage = new LocalConfigStorage("ksm-config.txt");
        SecretsManagerOptions options = new SecretsManagerOptions(storage);

        KeeperSecrets secrets = SecretsManager.getSecrets(options);

        KeeperRecordData newRecordData = new KeeperRecordData(
                "Sample Example KSM Record",
                "login",
                List.of(
                        new Login("username@email.com"),
                        new Password("Pa$$word123")
                ),
                null,
                "\tThis record was created\n\tvia KSM Documentation Java Example"
        );

        SecretsManager.createSecret(options, folderUid, newRecordData, secrets);
    }

    public static void main(String[] args) {
        addLoginRecord();
    }
}

Additional secret creation features and Record Type and Record Fields validation coming in future releases of Keeper Secrets Manager

Delete a Secret

Secrets Manager can be used to delete records from the Keeper Vault.

In order to delete a record, the Secrets Manager application must have access to the shared folder that the record is in, and the application must have edit capability. The record UID is required by Secrets Manager SDKs in order to delete the record.

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

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

Script Integration

Keeper Secrets Manager CLI provides a wrapper function that executes any arbitrary system call and replaces environmental variables with values from the Keeper Vault.

Secrets Manager CLI Exec Command

Vault and Admin SDKs

For higher level functionality at the Vault and Administrative level, please see the Vault SDKs page which contains links to various development tools.

Vault SDKs

Last updated