Skip to content

Instantly share code, notes, and snippets.

const geoSchema = new Schema({
type: {
type: String,
default: 'Point'
},
coordinates: {
type: [Number]
}
});
private fun decryptEncryptedFile(): ByteArray {
val filePath = filesDir.absolutePath + "/filename"
val fileData = readFile(filePath)
val secretKey = getSecretKey(sharedPref)
return decode(secretKey, fileData)
}
@BDOMDev
BDOMDev / Utils.kt
Created June 26, 2019 08:58
Decrypt a file
@Throws(Exception::class)
fun decrypt(yourKey: SecretKey, fileData: ByteArray): ByteArray {
val decrypted: ByteArray
val cipher = Cipher.getInstance("AES", "BC")
cipher.init(Cipher.DECRYPT_MODE, yourKey, IvParameterSpec(ByteArray(cipher.blockSize)))
decrypted = cipher.doFinal(fileData)
return decrypted
}
fun getSecretKey(sharedPref: SharedPreferences): SecretKey {
val key = sharedPref.getString(AppConstants.secretKeyPref, null)
if (key == null) {
//generate secure random
val secretKey = generateSecreKey()
saveSecretKey(sharedPref, secretKey!!)
return secretKey
}
fun encryptDownloadedFile() {
try {
val filePath = filesDir.absolutePath + "/filename"
val fileData = readFile(filePath)
//get secret key
val secretKey = getSecretKey(sharedPref)
//encrypt file
val encodedData = encrypt(secretKey, fileData)
@BDOMDev
BDOMDev / Utils.kt
Created June 26, 2019 08:27
Encrypt a file
fun encryptDownloadedFile(filePath: String) {
val fileData = readFile(filePath)
val secretKey = getSecretKey(sharedPref)
val encodedData = encode(secretKey, fileData)
saveFile(encodedData, filePath)
}
@BDOMDev
BDOMDev / Utils.kt
Created June 26, 2019 08:25
Save a ByteArray to a file
@Throws(Exception::class)
fun saveFile(fileData: ByteArray, path: String) {
val file = File(path)
val bos = BufferedOutputStream(FileOutputStream(file, false))
bos.write(fileData)
bos.flush()
bos.close()
}
@BDOMDev
BDOMDev / Utils.kt
Created June 26, 2019 08:20
Read a file as ByteArray
@Throws(Exception::class)
fun readFile(filePath: String): ByteArray {
val file = File(filePath)
val fileContents = file.readBytes()
val inputBuffer = BufferedInputStream(
FileInputStream(file)
)
inputBuffer.read(fileContents)
inputBuffer.close()
@BDOMDev
BDOMDev / PrefUrls.kt
Created June 26, 2019 08:14
Save a Secret key to sharedPreference
fun saveSecretKey(sharedPref: SharedPreferences, secretKey: SecretKey): String {
val encodedKey = Base64.encodeToString(secretKey.encoded, Base64.NO_WRAP)
sharedPref.edit().putString(AppConstants.secretKeyPref, encodedKey).apply()
return encodedKey
}
@Throws(Exception::class)
fun generateSecretKey(): SecretKey? {
val secureRandom = SecureRandom()
val keyGenerator = KeyGenerator.getInstance("AES")
//generate a key with secure random
keyGenerator?.init(128, secureRandom)
return keyGenerator?.generateKey()
}