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 on how to use a custom security provider.
importstaticcom.keepersecurity.secretsManager.core.SecretsManager.initializeStorage;importcom.keepersecurity.secretsManager.core.LocalConfigStorage;importcom.keepersecurity.secretsManager.core.SecretsManagerOptions;importjava.security.Security;importorg.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;// oneTimeToken is used only once to initialize the storage// after the first run, subsequent calls will use "ksm-config.txt" fileString oneTimeToken ="[One Time Access Token]";LocalConfigStorage storage =newLocalConfigStorage("ksm-config.txt");Security.addProvider(newBouncyCastleFipsProvider());try {initializeStorage(storage, oneTimeToken);SecretsManagerOptions options =newSecretsManagerOptions(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()); }
Object containing all Keeper records, or records that match the given filter criteria
Example Usage
Retrieve all Secrets
importcom.keepersecurity.secretsManager.core.SecretsManagerOptions;importcom.keepersecurity.secretsManager.core.SecretsManager;importcom.keepersecurity.secretsManager.core.KeeperRecord;importcom.keepersecurity.secretsManager.core.KeeperSecrets;importjava.security.Security;importorg.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());//get secretsSecretsManagerOptions options =newSecretsManagerOptions(storage);KeeperSecrets secrets =SecretsManager.getSecrets(options);//get records from secretsList<KeeperRecord> records =secrets.getRecords();
Retrieve one secret by UID
importcom.keepersecurity.secretsManager.core.SecretsManagerOptions;importcom.keepersecurity.secretsManager.core.SecretsManager;importcom.keepersecurity.secretsManager.core.KeeperRecord;importcom.keepersecurity.secretsManager.core.KeeperSecrets;importjava.security.Security;importorg.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());//get secretsSecretsManagerOptions options =newSecretsManagerOptions(storage);KeeperSecrets secrets =SecretsManager.getSecrets(options);// identify one or more record UID to fetch secrets byList<String> uidFilter =List.of("[XXX]");// fetch secrets with the filterKeeperSecrets secrets =SecretsManager.getSecrets(options, uidFilter);//get records from secretsList<KeeperRecord> records =secrets.getRecords();
Retrieve Secrets by Title
// get all matching recordsgetSecretsByTitle(recordTitle: String):List<KeeperRecord>// get only the first matching recordgetSecretByTitle(recordTitle: String):KeeperRecord
Parameter
Type
Required
Description
recordTitle
String
Yes
Record title to search for
Example Usage
importcom.keepersecurity.secretsManager.core.*;importjava.util.List;publicclassKSMSample {publicstaticvoidmain(String[] args){// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());// get pre-initialized storageKeyValueStorage storage =newLocalConfigStorage("ksm-config.json");try {SecretsManagerOptions options =newSecretsManagerOptions(storage);// title of the record to fetchString recordTitle ="My Credentials";// search for record by titleKeeperRecord myCredentials =secrets.getRecords().getSecretByTitle(recordTitle);// print out record detailsSystem.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.
secret.getPassword()
importcom.keepersecurity.secretsManager.core.SecretsManagerOptions;importcom.keepersecurity.secretsManager.core.SecretsManager;importcom.keepersecurity.secretsManager.core.KeeperRecord;importcom.keepersecurity.secretsManager.core.KeeperSecrets;importjava.security.Security;importorg.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());//get secretsSecretsManagerOptions options =newSecretsManagerOptions(storage);KeeperSecrets secrets =SecretsManager.getSecrets(options);//get the first recordList<KeeperRecord> records =secrets.getRecords().get(0);//get the password from the first recordfirstRecord.getPassword()
Retrieve Fields
secret.getData().getField(<FIELD_TYPE>)
importcom.keepersecurity.secretsManager.core.SecretsManagerOptions;importcom.keepersecurity.secretsManager.core.SecretsManager;importcom.keepersecurity.secretsManager.core.KeeperRecord;importcom.keepersecurity.secretsManager.core.KeeperSecrets;importjava.security.Security;importorg.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());//get secretsSecretsManagerOptions options =newSecretsManagerOptions(storage);KeeperSecrets secrets =SecretsManager.getSecrets(options);//get the first recordList<KeeperRecord> records =secrets.getRecords();KeeperRecord firstRecord =secrets.getRecords().get(0);//get the password from the first recordKeeperRecordField pwd =firstRecord.getData().getField(Password.class)
To get a field value, you will need to cast the return to the class of the corresponding field type. For a list of field types see the Record Types page.
Keeper Notation
Notation.getValue(secret,"<query>");// Query example "<RECORD UID>/field/login"
importstaticcom.keepersecurity.secretsManager.core.SecretsManager.*import static com.keepersecurity.secretsManager.core.Notation.*;importjava.security.Security;importorg.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());// get secretsKeeperSecrets secrets =getSecrets(options);// get login with dot notationString login =getValue(secrets,"BediNKCMG21ztm5xGYgNww/field/login");
importstaticcom.keepersecurity.secretsManager.core.Notation.*;importstaticcom.keepersecurity.secretsManager.core.TotpCode.*;importjava.security.Security;importorg.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;...// get secretsKeeperSecrets secrets =getSecrets(options);// get TOTP url from recordString url=getValue(secrets,"BediNKCMG21ztm5xGYgNww/field/oneTimeCode");// get TOTP codeTotpCode totp =uriToTotpCode(url);
Parameter
Type
Required
Default
Description
url
String
Yes
TOTP Url
Update Values in a Secret
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.
importcom.keepersecurity.secretsManager.core.KeeperRecord;importcom.keepersecurity.secretsManager.core.KeeperSecrets;importcom.keepersecurity.secretsManager.core.SecretsManagerOptions;importstaticcom.keepersecurity.secretsManager.core.SecretsManager.*;// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());// get secretsSecretsManagerOptions options =SecretsManagerOptions(storage);KeeperSecrets secrets =getSecrets(options);// we'll update the first recordKeeperRecord recordToUpdate =secrets.getRecords().get(0);// update passwordrecordToUpdate.updatePassword("aP1$t367QOCvL$eM$bG#");// save changesupdateSecret(options, recordToUpdate);
importcom.keepersecurity.secretsManager.core.KeeperRecord;importcom.keepersecurity.secretsManager.core.KeeperSecrets;importcom.keepersecurity.secretsManager.core.SecretsManagerOptions;importstaticcom.keepersecurity.secretsManager.core.SecretsManager.*;...// get secretsSecretsManagerOptions options =SecretsManagerOptions(storage);KeeperSecrets secrets =getSecrets(options);// we'll update the first recordKeeperRecord record =secrets.getRecords().get(0);// rotate password on the recordrecord.updatePassword("aP1$t367QOCvL$eM$bG#");// start a transactionupdateSecret(options, record, transactionType =UpdateTransactionType.GENERAL);// rotate password on remote hostboolean success =rotateRemoteSshPassword("aP1$t367QOCvL$eM$bG#");// complete the transaction - commit or rollbackcompleteTransaction(options,record.recordUid, rollback =!success);
Update Secret is used to save changes made to a secret. Once updateSecret is performed successfully, the changes are reflected in the Keeper Vault.
importstaticcom.keepersecurity.secretsManager.core.SecretsManager;importcom.keepersecurity.secretsManager.core.SecretsManagerOptions;importcom.keepersecurity.secretsManager.core.KeeperRecord;importcom.keepersecurity.secretsManager.core.KeeperSecrets;// get secretsSecretsManagerOptions options =SecretsManagerOptions(storage);KeeperSecrets secrets =getSecrets(options);// we'll update the first recordKeeperRecord recordToUpdate =secrets.getRecords().get(0);// update passwordrecordToUpdate.updatePassword("aP1$t367QOCvL$eM$bG#");// save changesSecretsManager.updateSecret(options, recordToUpdate);
// get field to editLogin recordLogin = (Login) recordToUpdate.getData().getField(Login.class);// update field valuerecordLogin.getValue().set(0,"New Login");// save changesSecretsManager.updateSecret(options, recordToUpdate);
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 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.
importcom.keepersecurity.secretsManager.core.CryptoUtils;// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());// get field to editPassword recordPassword = (Password) recordToUpdate.getData().getField(Password.class);// generate a random passwordString password =CryptoUtils.generatePassword();// update field valuerecordPassword.getValue().set(0, password);// save changesSecretsManager.updateSecret(options, recordToUpdate);
Parameter
Type
Required
Default
length
int
Optional
64
lowercase
int
Optional
0
uppercase
int
Optional
0
digits
int
Optional
0
specialCharacters
int
Optional
0
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
SecretsManager.downloadFile(file):ByteArray
importstaticcom.keepersecurity.secretsManager.core.SecretsManager;importcom.keepersecurity.secretsManager.core.KeeperRecord;importcom.keepersecurity.secretsManager.core.KeeperFile;// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());// download the first file from the first recordKeeperRecord firstRecord =secrets.getRecords().get(0);KeeperFile file =firstRecord.getFileByName("acme.cer");byte[] fileBytes =SecretsManager.downloadFile(file);// write file to a disktry (FileOutputStream fos =newFileOutputStream(file.getData().getName())) {fos.write(fileBytes);} catch (IOException ioException){ioException.printStackTrace();}
Parameter
Type
Required
Default
Description
file
KeeperFile
Yes
File to download
Response
Type:ByteArray
ByteArray of file for download
Download a Thumbnail
SecretsManager.downloadThumbnail(file):ByteArray
importstaticcom.keepersecurity.secretsManager.core.SecretsManager;importcom.keepersecurity.secretsManager.core.KeeperRecord;importcom.keepersecurity.secretsManager.core.KeeperFile;// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());// download the first file from the first recordKeeperRecord firstRecord =secrets.getRecords().get(0);KeeperFile file =firstRecord.getFileByName("acme.cer");byte[] fileBytes =SecretsManager.downloadThumbnail(file);// write file to a disktry (FileOutputStream fos =newFileOutputStream(file.getData().getName())) {fos.write(fileBytes);} catch (IOException ioException){ioException.printStackTrace();}
What the name of the file will be in Keeper once uploaded
title
string
Yes
What the title of the file will be in Keeper once uploaded
type
string
Optional
The mime type of data in the file. 'application/octet-stream' will be used if nothing is given
data
ByteArray
Yes
File data as bytes
Example Usage
importcom.keepersecurity.secretsManager.core.*;importjava.io.File;importjava.io.FileInputStream;importjava.util.Arrays;publicclassKSMSample {publicstaticvoidmain(String[] args){// Ensure security provider is loadedSecurity.addProvider(newBouncyCastleFipsProvider());// get pre-initialized storageKeyValueStorage storage =newLocalConfigStorage("ksm-config.json");try {SecretsManagerOptions options =newSecretsManagerOptions(storage);// create a filter with the UID of the record we wantList<String> uidFilter =List.of("XXX");// fetch secrets with the filterKeeperSecrets secrets =SecretsManager.getSecrets(options, uidFilter);// get the desired secret to upload a file toKeeperRecord ownerRecord =secrets.getRecords().get(0);// get bytes from file to uploadFile file =newFile("./myFile.json");FileInputStream fl =newFileInputStream(file);byte[] fileBytes =newbyte[(int)file.length()];fl.read(fileBytes);fl.close();// create a Keeper File to uploadKeeperFileUpload myFile =newKeeperFileUpload("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()); } }}
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 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
Freshly fetched list of all folders from the Keeper servers
This example creates a login type record with a login value and a generated password.
Replace '[FOLDER UID]' in the example with the UID of a shared folder that your Secrets Manager Application has access to.
importcom.keepersecurity.secretsManager.core.*;KeeperRecordData newRecordData =newKeeperRecordData("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);
This example creates a record with a custom record type.
Replace '[FOLDER UID]' in the example with the UID of a shared folder that your Secrets Manager Application has access to.
importcom.keepersecurity.secretsManager.core.*;KeeperRecordData newRecordData =newKeeperRecordData("Sample Custom Type KSM Record: Java","Custom Login",// Record Type NameArrays.asList(new Hosts("My Custom Host lbl",// labeltrue,// requiredfalse,// private screenList.of(new Host("127.0.0.1","8000"))),// OR new Hosts(new Host("127.0.0.1", "8000"))new Login("My Custom Login lbl",true,false,List.of("login@email.com")),// OR new Login("username@email.com")new Password( "My Custom Password lbl",true,false,List.of(CryptoUtils.generatePassword())),// OR new Password(CryptoUtils.generatePassword())new Url("My Login Page",true,false,List.of("http://localhost:8080/login")),// OR new Url("http://localhost:8080/login")new SecurityQuestions("My Question 1",true,false,List.of(new SecurityQuestion("What is one plus one (write just a number)","2"))),// OR new SecurityQuestions(new SecurityQuestion("What is one plus one (write just a number)", "2"))new Phones("My Phone Number",true,false,List.of(new Phone("US","510-444-3333","2345","Mobile"))),// OR new Phones(new Phone("US", "510-444-3333", "2345", "Mobile"))new Date("My Date Lbl",true,false,List.of(1641934793000L) ),// OR new Date(1641934793000L),new Names("My Custom Name lbl",true,false,List.of(new Name("John","Patrick","Smith"))),// OR new Names(new Name("John", "Patrick", "Smith"))new OneTimeCode("My TOTP",true,false,List.of("otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example"))// OR new OneTimeCode("otpauth://totp/Example:alice@google.com?secret=JBSWY3DPEHPK3PXP&issuer=Example") ),Arrays.asList(new Phones(new Phone("US","(510) 123-3456")),new Phones(new Phone("US","510-111-3333","45674","Mobile")) ),"\tThis custom type record was created\n\tvia KSM Java Document Example");String recordUid =SecretsManager.createSecret(options,"[FOLDER UID]", newRecordData);
Delete a Secret
The Java/Kotlin KSM SDK can delete records in the Keeper Vault.
deleteSecret(smOptions, recordUids);
Parameter
Type
Required
smOptions
SecretsManagerOptions
Yes
recordUids
List<Sting>
Yes
// setup secrets managerval storage =LocalConfigStorage("ksm-config.json")//initializeStorage(storage, "<One Time Access Token>")val smOptions =SecretsManagerOptions(storage)// delete a specific secret by record UIDdeleteSecret(smOptions,List.of("EG6KdJaaLG7esRZbMnfbFA"));
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 aSecretsManagerOptions object.
The Java SDK includes a default caching function cachingPostFunction which stores cached queries to a file.
//create options with cachingSecretsManagerOptions options =newSecretsManagerOptions(storage, SecretsManager::cachingPostFunction);//example get all secretsSecretsManager.getSecrets(options)
Folders
Folders have full CRUD support - create, read, update and delete operations.
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.
Removes a list of folders. Use forceDeletion flag to remove non-empty folders.
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.
Any folders UIDs missing from the vault or not shared to the KSM Application will not result in error.