Skip to content

Instantly share code, notes, and snippets.

@Hayk985
Last active February 28, 2024 15:42
Show Gist options
  • Save Hayk985/f05eb98dbb676fc45d0fe22ce1e109b6 to your computer and use it in GitHub Desktop.
Save Hayk985/f05eb98dbb676fc45d0fe22ce1e109b6 to your computer and use it in GitHub Desktop.
Password based encryption
import android.security.keystore.KeyProperties
import java.security.SecureRandom
import java.security.spec.KeySpec
import javax.crypto.SecretKey
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
// Source - https://medium.com/@hayk.mkrtchyan8998/shedding-light-on-android-encryption-android-crypto-api-part-2-cipher-147ff4411e1d
/**
* A symmetric encryption key can be generated from the passphrase by
* using the Password Based Key Derivation Function version 2 (PBKDF2).
* @param password - The passphrase to generate the key from
* @param keyLength - The length of the key to generate (i.e. 128, 192 or 256-bit AES key)
*/
fun generateStrongAESKey(password: CharArray, keyLength: Int): SecretKey {
//Initialize objects and variables for later use
val iterationCount = 10000
val saltLength = keyLength / 8
//Generate the salt
val salt = generateRandomSalt(saltLength)
val keySpec: KeySpec = PBEKeySpec(password, salt, iterationCount, keyLength)
val keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1")
val keyBytes = keyFactory.generateSecret(keySpec).encoded
return SecretKeySpec(keyBytes, KeyProperties.KEY_ALGORITHM_AES)
}
fun generateRandomSalt(saltLength: Int): ByteArray {
val random = SecureRandom()
val salt = ByteArray(saltLength)
random.nextBytes(salt)
return salt
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment