NATIVE_STORE.deleteOnExit();
SQLITE_DATABASE.deleteOnExit();
// Initialize context and storage system
K2Context context = new K2Context();
K2Storage storage = new K2Storage(context);
// Register available key versions
KeyVersionRegistry registry = context.getKeyVersionRegistry();
try {
registry.register(AESKeyVersion.class);
registry.register(HMACKeyVersion.class);
} catch (KeyVersionException ex) {
// Something wrong with a key version
throw ex;
}
// Install desired storage drivers in order of preference
try {
storage.installDriver(K2FileSystemDriver.class);
storage.installDriver(SqliteDriver.class);
storage.installDriver(K2MemoryDriver.class);
} catch (StorageDriverException ex) {
// Something wrong with a storage driver
throw ex;
}
// Create a key
Key original;
try {
original = new Key(new AESKeyVersion.Builder().build());
} catch (BuilderException ex) {
// Problem building key
throw ex;
}
// Quickly save it (the native driver recognizes file:// addresses)
storage.save(NATIVE_STORE.toURI(), original);
// Quickly load it back
Key loaded = storage.load(NATIVE_STORE.toURI());
assert(original.buildData().build().equals(loaded.buildData().build()));
// Use Store API for more elaborate operations
Store store = null;
try {
// Open a SQLite database store
store = storage.open(
"sqlite:" + SQLITE_DATABASE.toURI().getRawPath() + "#samekey");
// Save previously loaded key
store.save(loaded);