Developer SDKs
Sample code and SDK integration instructions for Keeper Secrets Manager
Last updated
Was this helpful?
Sample code and SDK integration instructions for Keeper Secrets Manager
Last updated
Was this helpful?
The Keeper Secrets Manager SDKs are purpose-built to provide extremely simple, fast and efficient access to Secrets Management functionality from all popular languages.
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.6.4
The Java SDK supports JDK version 8
through 13.02+8
Reference the maven repository for snapshots:
repositories {
mavenCentral()
maven("https://s01.oss.sonatype.org/content/groups/public/")
}
Add the following dependency to your project:
com.keepersecurity.secrets-manager:core:16.0.1-SNAPSHOT
npm install @keeper-security/secrets-manager-core
The JavaScript SDK supports Node version 11
through 16.12.0
pip3 install -U keeper-secrets-manager-core
The Python SDK supports Python version 3.6
through 3.10
dotnet add package Keeper.SecretsManager
The .Net SDK supports .Net version 4.7
and 4.8
Or .Net Core version 2.1
and later
import (
ksm "github.com/keeper-security/secrets-manager-go/core"
klog "github.com/keeper-security/secrets-manager-go/core/logger"
)
The GoLang SDK supports GoLang version 1.13
and later
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
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`
}
}
const {
getSecrets,
initializeStorage,
localConfigStorage,
downloadFile,
updateSecret
} = require('@keeper-security/secrets-manager-core')
const oneTimeToken = '[One Time Access Token]'
const getKeeperRecords = async () => {
const storage = localConfigStorage("ksm-config.json")
await initializeStorage(storage, oneTimeToken)
const {records} = await getSecrets({storage: storage})
console.log(records)
const firstRecord = records[0]
const firstRecordPassword = firstRecord.data.fields.find(x => x.type === 'password')
console.log(firstRecordPassword.value[0])
}
getKeeperRecords().finally()
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
oneTimeToken = "[One Time Access Token]"
secrets_manager = SecretsManager(
# One time tokens can be used only once - afterwards use the generated config file
token=oneTimeToken,
config=FileKeyValueStorage('ksm-config.json')
)
# Retrieve all password records (will also initialize config)
records = secrets_manager.get_secrets()
using System;
using SecretsManager;
var oneTimeToken = "[One Time Access Token]";
var storage = new LocalConfigStorage("ksm-config.json");
try {
// One time tokens can be used only once - afterwards use the generated config file
SecretsManagerClient.InitializeStorage(storage, oneTimeToken);
var options = new SecretsManagerOptions(storage);
// Retrieve all password records (will also initialize config)
var records = (await SecretsManagerClient.GetSecrets(options)).Records;
Console.WriteLine($"Received {records.Length} record(s)");
// get the password from the first record
var firstRecord = records[0];
var password = records[0].FieldValue("password").ToString();
Console.WriteLine($"Password: {password}");
} catch (Exception e) {
Console.WriteLine(e);
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
onetimeAccessCode := "[One Time Access Token]"
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Token: onetimeAccessCode,
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Retrieve all password records (will also initialize config)
allRecords, _ := sm.GetSecrets([]string{})
// Get password from first record:
firstRecord := allRecords[0]
firstRecordPassword := firstRecord.Password()
print("Password: [", firstRecordPassword, "]")
}
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:
{
"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.
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());
}
}
}
const {
getSecrets,
initializeStorage,
localConfigStorage,
downloadFile,
updateSecret
} = require('@keeper-security/secrets-manager-core')
const oneTimeToken = '[One Time Access Token]'
const getKeeperRecords = async () => {
const storage = localConfigStorage("ksm-config.json")
await initializeStorage(storage, oneTimeToken)
const {records} = await getSecrets({storage: storage})
}
getKeeperRecords().finally()
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
secrets_manager = SecretsManager(
config=FileKeyValueStorage('ksm-config.json')
)
all_records = secrets_manager.get_secrets()
# print out all record JSON data
for record in all_records:
# record.print() # print record to STDOUT
print(record.uid + " - " + record.title)
print("\tLogin: " + record.field('login')[0])
print("\tPassword: " + record.field('password')[0])
using System;
using System.Threading.Tasks;
using SecretsManager;
private static async Task retrieveAllSecrets()
{
// get pre-initialized storage
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
// get all available secrets
var records = (await SecretsManagerClient.GetSecrets(options)).Records;
foreach (var record in records)
{
Console.WriteLine(record.RecordUid + " - " + record.Data.title);
foreach (var field in record.Data.fields)
{
Console.WriteLine("\t" + field.label + " (" + field.type + "): [" + String.Join(", ", field.value) + "]");
}
}
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Retrieve all password records (will also initialize config)
allRecords, _ := sm.GetSecrets([]string{})
for _, record := range allRecords {
println("UID", record.Uid, ", title [", record.Title(), "]")
}
}
These examples assumes a Secrets Manager config file has already been initialized.
See the Initialization section for how to initialize a config file.
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());
}
}
}
const {
getSecretByTitle,
localConfigStorage,
} = require('@keeper-security/secrets-manager-core')
const getKeeperRecord = async () => {
const options = { storage: localConfigStorage("ksm-config.json")
const {myCredential} = await getSecretByTitle(options, "My Credential")
}
getKeeperRecord().finally()
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
secrets_manager = SecretsManager(
config=FileKeyValueStorage('ksm-config.json')
)
record_title = "My Record"
record = secrets_manager.get_secret_by_title(record_title)
if record:
print(record.uid + " - " + record.title)
print("\tLogin: " + record.field('login')[0])
print("\tPassword: " + record.field('password')[0])
else:
print("No record found with title: " + record_title)
using System;
using System.Threading.Tasks;
using SecretsManager;
private static async Task getOneIndividualSecret()
{
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
var records = (await SecretsManagerClient.GetSecretsByTitle(
options, "My Credentials")
).Records;
foreach (var record in records)
{
Console.WriteLine(record.RecordUid + " - " + record.Data.title);
foreach (var field in record.Data.fields)
{
Console.WriteLine("\t" + field.label + " (" + field.type + "): [" + String.Join(", ", field.value) + "]");
}
}
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Retrieve one individual record by Title
allRecords, _ := ksm.GetSecretsByTitle("My Credentials")
for _, record := range allRecords {
println("UID", record.Uid, ", title [", record.Title(), "]")
}
}
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());
}
}
}
const {
getSecretsByTitle,
localConfigStorage,
} = require('@keeper-security/secrets-manager-core')
const oneTimeToken = '[One Time Access Token]'
const getKeeperRecord = async () => {
const options = { storage: localConfigStorage("config.json")
const {myCredential} = await getSecrets(options, ["XXX"]
}
getKeeperRecord().finally()
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
secrets_manager = SecretsManager(
config=FileKeyValueStorage('ksm-config.json')
)
UID_FILTER = ['RECORD_UID']
record = secrets_manager.get_secrets(UID_FILTER)[0]
print(record.uid + " - " + record.title)
print("\tLogin: " + record.field('login')[0])
print("\tPassword: " + record.field('password')[0])
With a secret retrieved, individual fields can be retrieved from the secret.
# Get a standard template field
login = record.field('login', single=True)
# Get a custom field, e.g. API Key
api_key = record.custom_field('API Key', single=True)
using System;
using System.Threading.Tasks;
using SecretsManager;
private static async Task getOneIndividualSecret()
{
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
var records = (await SecretsManagerClient.GetSecrets(
options, new[] { "XXX" })
).Records;
foreach (var record in records)
{
Console.WriteLine(record.RecordUid + " - " + record.Data.title);
foreach (var field in record.Data.fields)
{
Console.WriteLine("\t" + field.label + " (" + field.type + "): [" + String.Join(", ", field.value) + "]");
}
}
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Retrieve one individual record by UID (will also initialize config)
allRecords, _ := sm.GetSecrets([]string{"[Record UID]"})
for _, record := range allRecords {
println("UID", record.Uid, ", title [", record.Title(), "]")
}
}
These examples assumes a Secrets Manager config file has already been initialized.
See the Initialization section for how to initialize a config file.
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());
}
}
}
secret.data.fields.find(x => x.type === 'password')
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
secrets_manager = SecretsManager(
config=FileKeyValueStorage('ksm-config.json')
)
# Get an individual secret by UID
UID_FILTER = 'XXX'
secret = secrets_manager.get_secrets([UID_FILTER])[0]
# Get a password from the secret
secret.field('password', single=True)
using System;
using System.Threading.Tasks;
using SecretsManager;
private static async Task retrieveAPassword()
{
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
var records = (await SecretsManagerClient.GetSecrets(
options, new[] { "XXX" })
).Records;
foreach (var record in records)
{
// retrieve "password" field
var passwordVal = record.FieldValue("password");
Console.WriteLine(record.RecordUid + " - " + record.Data.title + " - password=[" + passwordVal + "]");
}
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Retrieve all records (will also initialize config)
allRecords, _ := sm.GetSecrets([]string{})
for _, record := range allRecords {
passwordMethod1 := record.Password()
//passwordMethod2 := record.GetFieldValueByType("password") // retrieve password by accessing field
println("UID", record.Uid, ", Password [", passwordMethod1, "]")
}
}
These examples assumes a Secrets Manager config file has already been initialized.
See the Initialization section for how to initialize a config file.
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());
}
}
}
const file = firstRecord.files.find(x => x.data.name === 'acme.cer')
if (file) {
const fileBytes = await downloadFile(file)
fs.writeFileSync(file.data.name, fileBytes)
}
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
secrets_manager = SecretsManager(
config=FileKeyValueStorage('ksm-config.json')
)
# Get an individual secret by UID
UID_FILTER = 'XXX'
secret = secrets_manager.get_secrets([UID_FILTER])[0]
# Save all files to a /tmp folder (create folder if does not exist)
for file in secret.files:
print("file: %s" % file)
file.save_file("/tmp/" + file.name, True)
using System;
using System.IO;
using System.Threading.Tasks;
using SecretsManager;
private static async Task downloadAFileAttachment()
{
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
// get record by UID
var records = (await SecretsManagerClient.GetSecrets(
options, new[] { "XXX" })
).Records;
foreach (var record in records)
{
// download the file from the 1st record
var file = record.GetFileByName("acme.cer");
if (file != null)
{
var fileBytes = SecretsManagerClient.DownloadFile(file);
// write bytes to the disc
await File.WriteAllBytesAsync(file.Data.name, fileBytes);
}
}
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Retrieve all password records (will also initialize config)
allRecords, _ := sm.GetSecrets([]string{"[Record UID]"})
for _, record := range allRecords {
// Search file by title
file := record.FindFileByTitle("[FILE TITLE]")
// get file from the array by its index
//file := record.Files[0]
// Save file to the disc
file.SaveFile("/tmp/"+file.Name, true)
}
}
These examples assumes a Secrets Manager config file has already been initialized.
See the Initialization section for how to initialize a config file.
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());
}
}
}
import * as fs from "fs";
import {getSecrets, uploadFile} from "@keeper-security/secrets-manager-core";
// get record to attach file to
const {records} = await getSecrets({storage: storage}, ['XXX'])
const ownerRecord = records[0]
// get file data to upload
const fileData = fs.readFileSync('./assets/my-file.json')
// upload file to selected record
await uploadFile(options, ownerRecord, {
name: 'my-file.json',
title: 'Sample File',
type: 'application/json',
data: fileData
})
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
from keeper_secrets_manager_core.core import KeeperFileUpload
secrets_manager = SecretsManager(
config=FileKeyValueStorage('ksm-config.json')
)
# Get an individual secret by UID to attach the file to
UID_FILTER = 'XXX'
owner_record= secrets_manager.get_secrets([UID_FILTER])[0]
# Prepare file data for upload
my_file = KeeperFileUpload.from_file("./myFile.json", "myfile.json", "My File")
# Upload file attached to the owner record
upload_file(owner_record, file: my_file)
using System;
using System.IO;
using System.Threading.Tasks;
using SecretsManager;
private static async Task uploadFile()
{
// initalize storage and options
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
// get a record to attach the file to
var records = (await SecretsManagerClient.GetSecrets(
options, new[] { "XXX" })
).Records;
var ownerRecord = records[0];
// get file data to upload
var bytes = await File.ReadAllBytesAsync("my-file.json");
var myFile = new KeeperFileUpload(
"my-file1.json",
"My File",
null,
bytes
);
// upload file to selected record
await SecretsManagerClient.UploadFile(options, firstRecord, myFile);
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Get a record to upload the file to
allRecords, _ := sm.GetSecrets([]string{"[Record UID]"})
ownerRecord := allRecords[0]
// get file data and prepare for upload
dat, err := ioutil.ReadFile("/myFile.json")
var myFile := KeeperFileUpload{
Name: "myFile.json",
Title: "My File",
Type: "application/json",
Data: dat
}
// upload file to selected record
sm.UploadFile(ownerRecord, myFile)
}
These examples assumes a Secrets Manager config file has already been initialized
See the Initialization section for how to initialize a config file.
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());
}
}
}
const url = getValue(secrets, `keeper://${record.recordUid}/field/oneTimeCode`)
let totp = await getTotpCode(url)
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
# Import TOTP Util
from keeper_secrets_manager_core.utils import get_totp_code
secrets_manager = SecretsManager(
config=FileKeyValueStorage('ksm-config.json')
)
# Get an individual secret by UID
UID_FILTER = 'XXX'
secret = secrets_manager.get_secrets([UID_FILTER])[0]
# Get a TOTP URL from the secret
url = secret.get_standard_field_value('oneTimeCode', True)
# Get a One Time Token from the secret's TOTP field
code, _, _ = get_totp_code(url)
using System;
using System.Threading.Tasks;
using SecretsManager;
private static async Task retrieveTOTPCodes()
{
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
// get record by UID
var records = (await SecretsManagerClient.GetSecrets(
options, new[] { "XXX" })
).Records;
foreach (var record in records)
{
// Retrieve QR/TOTP Code from the record
string totpUrl = record.FieldValue("oneTimeCode").ToString();
// Convert TOTP URI using KSM's built-in function
var totp = CryptoUtils.GetTotpCode(totpUrl);
Console.WriteLine("QR Code: [" + totp.Code + "]");
Console.WriteLine("Expire in: [" + totp.TimeLeft + "]");
Console.WriteLine("Total time interval: [" + totp.Period + "]");
}
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Retrieve all password records (will also initialize config)
allRecords, _ := sm.GetSecrets([]string{"[Record UID]"})
for _, record := range allRecords {
totpUrl := record.GetFieldValueByType("oneTimeCode")
totpCode, _ := ksm.GetTotpCode(totpUrl)
println("QR Code: [", totpCode.Code, "]")
println("Expire in: [", totpCode.TimeLeft, "]")
println("Total time interval: [", totpCode.Period, "]")
}
}
These examples assumes a Secrets Manager config file has already been initialized.
See the Initialization section for how to initialize a config file.
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());
}
}
}
// update the password on the first record
firstRecordPassword.value[0] = 'aP1$t367QOCvL$eM$bG#'
await updateSecret({storage: storage}, firstRecord)
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
secrets_manager = SecretsManager(
config=FileKeyValueStorage('ksm-config.json')
)
# Get an individual secret by UID
UID_FILTER = ['XXX']
record = secrets_manager.get_secrets(UID_FILTER)[0]
# Set the new password to the secret
record.set_standard_field_value('password', 'NewPassword123')
# Save the secret with changes to the Keeper Vault
secrets_manager.save(record)
using System.Threading.Tasks;
using SecretsManager;
private static async Task updateAPassword()
{
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
var records = (await SecretsManagerClient.GetSecrets(
options, new[] { "XXX" })
).Records;
foreach (var record in records)
{
// Setting new value to the "password" field
record.UpdateFieldValue("password", "NewP4$$w0Rd");
// Persist field's new value to Keeper backend
await SecretsManagerClient.UpdateSecret(options, record);
}
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Retrieve all password records (will also initialize config)
allRecords, _ := sm.GetSecrets([]string{"[Record UID]"})
for _, record := range allRecords {
record.SetPassword("NewP4$$w0Rd") // Set the new password to the secret
record.RawJson = ksm.DictToJson(record.RecordDict) // Since we will be sending JSON to the server, we need to set the
sm.Save(record) // Save the secret with changes to the Keeper Vault
}
}
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());
}
}
}
// generate a random password
let password = await generatePassword()
// update the password on the first record
firstRecordPassword.value[0] = password
await updateSecret({storage: storage}, firstRecord)
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
# Import generate_password from Utils
from keeper_secrets_manager_core.utils import generate_password
secrets_manager = SecretsManager(
config=FileKeyValueStorage('ksm-config.json')
)
# Get an individual secret by UID
UID_FILTER = ['XXX']
secret = secrets_manager.get_secrets(UID_FILTER)[0]
# generate a random password
password = generate_password()
# Set the new password to the secret
record.set_standard_field_value('password', password)
# Save the secret with changes to the Keeper Vault
secrets_manager.save(record)
using System.Threading.Tasks;
using SecretsManager;
private static async Task generateNewPassword()
{
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
var records = (await SecretsManagerClient.GetSecrets(
options, new[] { "XXX" })
).Records;
foreach (var record in records)
{
// generate a new random password
var password = CryptoUtils.GeneratePassword();
// Setting new value to the "password" field
record.UpdateFieldValue("password", password);
// Persist field's new value to Keeper backend
await SecretsManagerClient.UpdateSecret(options, record);
}
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// Retrieve all password records (will also initialize config)
allRecords, _ := sm.GetSecrets([]string{"[Record UID]"})
for _, record := range allRecords {
newPassword, _ := ksm.GeneratePassword(64, 10, 10, 10, 10) // Generate new random password
record.SetPassword(newPassword) // Set the new password to the secret
sm.Save(record) // Save the secret with changes to the Keeper Vault
}
}
These examples assumes a Secrets Manager config file has already been initialized.
See the Initialization section for how to initialize a config file.
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();
}
}
// create login record and fields
let newRec = {
"title": "My JavaScript Record 1",
"type": "login",
"fields": [
{
"type": "login", "value": [ "My Username" ]
},
{
"type": "password", "value": [ await generatePassword() ]
}
],
"notes": "This record was createdvia KSM"
}
// save new record to the Keeper Vault
let newRecUid = await createSecret(options, "[FOLDER UID]", newRec)
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
# Import RecordCreate method
from keeper_secrets_manager_core.dto.dtos import RecordCreate
# create a new login record
new_login_record = RecordCreate('login', "Sample KSM Record")
# fill in login and password fields
new_login_record.fields = [
RecordField(field_type='login', value='username@email.com'),
RecordField(field_type='password', value=generate_password())
]
# fill in notes
new_login_record.notes = 'This is a Python record creation example'
# create the new record
secrets_manager.create_secret('[FOLDER UID]', new_login_record)
using System;
using System.Threading.Tasks;
using SecretsManager;
private static async Task createASecret()
{
var folderUid = "[FOLDER UID]";
var storage = new LocalConfigStorage("ksm-config.json");
var options = new SecretsManagerOptions(storage);
// Create new login record
var newRecord = new KeeperRecordData();
newRecord.type = "login";
newRecord.title = "Sample KSM Record from Docs Example (C#)";
// fill in record fields
newRecord.fields = new[]
{
new KeeperRecordField { type = "login", value = new[] { "username@email.com" } },
new KeeperRecordField { type = "password", value = new[] { CryptoUtils.GeneratePassword() } },
};
//fill in record notes
newRecord.notes = "This record was created via KSM .NET Example";
// save new record to the Keeper Vault
var recordUid = await SecretsManagerClient.CreateSecret(options, folderUid, newRecord);
Console.WriteLine("New record UID = [" + recordUid + "]");
}
package main
// Import Secrets Manager
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
folderUid := "[FOLDER UID]"
options := &ksm.ClientOptions{
// One time tokens can be used only once - afterwards use the generated config file
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
sm := ksm.NewSecretsManager(options)
// create a new login record
newLoginRecord := ksm.NewRecordCreate("login", "Sample KSM Record from Docs Example (GoLang)")
// fill in login and password fields
password, _ := ksm.GeneratePassword(32, 0, 0, 0, 0)
newLoginRecord.Fields = append(newLoginRecord.Fields,
ksm.NewLogin("username@email.com"),
ksm.NewPassword(password))
// fill in the notes
newLoginRecord.Notes = "This record was created via KSM GoLang Example"
// save new record to the Keeper Vault
recordUid, _ := sm.CreateSecretWithRecordData("", folderUid, newLoginRecord)
println("New record UID = [", recordUid, "]")
}
Additional secret creation features and Record Type and Record Fields validation coming in future releases of Keeper Secrets Manager
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"));
// setup secrets manager
const smOptions = { storage: localConfigStorage("ksm-config.json")
// delete a specific secret by record UID
await deleteSecret(smOptions, ["EG6KdJaaLG7esRZbMnfbFA"]);
from keeper_secrets_manager_core import SecretsManager
from keeper_secrets_manager_core.storage import FileKeyValueStorage
# setup secrets manger
secrets_manager = SecretsManager(
token='<One Time Access Token>',
config=FileKeyValueStorage('ksm-config.json')
)
# delete a specific secret by record UID
secret = secrets_manager.delete_secret('EG6KdJaaLG7esRZbMnfbFA')
using SecretsManager;
// setup secrets manager
var storage = new LocalConfigStorage("ksm-config.json");
//SecretsManagerClient.InitializeStorage(storage, "<One Time Access Token>");
var smOptions = new SecretsManagerOptions(storage);
// delete a specific secret by record UID
await SecretsManagerClient.DeleteSecret(smOptions, new string[] {"EG6KdJaaLG7esRZbMnfbFA"});
import ksm "github.com/keeper-security/secrets-manager-go/core"
func main() {
// setup secrets manager
options := &ksm.ClientOptions{
// Token: "<One Time Access Token>",
Config: ksm.NewFileKeyValueStorage("ksm-config.json")}
secretsManager := ksm.NewSecretsManager(options)
// delete a specific secret by record UID
secrets, err = secretsManager.DeleteSecrets([]string{"EG6KdJaaLG7esRZbMnfbFA"})
}
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
For higher level functionality at the Vault and Administrative level, please see the Vault SDKs page which contains links to various development tools.