Skip to content

Instantly share code, notes, and snippets.

@shafty023
shafty023 / save_to_prefs.kt
Created June 9, 2020 22:52
Persist the db key to storage
/**
* Save the storable instance to preferences.
*
* @param storable a storable instance
*/
fun saveToPrefs(context: Context, storable: Storable) {
val serialized = Gson().toJson(storable)
val prefs = context.getSharedPreferences("database",
Context.MODE_PRIVATE)
prefs.edit().putString("key", serialized).apply()
@shafty023
shafty023 / Storable.kt
Created June 9, 2020 22:41
Container for everything needed to decrypt db
/**
* Container for everything needed for decrypting the database.
*
* @param iv initialization vector
* @param key encrypted database key
* @param salt cryptographic salt
*/
data class Storable(val iv: String, val key: String, val salt: String)
@shafty023
shafty023 / CreateNewKey.kt
Created June 9, 2020 22:40
Wrapper function to create a new key
private lateinit var rawByteKey: ByteArray
private lateinit var dbCharKey: CharArray
/**
* Generates a new database key.
*/
fun createNewKey() {
// This is the raw key that we'll be encrypting + storing
rawByteKey = generateRandomKey()
// This is the key that will be used by Room
@shafty023
shafty023 / RawKeyGenerator.kt
Created June 9, 2020 22:31
Generates a random 32 byte key
/**
* Generates a random 32 byte key.
*
* @return a byte array containing random values
*/
fun generateRandomKey(): ByteArray =
ByteArray(32).apply {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
SecureRandom.getInstanceStrong().nextBytes(this)
} else {
/*
* Copyright (c) 2016 AirWatch, LLC. All rights reserved.
* This product is protected by copyright and intellectual property laws in
* the United States and other countries as well as by international treaties.
* AirWatch products may be covered by one or more patents listed at
* http://www.vmware.com/go/patents.
*/
package com.boxer.sdk;
import android.content.Context;