mirror of
https://github.com/Kunzisoft/KeePassDX.git
synced 2026-11-28 04:46:51 -08:00
Better key retrieve code
This commit is contained in:
1 parent
67fecf3fef
commit
bfbd81e3ee
17 files changed
+271
-314
No files matched your search
@@ -45,7 +45,7 @@ public class AesKdf extends KdfEngine {
|
||||
public static final String ParamSeed = "S";
|
||||
|
||||
AesKdf() {
|
||||
setUUID(CIPHER_UUID);
|
||||
setUuid(CIPHER_UUID);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -57,7 +57,7 @@ public class AesKdf extends KdfEngine {
|
||||
|
||||
@Override
|
||||
public KdfParameters getDefaultParameters() {
|
||||
KdfParameters p = new KdfParameters(uuid);
|
||||
KdfParameters p = new KdfParameters(getUuid());
|
||||
|
||||
p.setParamUUID();
|
||||
p.setUInt32(ParamRounds, DEFAULT_ROUNDS);
|
||||
|
||||
@@ -65,7 +65,7 @@ public class Argon2Kdf extends KdfEngine {
|
||||
private static final String DEFAULT_NAME = "Argon2";
|
||||
|
||||
Argon2Kdf() {
|
||||
setUUID(CIPHER_UUID);
|
||||
setUuid(CIPHER_UUID);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -77,7 +77,7 @@ public class Argon2Kdf extends KdfEngine {
|
||||
|
||||
@Override
|
||||
public KdfParameters getDefaultParameters() {
|
||||
KdfParameters p = new KdfParameters(uuid);
|
||||
KdfParameters p = new KdfParameters(getUuid());
|
||||
|
||||
p.setParamUUID();
|
||||
p.setUInt32(ParamParallelism, DefaultParallelism);
|
||||
@@ -134,10 +134,12 @@ public class Argon2Kdf extends KdfEngine {
|
||||
return p.getUInt64(ParamMemory);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setMemoryUsage(KdfParameters p, long memory) {
|
||||
p.setUInt64(ParamMemory, memory);
|
||||
}
|
||||
|
||||
@Override
|
||||
public long getDefaultMemoryUsage() {
|
||||
return DefaultMemory;
|
||||
}
|
||||
@@ -147,10 +149,12 @@ public class Argon2Kdf extends KdfEngine {
|
||||
return (int) p.getUInt32(ParamParallelism); // TODO Verify
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setParallelism(KdfParameters p, int parallelism) {
|
||||
p.setUInt32(ParamParallelism, parallelism);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getDefaultParallelism() {
|
||||
return (int) DefaultParallelism; // TODO Verify
|
||||
}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
/*
|
||||
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
|
||||
*
|
||||
* This file is part of KeePass DX.
|
||||
*
|
||||
* KeePass DX is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* KeePass DX is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
package com.kunzisoft.keepass.crypto.keyDerivation;
|
||||
|
||||
import com.kunzisoft.keepass.database.ObjectNameResource;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.UUID;
|
||||
|
||||
public abstract class KdfEngine implements ObjectNameResource{
|
||||
|
||||
public static final int UNKNOW_VALUE = -1;
|
||||
public static final String UNKNOW_VALUE_STRING = String.valueOf(-1);
|
||||
|
||||
protected UUID uuid;
|
||||
|
||||
public UUID getUUID() {
|
||||
return uuid;
|
||||
}
|
||||
|
||||
public void setUUID(UUID uuid) {
|
||||
this.uuid = uuid;
|
||||
}
|
||||
|
||||
public abstract KdfParameters getDefaultParameters();
|
||||
|
||||
public abstract byte[] transform(byte[] masterKey, KdfParameters p) throws IOException;
|
||||
|
||||
public abstract void randomize(KdfParameters p);
|
||||
|
||||
public abstract long getKeyRounds(KdfParameters p);
|
||||
|
||||
public abstract void setKeyRounds(KdfParameters p, long keyRounds);
|
||||
|
||||
public abstract long getDefaultKeyRounds();
|
||||
|
||||
public long getMemoryUsage(KdfParameters p) {
|
||||
return UNKNOW_VALUE;
|
||||
}
|
||||
|
||||
public void setMemoryUsage(KdfParameters p, long memory) {
|
||||
// Do nothing by default
|
||||
}
|
||||
|
||||
public long getDefaultMemoryUsage() {
|
||||
return UNKNOW_VALUE;
|
||||
}
|
||||
|
||||
public int getParallelism(KdfParameters p) {
|
||||
return UNKNOW_VALUE;
|
||||
}
|
||||
|
||||
public void setParallelism(KdfParameters p, int parallelism) {
|
||||
// Do nothing by default
|
||||
}
|
||||
|
||||
public int getDefaultParallelism() {
|
||||
return UNKNOW_VALUE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright 2019 Jeremy Jamet / Kunzisoft.
|
||||
*
|
||||
* This file is part of KeePass DX.
|
||||
*
|
||||
* KeePass DX is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* KeePass DX is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
package com.kunzisoft.keepass.crypto.keyDerivation
|
||||
|
||||
import com.kunzisoft.keepass.database.ObjectNameResource
|
||||
|
||||
import java.io.IOException
|
||||
import java.util.UUID
|
||||
|
||||
abstract class KdfEngine : ObjectNameResource {
|
||||
|
||||
var uuid: UUID? = null
|
||||
|
||||
abstract val defaultParameters: KdfParameters
|
||||
|
||||
abstract val defaultKeyRounds: Long
|
||||
|
||||
@Throws(IOException::class)
|
||||
abstract fun transform(masterKey: ByteArray, p: KdfParameters): ByteArray
|
||||
|
||||
abstract fun randomize(p: KdfParameters)
|
||||
|
||||
abstract fun getKeyRounds(p: KdfParameters): Long
|
||||
|
||||
abstract fun setKeyRounds(p: KdfParameters, keyRounds: Long)
|
||||
|
||||
open fun getMemoryUsage(p: KdfParameters): Long {
|
||||
return UNKNOWN_VALUE.toLong()
|
||||
}
|
||||
|
||||
open fun setMemoryUsage(p: KdfParameters, memory: Long) {
|
||||
// Do nothing by default
|
||||
}
|
||||
|
||||
open fun getDefaultMemoryUsage(): Long {
|
||||
return UNKNOWN_VALUE.toLong()
|
||||
}
|
||||
|
||||
open fun getParallelism(p: KdfParameters): Int {
|
||||
return UNKNOWN_VALUE
|
||||
}
|
||||
|
||||
open fun setParallelism(p: KdfParameters, parallelism: Int) {
|
||||
// Do nothing by default
|
||||
}
|
||||
|
||||
open fun getDefaultParallelism(): Int {
|
||||
return UNKNOWN_VALUE
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
const val UNKNOWN_VALUE = -1
|
||||
const val UNKNOWN_VALUE_STRING = (-1).toString()
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
/*
|
||||
* Copyright 2017 Brian Pellin, Jeremy Jamet / Kunzisoft.
|
||||
*
|
||||
* This file is part of KeePass DX.
|
||||
*
|
||||
* KeePass DX is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* KeePass DX is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
package com.kunzisoft.keepass.crypto.keyDerivation;
|
||||
|
||||
import com.kunzisoft.keepass.database.exception.UnknownKDF;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class KdfFactory {
|
||||
|
||||
public static AesKdf aesKdf = new AesKdf();
|
||||
public static Argon2Kdf argon2Kdf = new Argon2Kdf();
|
||||
|
||||
public static List<KdfEngine> kdfListV3 = new ArrayList<>();
|
||||
public static List<KdfEngine> kdfListV4 = new ArrayList<>();
|
||||
|
||||
static {
|
||||
kdfListV3.add(aesKdf);
|
||||
|
||||
kdfListV4.add(aesKdf);
|
||||
kdfListV4.add(argon2Kdf);
|
||||
}
|
||||
|
||||
public static KdfEngine getEngineV4(KdfParameters kdfParameters) throws UnknownKDF {
|
||||
UnknownKDF unknownKDFException = new UnknownKDF();
|
||||
if (kdfParameters == null) {
|
||||
throw unknownKDFException;
|
||||
}
|
||||
for (KdfEngine engine: kdfListV4) {
|
||||
if (engine.getUUID().equals(kdfParameters.getUUID())) {
|
||||
return engine;
|
||||
}
|
||||
}
|
||||
throw unknownKDFException;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
* Copyright 2019 Jeremy Jamet / Kunzisoft.
|
||||
*
|
||||
* This file is part of KeePass DX.
|
||||
*
|
||||
* KeePass DX is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* KeePass DX is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with KeePass DX. If not, see <http://www.gnu.org/licenses/>.
|
||||
*
|
||||
*/
|
||||
package com.kunzisoft.keepass.crypto.keyDerivation
|
||||
|
||||
import com.kunzisoft.keepass.database.exception.UnknownKDF
|
||||
|
||||
import java.util.ArrayList
|
||||
|
||||
object KdfFactory {
|
||||
|
||||
var aesKdf = AesKdf()
|
||||
var argon2Kdf = Argon2Kdf()
|
||||
|
||||
var kdfListV3: MutableList<KdfEngine> = ArrayList()
|
||||
var kdfListV4: MutableList<KdfEngine> = ArrayList()
|
||||
|
||||
init {
|
||||
kdfListV3.add(aesKdf)
|
||||
|
||||
kdfListV4.add(aesKdf)
|
||||
kdfListV4.add(argon2Kdf)
|
||||
}
|
||||
|
||||
@Throws(UnknownKDF::class)
|
||||
fun getEngineV4(kdfParameters: KdfParameters?): KdfEngine {
|
||||
val unknownKDFException = UnknownKDF()
|
||||
if (kdfParameters == null) {
|
||||
throw unknownKDFException
|
||||
}
|
||||
for (engine in kdfListV4) {
|
||||
if (engine.uuid == kdfParameters.uuid) {
|
||||
return engine
|
||||
}
|
||||
}
|
||||
throw unknownKDFException
|
||||
}
|
||||
|
||||
}
|
||||
@@ -19,51 +19,48 @@
|
||||
*/
|
||||
package com.kunzisoft.keepass.database.element
|
||||
|
||||
import android.util.SparseArray
|
||||
import com.kunzisoft.keepass.database.element.security.ProtectedBinary
|
||||
import java.util.HashMap
|
||||
import kotlin.collections.Map.Entry
|
||||
|
||||
class BinaryPool {
|
||||
// TODO SparseArray
|
||||
private val pool = HashMap<Int, ProtectedBinary>()
|
||||
private val pool = SparseArray<ProtectedBinary>()
|
||||
|
||||
operator fun get(key: Int): ProtectedBinary? {
|
||||
return pool[key]
|
||||
}
|
||||
|
||||
fun put(key: Int, value: ProtectedBinary) {
|
||||
pool[key] = value
|
||||
pool.put(key, value)
|
||||
}
|
||||
|
||||
fun entrySet(): Set<Entry<Int, ProtectedBinary>> {
|
||||
return pool.entries
|
||||
fun doForEachBinary(action: (key: Int, binary: ProtectedBinary) -> Unit) {
|
||||
for (i in 0 until pool.size()) {
|
||||
action.invoke(i, pool.get(pool.keyAt(i)))
|
||||
}
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
for ((_, value) in pool)
|
||||
value.clear()
|
||||
doForEachBinary { _, binary ->
|
||||
binary.clear()
|
||||
}
|
||||
pool.clear()
|
||||
}
|
||||
|
||||
fun binaries(): Collection<ProtectedBinary> {
|
||||
return pool.values
|
||||
}
|
||||
|
||||
fun add(protectedBinary: ProtectedBinary) {
|
||||
if (findKey(protectedBinary) != -1) return
|
||||
pool[findUnusedKey()] = protectedBinary
|
||||
pool.put(findUnusedKey(), protectedBinary)
|
||||
}
|
||||
|
||||
fun findUnusedKey(): Int {
|
||||
var unusedKey = pool.size
|
||||
var unusedKey = pool.size()
|
||||
while (get(unusedKey) != null)
|
||||
unusedKey++
|
||||
return unusedKey
|
||||
}
|
||||
|
||||
fun findKey(pb: ProtectedBinary): Int {
|
||||
for ((key, value) in pool) {
|
||||
if (value == pb) return key
|
||||
for (i in 0 until pool.size()) {
|
||||
if (pool.get(pool.keyAt(i)) == pb) return i
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
@@ -128,7 +128,7 @@ class Database {
|
||||
|
||||
var memoryUsage: Long
|
||||
get() {
|
||||
return pwDatabaseV4?.memoryUsage ?: return KdfEngine.UNKNOW_VALUE.toLong()
|
||||
return pwDatabaseV4?.memoryUsage ?: return KdfEngine.UNKNOWN_VALUE.toLong()
|
||||
}
|
||||
set(memory) {
|
||||
pwDatabaseV4?.memoryUsage = memory
|
||||
@@ -138,7 +138,7 @@ class Database {
|
||||
get() = parallelism.toString()
|
||||
|
||||
var parallelism: Int
|
||||
get() = pwDatabaseV4?.parallelism ?: KdfEngine.UNKNOW_VALUE
|
||||
get() = pwDatabaseV4?.parallelism ?: KdfEngine.UNKNOWN_VALUE
|
||||
set(parallelism) {
|
||||
pwDatabaseV4?.parallelism = parallelism
|
||||
}
|
||||
@@ -464,8 +464,8 @@ class Database {
|
||||
if (pwDatabaseV4?.kdfParameters?.uuid != kdfEngine.defaultParameters.uuid)
|
||||
pwDatabaseV4?.kdfParameters = kdfEngine.defaultParameters
|
||||
numberKeyEncryptionRounds = kdfEngine.defaultKeyRounds
|
||||
memoryUsage = kdfEngine.defaultMemoryUsage
|
||||
parallelism = kdfEngine.defaultParallelism
|
||||
memoryUsage = kdfEngine.getDefaultMemoryUsage()
|
||||
parallelism = kdfEngine.getDefaultParallelism()
|
||||
}
|
||||
|
||||
fun getKeyDerivationName(resources: Resources): String {
|
||||
|
||||
@@ -77,19 +77,41 @@ abstract class PwDatabase<Group : PwGroup<*, Group, Entry>, Entry : PwEntry<Grou
|
||||
@Throws(InvalidKeyFileException::class, IOException::class)
|
||||
protected fun getCompositeKey(key: String, keyInputStream: InputStream): ByteArray {
|
||||
val fileKey = getFileKey(keyInputStream)
|
||||
|
||||
val passwordKey = getPasswordKey(key)
|
||||
|
||||
val md: MessageDigest
|
||||
val messageDigest: MessageDigest
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA-256")
|
||||
messageDigest = MessageDigest.getInstance("SHA-256")
|
||||
} catch (e: NoSuchAlgorithmException) {
|
||||
throw IOException("SHA-256 not supported")
|
||||
}
|
||||
|
||||
md.update(passwordKey)
|
||||
messageDigest.update(passwordKey)
|
||||
|
||||
return md.digest(fileKey)
|
||||
return messageDigest.digest(fileKey)
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
protected fun getPasswordKey(key: String?): ByteArray {
|
||||
if (key == null)
|
||||
throw IllegalArgumentException("Key cannot be empty.") // TODO
|
||||
|
||||
val messageDigest: MessageDigest
|
||||
try {
|
||||
messageDigest = MessageDigest.getInstance("SHA-256")
|
||||
} catch (e: NoSuchAlgorithmException) {
|
||||
throw IOException("SHA-256 not supported")
|
||||
}
|
||||
|
||||
val bKey: ByteArray = try {
|
||||
key.toByteArray(charset(passwordEncoding))
|
||||
} catch (e: UnsupportedEncodingException) {
|
||||
key.toByteArray()
|
||||
}
|
||||
|
||||
messageDigest.update(bKey, 0, bKey.size)
|
||||
|
||||
return messageDigest.digest()
|
||||
}
|
||||
|
||||
@Throws(InvalidKeyFileException::class, IOException::class)
|
||||
@@ -158,29 +180,6 @@ abstract class PwDatabase<Group : PwGroup<*, Group, Entry>, Entry : PwEntry<Grou
|
||||
return key == reEncoded
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
fun getPasswordKey(key: String?): ByteArray {
|
||||
if (key == null)
|
||||
throw IllegalArgumentException("Key cannot be empty.") // TODO
|
||||
|
||||
val md: MessageDigest
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA-256")
|
||||
} catch (e: NoSuchAlgorithmException) {
|
||||
throw IOException("SHA-256 not supported")
|
||||
}
|
||||
|
||||
val bKey: ByteArray = try {
|
||||
key.toByteArray(charset(passwordEncoding))
|
||||
} catch (e: UnsupportedEncodingException) {
|
||||
key.toByteArray()
|
||||
}
|
||||
|
||||
md.update(bKey, 0, bKey.size)
|
||||
|
||||
return md.digest()
|
||||
}
|
||||
|
||||
/*
|
||||
* -------------------------------------
|
||||
* Node Creation
|
||||
|
||||
@@ -152,15 +152,17 @@ class PwDatabaseV3 : PwDatabase<PwGroupV3, PwEntryV3>() {
|
||||
}
|
||||
|
||||
@Throws(InvalidKeyFileException::class, IOException::class)
|
||||
public override fun getMasterKey(key: String?, keyInputStream: InputStream?): ByteArray {
|
||||
override fun getMasterKey(key: String?, keyInputStream: InputStream?): ByteArray {
|
||||
|
||||
return if (key != null && keyInputStream != null) {
|
||||
getCompositeKey(key, keyInputStream)
|
||||
} else key?.let { // key.length() >= 0
|
||||
getPasswordKey(it)
|
||||
} ?: (keyInputStream?.let { // key == null
|
||||
getFileKey(it)
|
||||
} ?: throw IllegalArgumentException("Key cannot be empty."))
|
||||
} else if (key != null) { // key.length() >= 0
|
||||
getPasswordKey(key)
|
||||
} else if (keyInputStream != null) { // key == null
|
||||
getFileKey(keyInputStream)
|
||||
} else {
|
||||
throw IllegalArgumentException("Key cannot be empty.")
|
||||
}
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
|
||||
@@ -118,44 +118,43 @@ class PwDatabaseV4 : PwDatabase<PwGroupV4, PwEntryV4> {
|
||||
|
||||
val kdfEngine: KdfEngine?
|
||||
get() {
|
||||
try {
|
||||
return KdfFactory.getEngineV4(kdfParameters)
|
||||
return try {
|
||||
KdfFactory.getEngineV4(kdfParameters)
|
||||
} catch (unknownKDF: UnknownKDF) {
|
||||
Log.i(TAG, "Unable to retrieve KDF engine", unknownKDF)
|
||||
return null
|
||||
null
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
override var numberKeyEncryptionRounds: Long
|
||||
get() {
|
||||
if (kdfEngine != null && kdfParameters != null)
|
||||
numKeyEncRounds = kdfEngine!!.getKeyRounds(kdfParameters)
|
||||
numKeyEncRounds = kdfEngine!!.getKeyRounds(kdfParameters!!)
|
||||
return numKeyEncRounds
|
||||
}
|
||||
@Throws(NumberFormatException::class)
|
||||
set(rounds) {
|
||||
if (kdfEngine != null && kdfParameters != null)
|
||||
kdfEngine!!.setKeyRounds(kdfParameters, rounds)
|
||||
kdfEngine!!.setKeyRounds(kdfParameters!!, rounds)
|
||||
numKeyEncRounds = rounds
|
||||
}
|
||||
|
||||
var memoryUsage: Long
|
||||
get() = if (kdfEngine != null && kdfParameters != null) {
|
||||
kdfEngine!!.getMemoryUsage(kdfParameters)
|
||||
} else KdfEngine.UNKNOW_VALUE.toLong()
|
||||
kdfEngine!!.getMemoryUsage(kdfParameters!!)
|
||||
} else KdfEngine.UNKNOWN_VALUE.toLong()
|
||||
set(memory) {
|
||||
if (kdfEngine != null && kdfParameters != null)
|
||||
kdfEngine!!.setMemoryUsage(kdfParameters, memory)
|
||||
kdfEngine!!.setMemoryUsage(kdfParameters!!, memory)
|
||||
}
|
||||
|
||||
var parallelism: Int
|
||||
get() = if (kdfEngine != null && kdfParameters != null) {
|
||||
kdfEngine!!.getParallelism(kdfParameters)
|
||||
} else KdfEngine.UNKNOW_VALUE
|
||||
kdfEngine!!.getParallelism(kdfParameters!!)
|
||||
} else KdfEngine.UNKNOWN_VALUE
|
||||
set(parallelism) {
|
||||
if (kdfEngine != null && kdfParameters != null)
|
||||
kdfEngine!!.setParallelism(kdfParameters, parallelism)
|
||||
kdfEngine!!.setParallelism(kdfParameters!!, parallelism)
|
||||
}
|
||||
|
||||
override val passwordEncoding: String
|
||||
@@ -200,50 +199,52 @@ class PwDatabaseV4 : PwDatabase<PwGroupV4, PwEntryV4> {
|
||||
@Throws(InvalidKeyFileException::class, IOException::class)
|
||||
public override fun getMasterKey(key: String?, keyInputStream: InputStream?): ByteArray {
|
||||
|
||||
var fKey = byteArrayOf()
|
||||
var masterKey = byteArrayOf()
|
||||
|
||||
if (key != null && keyInputStream != null) {
|
||||
return getCompositeKey(key, keyInputStream)
|
||||
} else if (key != null) { // key.length() >= 0
|
||||
fKey = getPasswordKey(key)
|
||||
masterKey = getPasswordKey(key)
|
||||
} else if (keyInputStream != null) { // key == null
|
||||
fKey = getFileKey(keyInputStream)
|
||||
masterKey = getFileKey(keyInputStream)
|
||||
}
|
||||
|
||||
val md: MessageDigest
|
||||
val messageDigest: MessageDigest
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA-256")
|
||||
messageDigest = MessageDigest.getInstance("SHA-256")
|
||||
} catch (e: NoSuchAlgorithmException) {
|
||||
throw IOException("No SHA-256 implementation")
|
||||
}
|
||||
|
||||
return md.digest(fKey)
|
||||
return messageDigest.digest(masterKey)
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
fun makeFinalKey(masterSeed: ByteArray) {
|
||||
|
||||
val kdfEngine = KdfFactory.getEngineV4(kdfParameters)
|
||||
kdfParameters?.let { keyDerivationFunctionParameters ->
|
||||
val kdfEngine = KdfFactory.getEngineV4(keyDerivationFunctionParameters)
|
||||
|
||||
var transformedMasterKey = kdfEngine.transform(masterKey, kdfParameters)
|
||||
if (transformedMasterKey.size != 32) {
|
||||
transformedMasterKey = CryptoUtil.hashSha256(transformedMasterKey)
|
||||
}
|
||||
var transformedMasterKey = kdfEngine.transform(masterKey, keyDerivationFunctionParameters)
|
||||
if (transformedMasterKey.size != 32) {
|
||||
transformedMasterKey = CryptoUtil.hashSha256(transformedMasterKey)
|
||||
}
|
||||
|
||||
val cmpKey = ByteArray(65)
|
||||
System.arraycopy(masterSeed, 0, cmpKey, 0, 32)
|
||||
System.arraycopy(transformedMasterKey, 0, cmpKey, 32, 32)
|
||||
finalKey = CryptoUtil.resizeKey(cmpKey, 0, 64, dataEngine.keyLength())
|
||||
val cmpKey = ByteArray(65)
|
||||
System.arraycopy(masterSeed, 0, cmpKey, 0, 32)
|
||||
System.arraycopy(transformedMasterKey, 0, cmpKey, 32, 32)
|
||||
finalKey = CryptoUtil.resizeKey(cmpKey, 0, 64, dataEngine.keyLength())
|
||||
|
||||
val md: MessageDigest
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA-512")
|
||||
cmpKey[64] = 1
|
||||
hmacKey = md.digest(cmpKey)
|
||||
} catch (e: NoSuchAlgorithmException) {
|
||||
throw IOException("No SHA-512 implementation")
|
||||
} finally {
|
||||
Arrays.fill(cmpKey, 0.toByte())
|
||||
val md: MessageDigest
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA-512")
|
||||
cmpKey[64] = 1
|
||||
hmacKey = md.digest(cmpKey)
|
||||
} catch (e: NoSuchAlgorithmException) {
|
||||
throw IOException("No SHA-512 implementation")
|
||||
} finally {
|
||||
Arrays.fill(cmpKey, 0.toByte())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,22 +19,16 @@
|
||||
*/
|
||||
package com.kunzisoft.keepass.database.file
|
||||
|
||||
import com.kunzisoft.keepass.crypto.CrsAlgorithm
|
||||
import com.kunzisoft.keepass.crypto.keyDerivation.AesKdf
|
||||
import com.kunzisoft.keepass.crypto.keyDerivation.KdfFactory
|
||||
import com.kunzisoft.keepass.crypto.keyDerivation.KdfParameters
|
||||
import com.kunzisoft.keepass.crypto.CrsAlgorithm
|
||||
import com.kunzisoft.keepass.database.NodeHandler
|
||||
import com.kunzisoft.keepass.database.element.PwDatabaseV4
|
||||
import com.kunzisoft.keepass.database.element.PwEntryV4
|
||||
import com.kunzisoft.keepass.database.element.PwGroupV4
|
||||
import com.kunzisoft.keepass.database.exception.InvalidDBVersionException
|
||||
import com.kunzisoft.keepass.stream.CopyInputStream
|
||||
import com.kunzisoft.keepass.stream.HmacBlockStream
|
||||
import com.kunzisoft.keepass.stream.LEDataInputStream
|
||||
import com.kunzisoft.keepass.utils.Types
|
||||
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
import java.io.ByteArrayOutputStream
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
@@ -42,8 +36,10 @@ import java.security.DigestInputStream
|
||||
import java.security.InvalidKeyException
|
||||
import java.security.MessageDigest
|
||||
import java.security.NoSuchAlgorithmException
|
||||
import javax.crypto.Mac
|
||||
import javax.crypto.spec.SecretKeySpec
|
||||
|
||||
class PwDbHeaderV4(private val db: PwDatabaseV4) : PwDbHeader() {
|
||||
class PwDbHeaderV4(private val databaseV4: PwDatabaseV4) : PwDbHeader() {
|
||||
var innerRandomStreamKey: ByteArray = ByteArray(32)
|
||||
var streamStartBytes: ByteArray = ByteArray(32)
|
||||
var innerRandomStream: CrsAlgorithm? = null
|
||||
@@ -51,10 +47,10 @@ class PwDbHeaderV4(private val db: PwDatabaseV4) : PwDbHeader() {
|
||||
|
||||
// version < FILE_VERSION_32_4)
|
||||
var transformSeed: ByteArray?
|
||||
get() = db.kdfParameters?.getByteArray(AesKdf.ParamSeed)
|
||||
get() = databaseV4.kdfParameters?.getByteArray(AesKdf.ParamSeed)
|
||||
private set(seed) {
|
||||
assignAesKdfEngineIfNotExists()
|
||||
db.kdfParameters?.setByteArray(AesKdf.ParamSeed, seed)
|
||||
databaseV4.kdfParameters?.setByteArray(AesKdf.ParamSeed, seed)
|
||||
}
|
||||
|
||||
object PwDbHeaderV4Fields {
|
||||
@@ -88,97 +84,61 @@ class PwDbHeaderV4(private val db: PwDatabaseV4) : PwDbHeader() {
|
||||
inner class HeaderAndHash(var header: ByteArray, var hash: ByteArray)
|
||||
|
||||
init {
|
||||
this.version = getMinKdbxVersion(db).toLong() // Only for writing
|
||||
this.version = getMinKdbxVersion(databaseV4) // Only for writing
|
||||
this.masterSeed = ByteArray(32)
|
||||
}
|
||||
|
||||
private inner class GroupHasCustomData : NodeHandler<PwGroupV4>() {
|
||||
|
||||
internal var hasCustomData = false
|
||||
|
||||
override fun operate(node: PwGroupV4): Boolean {
|
||||
if (node.containsCustomData()) {
|
||||
hasCustomData = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private inner class EntryHasCustomData : NodeHandler<PwEntryV4>() {
|
||||
|
||||
internal var hasCustomData = false
|
||||
|
||||
override fun operate(node: PwEntryV4): Boolean {
|
||||
if (node.containsCustomData()) {
|
||||
hasCustomData = true
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
private fun getMinKdbxVersion(databaseV4: PwDatabaseV4): Long {
|
||||
if (databaseV4.rootGroup == null) {
|
||||
return FILE_VERSION_32_3
|
||||
}
|
||||
|
||||
// Return v4 if AES is not use
|
||||
if (databaseV4.kdfParameters != null && databaseV4.kdfParameters!!.uuid != AesKdf.CIPHER_UUID) {
|
||||
return FILE_VERSION_32_4
|
||||
}
|
||||
|
||||
// Return V4 if custom data are present
|
||||
if (databaseV4.containsPublicCustomData()) {
|
||||
return FILE_VERSION_32_4
|
||||
}
|
||||
|
||||
val entryHandler = EntryHasCustomData()
|
||||
val groupHandler = GroupHasCustomData()
|
||||
|
||||
if (databaseV4.rootGroup == null) {
|
||||
return FILE_VERSION_32_3
|
||||
}
|
||||
databaseV4.rootGroup?.doForEachChildAndForIt(entryHandler, groupHandler)
|
||||
return if (groupHandler.hasCustomData || entryHandler.hasCustomData) {
|
||||
FILE_VERSION_32_4
|
||||
} else FILE_VERSION_32_3
|
||||
|
||||
// Return V4 by default
|
||||
return FILE_VERSION_32_4
|
||||
}
|
||||
|
||||
/** Assumes the input stream is at the beginning of the .kdbx file
|
||||
* @param `is`
|
||||
* @param inputStream
|
||||
* @throws IOException
|
||||
* @throws InvalidDBVersionException
|
||||
*/
|
||||
@Throws(IOException::class, InvalidDBVersionException::class)
|
||||
fun loadFromFile(inputStream: InputStream): HeaderAndHash {
|
||||
val md: MessageDigest
|
||||
val messageDigest: MessageDigest
|
||||
try {
|
||||
md = MessageDigest.getInstance("SHA-256")
|
||||
messageDigest = MessageDigest.getInstance("SHA-256")
|
||||
} catch (e: NoSuchAlgorithmException) {
|
||||
throw IOException("No SHA-256 implementation")
|
||||
}
|
||||
|
||||
val headerBOS = ByteArrayOutputStream()
|
||||
val cis = CopyInputStream(inputStream, headerBOS)
|
||||
val dis = DigestInputStream(cis, md)
|
||||
val lis = LEDataInputStream(dis)
|
||||
val copyInputStream = CopyInputStream(inputStream, headerBOS)
|
||||
val digestInputStream = DigestInputStream(copyInputStream, messageDigest)
|
||||
val littleEndianDataInputStream = LEDataInputStream(digestInputStream)
|
||||
|
||||
val sig1 = lis.readInt()
|
||||
val sig2 = lis.readInt()
|
||||
val sig1 = littleEndianDataInputStream.readInt()
|
||||
val sig2 = littleEndianDataInputStream.readInt()
|
||||
|
||||
if (!matchesHeader(sig1, sig2)) {
|
||||
throw InvalidDBVersionException()
|
||||
}
|
||||
|
||||
version = lis.readUInt() // Erase previous value
|
||||
version = littleEndianDataInputStream.readUInt() // Erase previous value
|
||||
if (!validVersion(version)) {
|
||||
throw InvalidDBVersionException()
|
||||
}
|
||||
|
||||
var done = false
|
||||
while (!done) {
|
||||
done = readHeaderField(lis)
|
||||
done = readHeaderField(littleEndianDataInputStream)
|
||||
}
|
||||
|
||||
val hash = md.digest()
|
||||
val hash = messageDigest.digest()
|
||||
return HeaderAndHash(headerBOS.toByteArray(), hash)
|
||||
}
|
||||
|
||||
@@ -228,10 +188,10 @@ class PwDbHeaderV4(private val db: PwDatabaseV4) : PwDbHeader() {
|
||||
PwDbHeaderV4Fields.InnerRandomStreamID -> if (version < FILE_VERSION_32_4)
|
||||
setRandomStreamID(fieldData)
|
||||
|
||||
PwDbHeaderV4Fields.KdfParameters -> db.kdfParameters = KdfParameters.deserialize(fieldData)
|
||||
PwDbHeaderV4Fields.KdfParameters -> databaseV4.kdfParameters = KdfParameters.deserialize(fieldData)
|
||||
|
||||
PwDbHeaderV4Fields.PublicCustomData -> {
|
||||
db.publicCustomData = KdfParameters.deserialize(fieldData) // TODO verify
|
||||
databaseV4.publicCustomData = KdfParameters.deserialize(fieldData) // TODO verify
|
||||
throw IOException("Invalid header type: $fieldID")
|
||||
}
|
||||
else -> throw IOException("Invalid header type: $fieldID")
|
||||
@@ -241,8 +201,8 @@ class PwDbHeaderV4(private val db: PwDatabaseV4) : PwDbHeader() {
|
||||
}
|
||||
|
||||
private fun assignAesKdfEngineIfNotExists() {
|
||||
if (db.kdfParameters == null || db.kdfParameters!!.uuid != KdfFactory.aesKdf.uuid) {
|
||||
db.kdfParameters = KdfFactory.aesKdf.defaultParameters
|
||||
if (databaseV4.kdfParameters == null || databaseV4.kdfParameters!!.uuid != KdfFactory.aesKdf.uuid) {
|
||||
databaseV4.kdfParameters = KdfFactory.aesKdf.defaultParameters
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,14 +212,14 @@ class PwDbHeaderV4(private val db: PwDatabaseV4) : PwDbHeader() {
|
||||
throw IOException("Invalid cipher ID.")
|
||||
}
|
||||
|
||||
db.dataCipher = Types.bytestoUUID(pbId)
|
||||
databaseV4.dataCipher = Types.bytestoUUID(pbId)
|
||||
}
|
||||
|
||||
private fun setTransformRound(roundsByte: ByteArray?) {
|
||||
assignAesKdfEngineIfNotExists()
|
||||
val rounds = LEDataInputStream.readLong(roundsByte!!, 0)
|
||||
db.kdfParameters?.setUInt64(AesKdf.ParamRounds, rounds)
|
||||
db.numberKeyEncryptionRounds = rounds
|
||||
databaseV4.kdfParameters?.setUInt64(AesKdf.ParamRounds, rounds)
|
||||
databaseV4.numberKeyEncryptionRounds = rounds
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
@@ -274,7 +234,7 @@ class PwDbHeaderV4(private val db: PwDatabaseV4) : PwDbHeader() {
|
||||
}
|
||||
|
||||
PwCompressionAlgorithm.fromId(flag)?.let { compression ->
|
||||
db.compressionAlgorithm = compression
|
||||
databaseV4.compressionAlgorithm = compression
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -95,20 +95,21 @@ class ImporterV4(private val streamDir: File) : Importer<PwDatabaseV4>() {
|
||||
keyInputStream: InputStream?,
|
||||
progressTaskUpdater: ProgressTaskUpdater?): PwDatabaseV4 {
|
||||
|
||||
// TODO performance
|
||||
progressTaskUpdater?.updateMessage(R.string.retrieving_db_key)
|
||||
|
||||
mDatabase = PwDatabaseV4()
|
||||
|
||||
val header = PwDbHeaderV4(mDatabase)
|
||||
mDatabase.binPool.clear()
|
||||
|
||||
val hh = header.loadFromFile(databaseInputStream)
|
||||
val headerAndHash = header.loadFromFile(databaseInputStream)
|
||||
version = header.version
|
||||
|
||||
hashOfHeader = hh.hash
|
||||
val pbHeader = hh.header
|
||||
hashOfHeader = headerAndHash.hash
|
||||
val pbHeader = headerAndHash.header
|
||||
|
||||
mDatabase.retrieveMasterKey(password, keyInputStream)
|
||||
mDatabase.makeFinalKey(header.masterSeed)
|
||||
// TODO performance
|
||||
|
||||
progressTaskUpdater?.updateMessage(R.string.decrypting_db)
|
||||
val engine: CipherEngine
|
||||
|
||||
+1
-3
@@ -21,10 +21,8 @@ package com.kunzisoft.keepass.database.file.save
|
||||
|
||||
import com.kunzisoft.keepass.database.element.PwDatabaseV4
|
||||
import com.kunzisoft.keepass.database.file.PwDbHeaderV4
|
||||
import com.kunzisoft.keepass.database.element.security.ProtectedBinary
|
||||
import com.kunzisoft.keepass.stream.LEDataOutputStream
|
||||
import com.kunzisoft.keepass.utils.MemUtil
|
||||
|
||||
import java.io.IOException
|
||||
import java.io.OutputStream
|
||||
import kotlin.experimental.or
|
||||
@@ -46,7 +44,7 @@ class PwDbInnerHeaderOutputV4(private val db: PwDatabaseV4, private val header:
|
||||
los.writeInt(streamKeySize)
|
||||
los.write(header.innerRandomStreamKey)
|
||||
|
||||
for (protectedBinary in db.binPool.binaries()) {
|
||||
db.binPool.doForEachBinary { _, protectedBinary ->
|
||||
var flag = PwDbHeaderV4.KdbxBinaryFlags.None
|
||||
if (protectedBinary.isProtected) {
|
||||
flag = flag or PwDbHeaderV4.KdbxBinaryFlags.Protected
|
||||
|
||||
@@ -260,7 +260,7 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, outputStream: OutputSt
|
||||
|
||||
try {
|
||||
val kdf = KdfFactory.getEngineV4(mDatabaseV4.kdfParameters)
|
||||
kdf.randomize(mDatabaseV4.kdfParameters)
|
||||
kdf.randomize(mDatabaseV4.kdfParameters!!)
|
||||
} catch (unknownKDF: UnknownKDF) {
|
||||
Log.e(TAG, "Unable to retrieve header", unknownKDF)
|
||||
}
|
||||
@@ -705,14 +705,13 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, outputStream: OutputSt
|
||||
private fun writeBinPool() {
|
||||
xml.startTag(null, PwDatabaseV4XML.ElemBinaries)
|
||||
|
||||
for ((key, value) in mDatabaseV4.binPool.entrySet()) {
|
||||
mDatabaseV4.binPool.doForEachBinary { key, binary ->
|
||||
xml.startTag(null, PwDatabaseV4XML.ElemBinary)
|
||||
xml.attribute(null, PwDatabaseV4XML.AttrId, Integer.toString(key))
|
||||
|
||||
subWriteValue(value)
|
||||
subWriteValue(binary)
|
||||
|
||||
xml.endTag(null, PwDatabaseV4XML.ElemBinary)
|
||||
|
||||
}
|
||||
|
||||
xml.endTag(null, PwDatabaseV4XML.ElemBinaries)
|
||||
|
||||
+1
-1
@@ -44,7 +44,7 @@ class InputNumberPreference @JvmOverloads constructor(context: Context,
|
||||
}
|
||||
|
||||
override fun setSummary(summary: CharSequence) {
|
||||
if (summary == KdfEngine.UNKNOW_VALUE_STRING) {
|
||||
if (summary == KdfEngine.UNKNOWN_VALUE_STRING) {
|
||||
isEnabled = false
|
||||
super.setSummary("")
|
||||
} else {
|
||||
|
||||
+2
-2
@@ -101,8 +101,8 @@ class DatabaseKeyDerivationPreferenceDialogFragmentCompat : DatabaseSavePreferen
|
||||
|
||||
roundPreference?.summary = kdfEngineToShow.defaultKeyRounds.toString()
|
||||
// Disable memory and parallelism if not available
|
||||
memoryPreference?.summary = kdfEngineToShow.defaultMemoryUsage.toString()
|
||||
parallelismPreference?.summary = kdfEngineToShow.defaultParallelism.toString()
|
||||
memoryPreference?.summary = kdfEngineToShow.getDefaultMemoryUsage().toString()
|
||||
parallelismPreference?.summary = kdfEngineToShow.getDefaultParallelism().toString()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user