From be6f01dc999951e22a8dae920f292b3d8d38b217 Mon Sep 17 00:00:00 2001 From: J-Jamet Date: Wed, 20 Nov 2019 12:40:56 +0100 Subject: [PATCH] Fix PWDate and blocks --- .../tests/DatabaseInputOutputUtilsTest.kt | 19 +- .../com/kunzisoft/keepass/tests/PwDateTest.kt | 5 +- .../keepass/crypto/engine/AesEngine.kt | 2 +- .../keepass/crypto/engine/ChaCha20Engine.kt | 2 +- .../keepass/crypto/engine/TwofishEngine.kt | 2 +- .../keepass/crypto/keyDerivation/AesKdf.kt | 4 +- .../keepass/crypto/keyDerivation/Argon2Kdf.kt | 4 +- .../crypto/keyDerivation/KdfParameters.java | 75 ------ .../crypto/keyDerivation/KdfParameters.kt | 67 +++++ .../keepass/database/element/PwDate.kt | 142 +---------- .../keepass/database/file/PwDbHeaderV4.kt | 4 +- .../keepass/database/file/load/ImporterV3.kt | 18 +- .../keepass/database/file/load/ImporterV4.kt | 2 +- .../database/file/save/PwDbHeaderOutputV4.kt | 4 +- .../database/file/save/PwDbV4Output.kt | 2 +- .../database/file/save/PwEntryOutputV3.kt | 10 +- .../database/file/save/PwGroupOutputV3.kt | 8 +- .../keepass/database/search/UuidUtil.java | 19 +- .../stream/HashedBlockInputStream.java | 165 ------------- .../keepass/stream/HashedBlockInputStream.kt | 164 ++++++++++++ .../keepass/stream/HmacBlockInputStream.java | 175 ------------- .../keepass/stream/HmacBlockInputStream.kt | 166 +++++++++++++ .../keepass/stream/LEDataInputStream.java | 14 ++ .../utils/DatabaseInputOutputUtils.java | 184 -------------- .../keepass/utils/DatabaseInputOutputUtils.kt | 233 ++++++++++++++++++ 25 files changed, 703 insertions(+), 787 deletions(-) delete mode 100644 app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/KdfParameters.java create mode 100644 app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/KdfParameters.kt delete mode 100644 app/src/main/java/com/kunzisoft/keepass/stream/HashedBlockInputStream.java create mode 100644 app/src/main/java/com/kunzisoft/keepass/stream/HashedBlockInputStream.kt delete mode 100644 app/src/main/java/com/kunzisoft/keepass/stream/HmacBlockInputStream.java create mode 100644 app/src/main/java/com/kunzisoft/keepass/stream/HmacBlockInputStream.kt delete mode 100644 app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.java create mode 100644 app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.kt diff --git a/app/src/androidTest/java/com/kunzisoft/keepass/tests/DatabaseInputOutputUtilsTest.kt b/app/src/androidTest/java/com/kunzisoft/keepass/tests/DatabaseInputOutputUtilsTest.kt index 1d8ee444a..61dcd2a5d 100644 --- a/app/src/androidTest/java/com/kunzisoft/keepass/tests/DatabaseInputOutputUtilsTest.kt +++ b/app/src/androidTest/java/com/kunzisoft/keepass/tests/DatabaseInputOutputUtilsTest.kt @@ -27,7 +27,6 @@ import java.util.Random import junit.framework.TestCase -import com.kunzisoft.keepass.database.element.PwDate import com.kunzisoft.keepass.stream.LEDataInputStream import com.kunzisoft.keepass.stream.LEDataOutputStream import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils @@ -168,27 +167,31 @@ class DatabaseInputOutputUtilsTest : TestCase() { val expected = Calendar.getInstance() expected.set(2008, 1, 2, 3, 4, 5) - val buf = PwDate.writeTime(expected.time, cal) val actual = Calendar.getInstance() - actual.time = PwDate.readTime(buf, 0, cal) + DatabaseInputOutputUtils.writeCDate(expected.time, cal)?.let { buf -> + actual.time = DatabaseInputOutputUtils.readCDate(buf, 0, cal).date + } assertEquals("Year mismatch: ", 2008, actual.get(Calendar.YEAR)) assertEquals("Month mismatch: ", 1, actual.get(Calendar.MONTH)) - assertEquals("Day mismatch: ", 1, actual.get(Calendar.DAY_OF_MONTH)) + assertEquals("Day mismatch: ", 2, actual.get(Calendar.DAY_OF_MONTH)) assertEquals("Hour mismatch: ", 3, actual.get(Calendar.HOUR_OF_DAY)) assertEquals("Minute mismatch: ", 4, actual.get(Calendar.MINUTE)) assertEquals("Second mismatch: ", 5, actual.get(Calendar.SECOND)) } fun testUUID() { - val rnd = Random() val bUUID = ByteArray(16) - rnd.nextBytes(bUUID) + Random().nextBytes(bUUID) - val uuid = DatabaseInputOutputUtils.bytestoUUID(bUUID) - val eUUID = DatabaseInputOutputUtils.UUIDtoBytes(uuid) + val uuid = DatabaseInputOutputUtils.bytesToUuid(bUUID) + val eUUID = DatabaseInputOutputUtils.uuidToBytes(uuid) + + val lUUID = LEDataInputStream.readUuid(bUUID, 0) + val leUUID = DatabaseInputOutputUtils.uuidToBytes(lUUID) assertArrayEquals("UUID match failed", bUUID, eUUID) + assertArrayEquals("UUID match failed", bUUID, leUUID) } @Throws(Exception::class) diff --git a/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwDateTest.kt b/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwDateTest.kt index 7cb932d86..a7269ad1f 100644 --- a/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwDateTest.kt +++ b/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwDateTest.kt @@ -22,6 +22,7 @@ package com.kunzisoft.keepass.tests import junit.framework.TestCase import com.kunzisoft.keepass.database.element.PwDate +import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils import org.junit.Assert class PwDateTest : TestCase() { @@ -29,9 +30,9 @@ class PwDateTest : TestCase() { fun testDate() { val jDate = PwDate(System.currentTimeMillis()) val intermediate = PwDate(jDate) - val cDate = PwDate(intermediate.byteArrayDate!!, 0) + val cDate = DatabaseInputOutputUtils.readCDate(DatabaseInputOutputUtils.writeCDate(intermediate.date)!!, 0) Assert.assertTrue("jDate and intermediate not equal", jDate == intermediate) - Assert.assertTrue("jDate and cDate not equal", cDate == jDate) + Assert.assertTrue("jDate $jDate and cDate $cDate not equal", cDate == jDate) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/AesEngine.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/AesEngine.kt index 123c503fd..ac59b4ea4 100644 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/AesEngine.kt +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/AesEngine.kt @@ -47,7 +47,7 @@ class AesEngine : CipherEngine() { companion object { - val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytestoUUID( + val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytesToUuid( byteArrayOf(0x31.toByte(), 0xC1.toByte(), 0xF2.toByte(), 0xE6.toByte(), 0xBF.toByte(), 0x71.toByte(), 0x43.toByte(), 0x50.toByte(), 0xBE.toByte(), 0x58.toByte(), 0x05.toByte(), 0x21.toByte(), 0x6A.toByte(), 0xFC.toByte(), 0x5A.toByte(), 0xFF.toByte())) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/ChaCha20Engine.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/ChaCha20Engine.kt index 68cd847c4..34010d18d 100644 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/ChaCha20Engine.kt +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/ChaCha20Engine.kt @@ -50,7 +50,7 @@ class ChaCha20Engine : CipherEngine() { companion object { - val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytestoUUID( + val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytesToUuid( byteArrayOf(0xD6.toByte(), 0x03.toByte(), 0x8A.toByte(), 0x2B.toByte(), 0x8B.toByte(), 0x6F.toByte(), 0x4C.toByte(), 0xB5.toByte(), 0xA5.toByte(), 0x24.toByte(), 0x33.toByte(), 0x9A.toByte(), 0x31.toByte(), 0xDB.toByte(), 0xB5.toByte(), 0x9A.toByte())) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/TwofishEngine.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/TwofishEngine.kt index 32eaef59d..0e323b24b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/engine/TwofishEngine.kt +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/engine/TwofishEngine.kt @@ -53,7 +53,7 @@ class TwofishEngine : CipherEngine() { companion object { - val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytestoUUID( + val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytesToUuid( byteArrayOf(0xAD.toByte(), 0x68.toByte(), 0xF2.toByte(), 0x9F.toByte(), 0x57.toByte(), 0x6F.toByte(), 0x4B.toByte(), 0xB9.toByte(), 0xA3.toByte(), 0x6A.toByte(), 0xD4.toByte(), 0x7A.toByte(), 0xF9.toByte(), 0x65.toByte(), 0x34.toByte(), 0x6C.toByte())) } } diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/AesKdf.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/AesKdf.kt index a8e456c99..4612ee9dd 100644 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/AesKdf.kt +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/AesKdf.kt @@ -32,7 +32,7 @@ class AesKdf internal constructor() : KdfEngine() { override val defaultParameters: KdfParameters get() { - return KdfParameters(uuid).apply { + return KdfParameters(uuid!!).apply { setParamUUID() setUInt32(PARAM_ROUNDS, DEFAULT_ROUNDS.toLong()) } @@ -88,7 +88,7 @@ class AesKdf internal constructor() : KdfEngine() { private const val DEFAULT_ROUNDS = 6000 - val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytestoUUID( + val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytesToUuid( byteArrayOf(0xC9.toByte(), 0xD9.toByte(), 0xF3.toByte(), diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/Argon2Kdf.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/Argon2Kdf.kt index e22934448..8e60b330d 100644 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/Argon2Kdf.kt +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/Argon2Kdf.kt @@ -30,7 +30,7 @@ class Argon2Kdf internal constructor() : KdfEngine() { override val defaultParameters: KdfParameters get() { - val p = KdfParameters(uuid) + val p = KdfParameters(uuid!!) p.setParamUUID() p.setUInt32(PARAM_PARALLELISM, DEFAULT_PARALLELISM) @@ -126,7 +126,7 @@ class Argon2Kdf internal constructor() : KdfEngine() { companion object { - val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytestoUUID( + val CIPHER_UUID: UUID = DatabaseInputOutputUtils.bytesToUuid( byteArrayOf(0xEF.toByte(), 0x63.toByte(), 0x6D.toByte(), diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/KdfParameters.java b/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/KdfParameters.java deleted file mode 100644 index 31e9289a4..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/KdfParameters.java +++ /dev/null @@ -1,75 +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 . - * - */ -package com.kunzisoft.keepass.crypto.keyDerivation; - -import com.kunzisoft.keepass.utils.VariantDictionary; -import com.kunzisoft.keepass.stream.LEDataInputStream; -import com.kunzisoft.keepass.stream.LEDataOutputStream; -import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.UUID; - -public class KdfParameters extends VariantDictionary { - - private UUID kdfUUID; - - private static final String ParamUUID = "$UUID"; - - KdfParameters(UUID uuid) { - kdfUUID = uuid; - } - - public UUID getUUID() { - return kdfUUID; - } - - protected void setParamUUID() { - setByteArray(ParamUUID, DatabaseInputOutputUtils.UUIDtoBytes(kdfUUID)); - } - - public static KdfParameters deserialize(byte[] data) throws IOException { - ByteArrayInputStream bis = new ByteArrayInputStream(data); - LEDataInputStream lis = new LEDataInputStream(bis); - - VariantDictionary d = VariantDictionary.deserialize(lis); - if (d == null) { - return null; - } - - UUID uuid = DatabaseInputOutputUtils.bytestoUUID(d.getByteArray(ParamUUID)); - - KdfParameters kdfP = new KdfParameters(uuid); - kdfP.copyTo(d); - return kdfP; - } - - public static byte[] serialize(KdfParameters kdf) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - LEDataOutputStream los = new LEDataOutputStream(bos); - - KdfParameters.serialize(kdf, los); - - return bos.toByteArray(); - } - -} diff --git a/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/KdfParameters.kt b/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/KdfParameters.kt new file mode 100644 index 000000000..d8526545f --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/crypto/keyDerivation/KdfParameters.kt @@ -0,0 +1,67 @@ +/* + * 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 . + * + */ +package com.kunzisoft.keepass.crypto.keyDerivation + +import com.kunzisoft.keepass.utils.VariantDictionary +import com.kunzisoft.keepass.stream.LEDataInputStream +import com.kunzisoft.keepass.stream.LEDataOutputStream +import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils + +import java.io.ByteArrayInputStream +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.util.UUID + +class KdfParameters internal constructor(val uuid: UUID) : VariantDictionary() { + + fun setParamUUID() { + setByteArray(PARAM_UUID, DatabaseInputOutputUtils.uuidToBytes(uuid)) + } + + companion object { + + private const val PARAM_UUID = "\$UUID" + + @Throws(IOException::class) + fun deserialize(data: ByteArray): KdfParameters? { + val bis = ByteArrayInputStream(data) + val lis = LEDataInputStream(bis) + + val d = deserialize(lis) ?: return null + + val uuid = DatabaseInputOutputUtils.bytesToUuid(d.getByteArray(PARAM_UUID)) + + val kdfP = KdfParameters(uuid) + kdfP.copyTo(d) + return kdfP + } + + @Throws(IOException::class) + fun serialize(kdf: KdfParameters): ByteArray { + val bos = ByteArrayOutputStream() + val los = LEDataOutputStream(bos) + + serialize(kdf, los) + + return bos.toByteArray() + } + } + +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDate.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDate.kt index 439dc562e..5d8cd906a 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDate.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDate.kt @@ -33,69 +33,28 @@ import java.util.* class PwDate : Parcelable { private var jDate: Date = Date() - private var jDateBuilt = false - @Transient - private var cDate: ByteArray? = null - @Transient - private var cDateBuilt = false val date: Date - get() { - if (!jDateBuilt) { - jDate = readTime(cDate, 0, calendar) - jDateBuilt = true - } - - return jDate - } - - val byteArrayDate: ByteArray? - get() { - if (!cDateBuilt) { - cDate = writeTime(jDate, calendar) - cDateBuilt = true - } - - return cDate - } - - constructor(buf: ByteArray, offset: Int) { - cDate = ByteArray(DATE_SIZE) - System.arraycopy(buf, offset, cDate!!, 0, DATE_SIZE) - cDateBuilt = true - } + get() = jDate constructor(source: PwDate) { this.jDate = Date(source.jDate.time) - this.jDateBuilt = source.jDateBuilt - - if (source.cDate != null) { - val dateLength = source.cDate!!.size - this.cDate = ByteArray(dateLength) - System.arraycopy(source.cDate!!, 0, this.cDate!!, 0, dateLength) - } - this.cDateBuilt = source.cDateBuilt } constructor(date: Date) { jDate = Date(date.time) - jDateBuilt = true } constructor(millis: Long) { jDate = Date(millis) - jDateBuilt = true } constructor() { jDate = Date() - jDateBuilt = true } protected constructor(parcel: Parcel) { jDate = parcel.readSerializable() as Date - jDateBuilt = parcel.readByte().toInt() != 0 - cDateBuilt = false } override fun describeContents(): Int { @@ -108,7 +67,6 @@ class PwDate : Parcelable { override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeSerializable(date) - dest.writeByte((if (jDateBuilt) 1 else 0).toByte()) } override fun equals(other: Any?): Boolean { @@ -122,42 +80,22 @@ class PwDate : Parcelable { return false } - val date = other as PwDate? - return if (cDateBuilt && date!!.cDateBuilt) { - Arrays.equals(cDate, date.cDate) - } else if (jDateBuilt && date!!.jDateBuilt) { - isSameDate(jDate, date.jDate) - } else if (cDateBuilt && date!!.jDateBuilt) { - Arrays.equals(date.byteArrayDate, cDate) - } else { - isSameDate(date!!.date, jDate) - } + val date = other as PwDate + return isSameDate(jDate, date.jDate) } override fun hashCode(): Int { - var result = jDate.hashCode() - result = 31 * result + jDateBuilt.hashCode() - result = 31 * result + (cDate?.contentHashCode() ?: 0) - result = 31 * result + cDateBuilt.hashCode() - return result + return jDate.hashCode() + } + + override fun toString(): String { + return jDate.toString() } companion object { - private const val DATE_SIZE = 5 - - private var mCalendar: Calendar? = null - val NEVER_EXPIRE = neverExpire - private val calendar: Calendar? - get() { - if (mCalendar == null) { - mCalendar = Calendar.getInstance() - } - return mCalendar - } - private val neverExpire: PwDate get() { val cal = Calendar.getInstance() @@ -182,70 +120,6 @@ class PwDate : Parcelable { } } - /** - * Unpack date from 5 byte format. The five bytes at 'offset' are unpacked - * to a java.util.Date instance. - */ - fun readTime(buf: ByteArray?, offset: Int, calendar: Calendar?): Date { - var time = calendar - val dw1 = DatabaseInputOutputUtils.readUByte(buf!!, offset) - val dw2 = DatabaseInputOutputUtils.readUByte(buf, offset + 1) - val dw3 = DatabaseInputOutputUtils.readUByte(buf, offset + 2) - val dw4 = DatabaseInputOutputUtils.readUByte(buf, offset + 3) - val dw5 = DatabaseInputOutputUtils.readUByte(buf, offset + 4) - - // Unpack 5 byte structure to date and time - val year = dw1 shl 6 or (dw2 shr 2) - val month = dw2 and 0x00000003 shl 2 or (dw3 shr 6) - - val day = dw3 shr 1 and 0x0000001F - val hour = dw3 and 0x00000001 shl 4 or (dw4 shr 4) - val minute = dw4 and 0x0000000F shl 2 or (dw5 shr 6) - val second = dw5 and 0x0000003F - - if (time == null) { - time = Calendar.getInstance() - } - // File format is a 1 based month, java Calendar uses a zero based month - // File format is a 1 based day, java Calendar uses a 1 based day - time!!.set(year, month - 1, day, hour, minute, second) - - return time.time - - } - - @JvmOverloads - fun writeTime(date: Date?, calendar: Calendar? = null): ByteArray? { - var cal = calendar - if (date == null) { - return null - } - - val buf = ByteArray(5) - if (cal == null) { - cal = Calendar.getInstance() - } - cal!!.time = date - - val year = cal.get(Calendar.YEAR) - // File format is a 1 based month, java Calendar uses a zero based month - val month = cal.get(Calendar.MONTH) + 1 - // File format is a 0 based day, java Calendar uses a 1 based day - val day = cal.get(Calendar.DAY_OF_MONTH) - 1 - val hour = cal.get(Calendar.HOUR_OF_DAY) - val minute = cal.get(Calendar.MINUTE) - val second = cal.get(Calendar.SECOND) - - buf[0] = DatabaseInputOutputUtils.writeUByte(year shr 6 and 0x0000003F) - buf[1] = DatabaseInputOutputUtils.writeUByte(year and 0x0000003F shl 2 or (month shr 2 and 0x00000003)) - buf[2] = (month and 0x00000003 shl 6 - or (day and 0x0000001F shl 1) or (hour shr 4 and 0x00000001)).toByte() - buf[3] = (hour and 0x0000000F shl 4 or (minute shr 2 and 0x0000000F)).toByte() - buf[4] = (minute and 0x00000003 shl 6 or (second and 0x0000003F)).toByte() - - return buf - } - private fun isSameDate(d1: Date?, d2: Date?): Boolean { val cal1 = Calendar.getInstance() cal1.time = d1 diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV4.kt index d40f2c5a4..c711d221f 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/PwDbHeaderV4.kt @@ -216,7 +216,7 @@ class PwDbHeaderV4(private val databaseV4: PwDatabaseV4) : PwDbHeader() { PwDbHeaderV4Fields.KdfParameters -> databaseV4.kdfParameters = KdfParameters.deserialize(fieldData) PwDbHeaderV4Fields.PublicCustomData -> { - databaseV4.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") @@ -239,7 +239,7 @@ class PwDbHeaderV4(private val databaseV4: PwDatabaseV4) : PwDbHeader() { throw IOException("Invalid cipher ID.") } - databaseV4.dataCipher = DatabaseInputOutputUtils.bytestoUUID(pbId) + databaseV4.dataCipher = DatabaseInputOutputUtils.bytesToUuid(pbId) } private fun setTransformRound(roundsByte: ByteArray?) { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV3.kt index 74b95430d..71798855f 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV3.kt @@ -288,10 +288,10 @@ class ImporterV3 : Importer() { } 0x0001 -> grp.setGroupId(LEDataInputStream.readInt(buf, offset)) 0x0002 -> grp.title = DatabaseInputOutputUtils.readCString(buf, offset) - 0x0003 -> grp.creationTime = PwDate(buf, offset) - 0x0004 -> grp.lastModificationTime = PwDate(buf, offset) - 0x0005 -> grp.lastAccessTime = PwDate(buf, offset) - 0x0006 -> grp.expiryTime = PwDate(buf, offset) + 0x0003 -> grp.creationTime = DatabaseInputOutputUtils.readCDate(buf, offset) + 0x0004 -> grp.lastModificationTime = DatabaseInputOutputUtils.readCDate(buf, offset) + 0x0005 -> grp.lastAccessTime = DatabaseInputOutputUtils.readCDate(buf, offset) + 0x0006 -> grp.expiryTime = DatabaseInputOutputUtils.readCDate(buf, offset) 0x0007 -> grp.icon = db.iconFactory.getIcon(LEDataInputStream.readInt(buf, offset)) 0x0008 -> grp.level = LEDataInputStream.readUShort(buf, offset) 0x0009 -> grp.flags = LEDataInputStream.readInt(buf, offset) @@ -309,7 +309,7 @@ class ImporterV3 : Importer() { when (fieldType) { 0x0000 -> { } - 0x0001 -> ent.nodeId = PwNodeIdUUID(DatabaseInputOutputUtils.bytestoUUID(buf, offsetMutable)) + 0x0001 -> ent.nodeId = PwNodeIdUUID(LEDataInputStream.readUuid(buf, offsetMutable)) 0x0002 -> { val pwGroupV3 = mDatabaseToOpen.createGroup() pwGroupV3.nodeId = PwNodeIdInt(LEDataInputStream.readInt(buf, offsetMutable)) @@ -330,10 +330,10 @@ class ImporterV3 : Importer() { 0x0006 -> ent.username = DatabaseInputOutputUtils.readCString(buf, offsetMutable) 0x0007 -> ent.password = DatabaseInputOutputUtils.readPassword(buf, offsetMutable) 0x0008 -> ent.notes = DatabaseInputOutputUtils.readCString(buf, offsetMutable) - 0x0009 -> ent.creationTime = PwDate(buf, offsetMutable) - 0x000A -> ent.lastModificationTime = PwDate(buf, offsetMutable) - 0x000B -> ent.lastAccessTime = PwDate(buf, offsetMutable) - 0x000C -> ent.expiryTime = PwDate(buf, offsetMutable) + 0x0009 -> ent.creationTime = DatabaseInputOutputUtils.readCDate(buf, offsetMutable) + 0x000A -> ent.lastModificationTime = DatabaseInputOutputUtils.readCDate(buf, offsetMutable) + 0x000B -> ent.lastAccessTime = DatabaseInputOutputUtils.readCDate(buf, offsetMutable) + 0x000C -> ent.expiryTime = DatabaseInputOutputUtils.readCDate(buf, offsetMutable) 0x000D -> ent.binaryDesc = DatabaseInputOutputUtils.readCString(buf, offsetMutable) 0x000E -> ent.binaryData = DatabaseInputOutputUtils.readBytes(buf, offsetMutable, fieldSize) }// Ignore field diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV4.kt index a31af4b72..76083b925 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/load/ImporterV4.kt @@ -876,7 +876,7 @@ class ImporterV4(private val streamDir: File, // TODO: Switch to framework Base64 once API level 8 is the minimum val buf = Base64Coder.decode(encoded) - return DatabaseInputOutputUtils.bytestoUUID(buf) + return DatabaseInputOutputUtils.bytesToUuid(buf) } @Throws(IOException::class, XmlPullParserException::class) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV4.kt index ec28125d5..6698e02d8 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbHeaderOutputV4.kt @@ -86,7 +86,7 @@ constructor(private val db: PwDatabaseV4, private val header: PwDbHeaderV4, os: los.writeUInt(PwDbHeaderV4.DBSIG_2.toLong()) los.writeUInt(header.version) - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.CipherID, DatabaseInputOutputUtils.UUIDtoBytes(db.dataCipher)) + writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.CipherID, DatabaseInputOutputUtils.uuidToBytes(db.dataCipher)) writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.CompressionFlags, LEDataOutputStream.writeIntBuf(PwDbHeaderV4.getFlagFromCompression(db.compressionAlgorithm))) writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.MasterSeed, header.masterSeed) @@ -94,7 +94,7 @@ constructor(private val db: PwDatabaseV4, private val header: PwDbHeaderV4, os: writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.TransformSeed, header.transformSeed) writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.TransformRounds, LEDataOutputStream.writeLongBuf(db.numberKeyEncryptionRounds)) } else { - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.KdfParameters, KdfParameters.serialize(db.kdfParameters)) + writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.KdfParameters, KdfParameters.serialize(db.kdfParameters!!)) } if (header.encryptionIV.isNotEmpty()) { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV4Output.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV4Output.kt index fa8a28634..8ab973b61 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV4Output.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwDbV4Output.kt @@ -505,7 +505,7 @@ class PwDbV4Output(private val mDatabaseV4: PwDatabaseV4, outputStream: OutputSt @Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class) private fun writeObject(name: String, uuid: UUID) { - val data = DatabaseInputOutputUtils.UUIDtoBytes(uuid) + val data = DatabaseInputOutputUtils.uuidToBytes(uuid) writeObject(name, String(Base64Coder.encode(data))) } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwEntryOutputV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwEntryOutputV3.kt index c505478f3..6c8798e81 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwEntryOutputV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwEntryOutputV3.kt @@ -47,7 +47,7 @@ class PwEntryOutputV3 // UUID mOutputStream.write(UUID_FIELD_TYPE) mOutputStream.write(UUID_FIELD_SIZE) - mOutputStream.write(DatabaseInputOutputUtils.UUIDtoBytes(mEntry.id)) + mOutputStream.write(DatabaseInputOutputUtils.uuidToBytes(mEntry.id)) // Group ID mOutputStream.write(GROUPID_FIELD_TYPE) @@ -81,16 +81,16 @@ class PwEntryOutputV3 length += DatabaseInputOutputUtils.writeCString(mEntry.notes, mOutputStream).toLong() // Create date - writeDate(CREATE_FIELD_TYPE, mEntry.creationTime.byteArrayDate) + writeDate(CREATE_FIELD_TYPE, DatabaseInputOutputUtils.writeCDate(mEntry.creationTime.date)) // Modification date - writeDate(MOD_FIELD_TYPE, mEntry.lastModificationTime.byteArrayDate) + writeDate(MOD_FIELD_TYPE, DatabaseInputOutputUtils.writeCDate(mEntry.lastModificationTime.date)) // Access date - writeDate(ACCESS_FIELD_TYPE, mEntry.lastAccessTime.byteArrayDate) + writeDate(ACCESS_FIELD_TYPE, DatabaseInputOutputUtils.writeCDate(mEntry.lastAccessTime.date)) // Expiration date - writeDate(EXPIRE_FIELD_TYPE, mEntry.expiryTime.byteArrayDate) + writeDate(EXPIRE_FIELD_TYPE, DatabaseInputOutputUtils.writeCDate(mEntry.expiryTime.date)) // Binary writeBinary(mEntry.binaryData) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwGroupOutputV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwGroupOutputV3.kt index 34f45c292..fea1c209b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwGroupOutputV3.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/file/save/PwGroupOutputV3.kt @@ -47,22 +47,22 @@ class PwGroupOutputV3 (private val mGroup: PwGroupV3, private val mOutputStream: // Create date mOutputStream.write(CREATE_FIELD_TYPE) mOutputStream.write(DATE_FIELD_SIZE) - mOutputStream.write(mGroup.creationTime.byteArrayDate) + mOutputStream.write(DatabaseInputOutputUtils.writeCDate(mGroup.creationTime.date)) // Modification date mOutputStream.write(MOD_FIELD_TYPE) mOutputStream.write(DATE_FIELD_SIZE) - mOutputStream.write(mGroup.lastModificationTime.byteArrayDate) + mOutputStream.write(DatabaseInputOutputUtils.writeCDate(mGroup.lastModificationTime.date)) // Access date mOutputStream.write(ACCESS_FIELD_TYPE) mOutputStream.write(DATE_FIELD_SIZE) - mOutputStream.write(mGroup.lastAccessTime.byteArrayDate) + mOutputStream.write(DatabaseInputOutputUtils.writeCDate(mGroup.lastAccessTime.date)) // Expiration date mOutputStream.write(EXPIRE_FIELD_TYPE) mOutputStream.write(DATE_FIELD_SIZE) - mOutputStream.write(mGroup.expiryTime.byteArrayDate) + mOutputStream.write(DatabaseInputOutputUtils.writeCDate(mGroup.expiryTime.date)) // Image ID mOutputStream.write(IMAGEID_FIELD_TYPE) diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/UuidUtil.java b/app/src/main/java/com/kunzisoft/keepass/database/search/UuidUtil.java index 7ab28392f..b3119ca01 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/search/UuidUtil.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/search/UuidUtil.java @@ -24,11 +24,11 @@ import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils; import java.util.UUID; public class UuidUtil { + public static String toHexString(UUID uuid) { if (uuid == null) { return null; } - byte[] buf = DatabaseInputOutputUtils.UUIDtoBytes(uuid); - if (buf == null) { return null; } + byte[] buf = DatabaseInputOutputUtils.INSTANCE.uuidToBytes(uuid); int len = buf.length; if (len == 0) { return ""; } @@ -37,17 +37,10 @@ public class UuidUtil { short bt; char high, low; - for (int i = 0; i < len; i++) { - bt = (short)(buf[i] & 0xFF); - high = (char)(bt >>> 4); - - - low = (char)(bt & 0x0F); - - char h,l; - h = byteToChar(high); - l = byteToChar(low); - + for (byte b : buf) { + bt = (short) (b & 0xFF); + high = (char) (bt >>> 4); + low = (char) (bt & 0x0F); sb.append(byteToChar(high)); sb.append(byteToChar(low)); } diff --git a/app/src/main/java/com/kunzisoft/keepass/stream/HashedBlockInputStream.java b/app/src/main/java/com/kunzisoft/keepass/stream/HashedBlockInputStream.java deleted file mode 100644 index 8e76e3e38..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/stream/HashedBlockInputStream.java +++ /dev/null @@ -1,165 +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 . - * - */ -package com.kunzisoft.keepass.stream; - -import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; - - -public class HashedBlockInputStream extends InputStream { - - private final static int HASH_SIZE = 32; - - private LEDataInputStream baseStream; - private int bufferPos = 0; - private byte[] buffer = new byte[0]; - private long bufferIndex = 0; - private boolean atEnd = false; - - - @Override - public int read(byte[] b) throws IOException { - return read(b, 0, b.length); - } - - public HashedBlockInputStream(InputStream is) { - baseStream = new LEDataInputStream(is); - } - - @Override - public int read(byte[] b, int offset, int length) throws IOException { - if ( atEnd ) return -1; - - int remaining = length; - - while ( remaining > 0 ) { - if ( bufferPos == buffer.length ) { - // Get more from the source into the buffer - if ( ! ReadHashedBlock() ) { - return length - remaining; - } - - } - - // Copy from buffer out - int copyLen = Math.min(buffer.length - bufferPos, remaining); - - System.arraycopy(buffer, bufferPos, b, offset, copyLen); - - offset += copyLen; - bufferPos += copyLen; - - remaining -= copyLen; - } - - return length; - } - - /** - * @return false, when the end of the source stream is reached - * @throws IOException - */ - private boolean ReadHashedBlock() throws IOException { - if ( atEnd ) return false; - - bufferPos = 0; - - long index = baseStream.readUInt(); - if ( index != bufferIndex ) { - throw new IOException("Invalid data format"); - } - bufferIndex++; - - byte[] storedHash = baseStream.readBytes(32); - if ( storedHash == null || storedHash.length != HASH_SIZE) { - throw new IOException("Invalid data format"); - } - - int bufferSize = LEDataInputStream.readInt(baseStream); - if ( bufferSize < 0 ) { - throw new IOException("Invalid data format"); - } - - if ( bufferSize == 0 ) { - for (int hash = 0; hash < HASH_SIZE; hash++) { - if ( storedHash[hash] != 0 ) { - throw new IOException("Invalid data format"); - } - } - - atEnd = true; - buffer = new byte[0]; - return false; - } - - buffer = baseStream.readBytes(bufferSize); - if ( buffer == null || buffer.length != bufferSize ) { - throw new IOException("Invalid data format"); - } - - MessageDigest md = null; - try { - md = MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e) { - throw new IOException("SHA-256 not implemented here."); - } - - byte[] computedHash = md.digest(buffer); - if ( computedHash == null || computedHash.length != HASH_SIZE ) { - throw new IOException("Hash wrong size"); - } - - if ( ! Arrays.equals(storedHash, computedHash) ) { - throw new IOException("Hashes didn't match."); - } - - return true; - } - - @Override - public long skip(long n) throws IOException { - return 0; - } - - @Override - public int read() throws IOException { - if ( atEnd ) return -1; - - if ( bufferPos == buffer.length ) { - if ( ! ReadHashedBlock() ) return -1; - } - - int output = DatabaseInputOutputUtils.readUByte(buffer, bufferPos); - bufferPos++; - - return output; - } - - @Override - public void close() throws IOException { - baseStream.close(); - } - -} diff --git a/app/src/main/java/com/kunzisoft/keepass/stream/HashedBlockInputStream.kt b/app/src/main/java/com/kunzisoft/keepass/stream/HashedBlockInputStream.kt new file mode 100644 index 000000000..10877dfac --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/stream/HashedBlockInputStream.kt @@ -0,0 +1,164 @@ +/* + * 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 . + * + */ +package com.kunzisoft.keepass.stream + +import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils + +import java.io.IOException +import java.io.InputStream +import java.security.MessageDigest +import java.security.NoSuchAlgorithmException +import java.util.Arrays + + +class HashedBlockInputStream(inputStream: InputStream) : InputStream() { + + private val baseStream: LEDataInputStream = LEDataInputStream(inputStream) + private var bufferPos = 0 + private var buffer: ByteArray = ByteArray(0) + private var bufferIndex: Long = 0 + private var atEnd = false + + @Throws(IOException::class) + override fun read(b: ByteArray): Int { + return read(b, 0, b.size) + } + + @Throws(IOException::class) + override fun read(outBuffer: ByteArray, byteOffset: Int, length: Int): Int { + var offset = byteOffset + if (atEnd) return -1 + + var remaining = length + + while (remaining > 0) { + if (bufferPos == buffer.size) { + // Get more from the source into the buffer + if (!readHashedBlock()) { + return length - remaining + } + + } + + // Copy from buffer out + val copyLen = (buffer.size - bufferPos).coerceAtMost(remaining) + + System.arraycopy(buffer, bufferPos, outBuffer, offset, copyLen) + + offset += copyLen + bufferPos += copyLen + + remaining -= copyLen + } + + return length + } + + /** + * @return false, when the end of the source stream is reached + * @throws IOException + */ + @Throws(IOException::class) + private fun readHashedBlock(): Boolean { + if (atEnd) return false + + bufferPos = 0 + + val index = baseStream.readUInt() + if (index != bufferIndex) { + throw IOException("Invalid data format") + } + bufferIndex++ + + val storedHash = baseStream.readBytes(32) + if (storedHash == null || storedHash.size != HASH_SIZE) { + throw IOException("Invalid data format") + } + + val bufferSize = LEDataInputStream.readInt(baseStream) + if (bufferSize < 0) { + throw IOException("Invalid data format") + } + + if (bufferSize == 0) { + for (hash in 0 until HASH_SIZE) { + if (storedHash[hash].toInt() != 0) { + throw IOException("Invalid data format") + } + } + + atEnd = true + buffer = ByteArray(0) + return false + } + + buffer = baseStream.readBytes(bufferSize) + if (buffer.size != bufferSize) { + throw IOException("Invalid data format") + } + + val messageDigest: MessageDigest + try { + messageDigest = MessageDigest.getInstance("SHA-256") + } catch (e: NoSuchAlgorithmException) { + throw IOException("SHA-256 not implemented here.") + } + + val computedHash = messageDigest.digest(buffer) + if (computedHash == null || computedHash.size != HASH_SIZE) { + throw IOException("Hash wrong size") + } + + if (!Arrays.equals(storedHash, computedHash)) { + throw IOException("Hashes didn't match.") + } + + return true + } + + @Throws(IOException::class) + override fun skip(n: Long): Long { + return 0 + } + + @Throws(IOException::class) + override fun read(): Int { + if (atEnd) return -1 + + if (bufferPos == buffer.size) { + if (!readHashedBlock()) return -1 + } + + val output = DatabaseInputOutputUtils.readUByte(buffer, bufferPos) + bufferPos++ + + return output + } + + @Throws(IOException::class) + override fun close() { + baseStream.close() + } + + companion object { + + private const val HASH_SIZE = 32 + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/stream/HmacBlockInputStream.java b/app/src/main/java/com/kunzisoft/keepass/stream/HmacBlockInputStream.java deleted file mode 100644 index 870800d96..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/stream/HmacBlockInputStream.java +++ /dev/null @@ -1,175 +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 . - * - */ -package com.kunzisoft.keepass.stream; - -import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -public class HmacBlockInputStream extends InputStream { - private LEDataInputStream baseStream; - private boolean verify; - private byte[] key; - private byte[] buffer; - private int bufferPos = 0; - private long blockIndex = 0; - private boolean endOfStream = false; - - public HmacBlockInputStream(InputStream baseStream, boolean verify, byte[] key) { - super(); - - this.baseStream = new LEDataInputStream(baseStream); - this.verify = verify; - this.key = key; - buffer = new byte[0]; - } - - @Override - public int read() throws IOException { - if (endOfStream) return -1; - - if (bufferPos == buffer.length) { - if (!readSafeBlock()) return -1; - } - - int output = DatabaseInputOutputUtils.readUByte(buffer, bufferPos); - bufferPos++; - - return output; - } - - @Override - public int read(byte[] outBuffer, int byteOffset, int byteCount) throws IOException { - int remaining = byteCount; - while (remaining > 0) { - if (bufferPos == buffer.length) { - if (!readSafeBlock()) { - int read = byteCount - remaining; - if (read <= 0) { - return -1; - } else { - return byteCount - remaining; - } - } - } - - int copy = Math.min(buffer.length - bufferPos, remaining); - assert(copy > 0); - - System.arraycopy(buffer, bufferPos, outBuffer, byteOffset, copy); - byteOffset += copy; - bufferPos += copy; - - remaining -= copy; - } - - return byteCount; - } - - @Override - public int read(byte[] outBuffer) throws IOException { - return read(outBuffer, 0, outBuffer.length); - } - - private boolean readSafeBlock() throws IOException { - if (endOfStream) return false; - - byte[] storedHmac = baseStream.readBytes(32); - if (storedHmac == null || storedHmac.length != 32) { - throw new IOException("File corrupted"); - } - - byte[] pbBlockIndex = LEDataOutputStream.writeLongBuf(blockIndex); - byte[] pbBlockSize = baseStream.readBytes(4); - if (pbBlockSize == null || pbBlockSize.length != 4) { - throw new IOException("File corrupted"); - } - int blockSize = LEDataInputStream.readInt(pbBlockSize, 0); - bufferPos = 0; - - buffer = baseStream.readBytes(blockSize); - - if (verify) { - byte[] cmpHmac; - byte[] blockKey = HmacBlockStream.GetHmacKey64(key, blockIndex); - Mac hmac; - try { - hmac = Mac.getInstance("HmacSHA256"); - SecretKeySpec signingKey = new SecretKeySpec(blockKey, "HmacSHA256"); - hmac.init(signingKey); - } catch (NoSuchAlgorithmException e) { - throw new IOException("Invalid Hmac"); - } catch (InvalidKeyException e) { - throw new IOException("Invalid Hmac"); - } - - hmac.update(pbBlockIndex); - hmac.update(pbBlockSize); - - if (buffer.length > 0) { - hmac.update(buffer); - } - - cmpHmac = hmac.doFinal(); - Arrays.fill(blockKey, (byte)0); - - if (!Arrays.equals(cmpHmac, storedHmac)) { - throw new IOException("Invalid Hmac"); - } - - } - - blockIndex++; - - if (blockSize == 0) { - endOfStream = true; - return false; - } - - return true; - } - - @Override - public boolean markSupported() { - return false; - } - - @Override - public void close() throws IOException { - baseStream.close(); - } - - @Override - public long skip(long byteCount) throws IOException { - return 0; - } - - @Override - public int available() throws IOException { - return buffer.length - bufferPos; - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/stream/HmacBlockInputStream.kt b/app/src/main/java/com/kunzisoft/keepass/stream/HmacBlockInputStream.kt new file mode 100644 index 000000000..93d244271 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/stream/HmacBlockInputStream.kt @@ -0,0 +1,166 @@ +/* + * 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 . + * + */ +package com.kunzisoft.keepass.stream + +import com.kunzisoft.keepass.utils.DatabaseInputOutputUtils + +import java.io.IOException +import java.io.InputStream +import java.security.InvalidKeyException +import java.security.NoSuchAlgorithmException +import java.util.Arrays + +import javax.crypto.Mac +import javax.crypto.spec.SecretKeySpec + +class HmacBlockInputStream(baseStream: InputStream, private val verify: Boolean, private val key: ByteArray) : InputStream() { + + private val baseStream: LEDataInputStream = LEDataInputStream(baseStream) + private var buffer: ByteArray = ByteArray(0) + private var bufferPos = 0 + private var blockIndex: Long = 0 + private var endOfStream = false + + @Throws(IOException::class) + override fun read(): Int { + if (endOfStream) return -1 + + if (bufferPos == buffer.size) { + if (!readSafeBlock()) return -1 + } + + val output = DatabaseInputOutputUtils.readUByte(buffer, bufferPos) + bufferPos++ + + return output + } + + @Throws(IOException::class) + override fun read(outBuffer: ByteArray, byteOffset: Int, byteCount: Int): Int { + var offset = byteOffset + var remaining = byteCount + while (remaining > 0) { + if (bufferPos == buffer.size) { + if (!readSafeBlock()) { + val read = byteCount - remaining + return if (read <= 0) { + -1 + } else { + byteCount - remaining + } + } + } + + val copy = (buffer.size - bufferPos).coerceAtMost(remaining) + assert(copy > 0) + + System.arraycopy(buffer, bufferPos, outBuffer, offset, copy) + offset += copy + bufferPos += copy + + remaining -= copy + } + + return byteCount + } + + @Throws(IOException::class) + override fun read(outBuffer: ByteArray): Int { + return read(outBuffer, 0, outBuffer.size) + } + + @Throws(IOException::class) + private fun readSafeBlock(): Boolean { + if (endOfStream) return false + + val storedHmac = baseStream.readBytes(32) + if (storedHmac == null || storedHmac.size != 32) { + throw IOException("File corrupted") + } + + val pbBlockIndex = LEDataOutputStream.writeLongBuf(blockIndex) + val pbBlockSize = baseStream.readBytes(4) + if (pbBlockSize == null || pbBlockSize.size != 4) { + throw IOException("File corrupted") + } + val blockSize = LEDataInputStream.readInt(pbBlockSize, 0) + bufferPos = 0 + + buffer = baseStream.readBytes(blockSize) + + if (verify) { + val cmpHmac: ByteArray + val blockKey = HmacBlockStream.GetHmacKey64(key, blockIndex) + val hmac: Mac + try { + hmac = Mac.getInstance("HmacSHA256") + val signingKey = SecretKeySpec(blockKey, "HmacSHA256") + hmac.init(signingKey) + } catch (e: NoSuchAlgorithmException) { + throw IOException("Invalid Hmac") + } catch (e: InvalidKeyException) { + throw IOException("Invalid Hmac") + } + + hmac.update(pbBlockIndex) + hmac.update(pbBlockSize) + + if (buffer.isNotEmpty()) { + hmac.update(buffer) + } + + cmpHmac = hmac.doFinal() + Arrays.fill(blockKey, 0.toByte()) + + if (!Arrays.equals(cmpHmac, storedHmac)) { + throw IOException("Invalid Hmac") + } + + } + + blockIndex++ + + if (blockSize == 0) { + endOfStream = true + return false + } + + return true + } + + override fun markSupported(): Boolean { + return false + } + + @Throws(IOException::class) + override fun close() { + baseStream.close() + } + + @Throws(IOException::class) + override fun skip(byteCount: Long): Long { + return 0 + } + + @Throws(IOException::class) + override fun available(): Int { + return buffer.size - bufferPos + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/stream/LEDataInputStream.java b/app/src/main/java/com/kunzisoft/keepass/stream/LEDataInputStream.java index fb3ef1615..1b79dfde5 100644 --- a/app/src/main/java/com/kunzisoft/keepass/stream/LEDataInputStream.java +++ b/app/src/main/java/com/kunzisoft/keepass/stream/LEDataInputStream.java @@ -22,6 +22,7 @@ package com.kunzisoft.keepass.stream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; +import java.util.UUID; /** Little endian version of the DataInputStream @@ -210,4 +211,17 @@ public class LEDataInputStream extends InputStream { + ((buf[offset + 3] & 0xFF) << 24); } + public static UUID readUuid( byte[] buf, int offset ) { + long lsb = 0; + for (int i = 15; i >= 8; i--) { + lsb = (lsb << 8) | (buf[i + offset] & 0xff); + } + + long msb = 0; + for (int i = 7; i >= 0; i--) { + msb = (msb << 8) | (buf[i + offset] & 0xff); + } + + return new UUID(msb, lsb); + } } diff --git a/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.java b/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.java deleted file mode 100644 index f7617f5ac..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.java +++ /dev/null @@ -1,184 +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 . - * - * -KeePass for J2ME - -Copyright 2007 Naomaru Itoi - -This file was derived from - -Java clone of KeePass - A KeePass file viewer for Java -Copyright 2006 Bill Zwicky - -This program 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; version 2 - -This program 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 this program; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -package com.kunzisoft.keepass.utils; - -import com.kunzisoft.keepass.stream.LEDataOutputStream; - -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.Charset; -import java.util.UUID; - - -/** - * Tools for slicing and dicing Java and KeePass data types. - * - * @author Bill Zwicky - */ -public class DatabaseInputOutputUtils { - - public static long ULONG_MAX_VALUE = -1; - - private static Charset defaultCharset = Charset.forName("UTF-8"); - - private static final byte[] CRLFbuf = { 0x0D, 0x0A }; - private static final String CRLF = new String(CRLFbuf); - private static final String SEP = System.getProperty("line.separator"); - private static final boolean REPLACE = !SEP.equals(CRLF); - - /** Read an unsigned byte */ - public static int readUByte( byte[] buf, int offset ) { - return ((int)buf[offset] & 0xFF); - } - - /** - * Write an unsigned byte - */ - public static void writeUByte(int val, byte[] buf, int offset) { - buf[offset] = (byte)(val & 0xFF); - } - - public static byte writeUByte(int val) { - byte[] buf = new byte[1]; - - writeUByte(val, buf, 0); - - return buf[0]; - } - - /** - * Return len of null-terminated string (i.e. distance to null) - * within a byte buffer. - */ - private static int strlen( byte[] buf, int offset ) { - int len = 0; - while( buf[offset + len] != 0 ) - len++; - return len; - } - - public static String readCString(byte[] buf, int offset) { - String jstring = new String(buf, offset, strlen(buf, offset), defaultCharset); - - if ( REPLACE ) { - jstring = jstring.replace(CRLF, SEP); - } - - return jstring; - } - - public static int writeCString(String str, OutputStream os) throws IOException { - if ( str == null ) { - // Write out a null character - os.write(LEDataOutputStream.writeIntBuf(1)); - os.write(0x00); - return 0; - } - - if ( REPLACE ) { - str = str.replace(SEP, CRLF); - } - - byte[] initial = str.getBytes(defaultCharset); - - int length = initial.length+1; - os.write(LEDataOutputStream.writeIntBuf(length)); - os.write(initial); - os.write(0x00); - - return length; - } - - public static String readPassword(byte[] buf, int offset) { - return new String(buf, offset, strlen(buf, offset), defaultCharset); - } - - public static int writePassword(String str, OutputStream os) throws IOException { - byte[] initial = str.getBytes(defaultCharset); - int length = initial.length+1; - os.write(LEDataOutputStream.writeIntBuf(length)); - os.write(initial); - os.write(0x00); - return length; - } - - public static byte[] readBytes(byte[] buf, int offset, int len) { - byte[] binaryData = new byte[len]; - System.arraycopy(buf, offset, binaryData, 0, len); - return binaryData; - } - - public static int writeBytes(byte[] data, int dataLen, OutputStream os ) throws IOException { - os.write(LEDataOutputStream.writeIntBuf(dataLen)); - if (data != null) { - os.write(data); - } - return dataLen; - } - - public static UUID bytestoUUID(byte[] buf) { - return bytestoUUID(buf, 0); - } - - public static UUID bytestoUUID(byte[] buf, int offset) { - long lsb = 0; - for (int i = 15; i >= 8; i--) { - lsb = (lsb << 8) | (buf[i + offset] & 0xff); - } - - long msb = 0; - for (int i = 7; i >= 0; i--) { - msb = (msb << 8) | (buf[i + offset] & 0xff); - } - - return new UUID(msb, lsb); - } - - public static byte[] UUIDtoBytes(UUID uuid) { - byte[] buf = new byte[16]; - LEDataOutputStream.writeLong(uuid.getMostSignificantBits(), buf, 0); - LEDataOutputStream.writeLong(uuid.getLeastSignificantBits(), buf, 8); - return buf; - } - -} diff --git a/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.kt b/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.kt new file mode 100644 index 000000000..ff98e6459 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/utils/DatabaseInputOutputUtils.kt @@ -0,0 +1,233 @@ +/* + * 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 . + * + * +KeePass for J2ME + +Copyright 2007 Naomaru Itoi + +This file was derived from + +Java clone of KeePass - A KeePass file viewer for Java +Copyright 2006 Bill Zwicky + +This program 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; version 2 + +This program 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 this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +package com.kunzisoft.keepass.utils + +import com.kunzisoft.keepass.database.element.PwDate +import com.kunzisoft.keepass.stream.LEDataInputStream +import com.kunzisoft.keepass.stream.LEDataOutputStream +import java.io.IOException +import java.io.OutputStream +import java.nio.charset.Charset +import java.util.* + + +/** + * Tools for slicing and dicing Java and KeePass data types. + * + * @author Bill Zwicky @pobox.com> + */ +object DatabaseInputOutputUtils { + + var ULONG_MAX_VALUE: Long = -1 + + private val defaultCharset = Charset.forName("UTF-8") + + private val CRLFbuf = byteArrayOf(0x0D, 0x0A) + private val CRLF = String(CRLFbuf) + private val SEP = System.getProperty("line.separator") + private val REPLACE = SEP != CRLF + + /** Read an unsigned byte */ + fun readUByte(buf: ByteArray, offset: Int): Int { + return buf[offset].toInt() and 0xFF + } + + /** + * Write an unsigned byte + */ + fun writeUByte(`val`: Int, buf: ByteArray, offset: Int) { + buf[offset] = (`val` and 0xFF).toByte() + } + + fun writeUByte(`val`: Int): Byte { + val buf = ByteArray(1) + + writeUByte(`val`, buf, 0) + + return buf[0] + } + + /** + * Return len of null-terminated string (i.e. distance to null) + * within a byte buffer. + */ + private fun strlen(buf: ByteArray, offset: Int): Int { + var len = 0 + while (buf[offset + len].toInt() != 0) + len++ + return len + } + + fun readCString(buf: ByteArray, offset: Int): String { + var jstring = String(buf, offset, strlen(buf, offset), defaultCharset) + + if (REPLACE) { + jstring = jstring.replace(CRLF, SEP!!) + } + + return jstring + } + + @Throws(IOException::class) + fun writeCString(string: String?, os: OutputStream): Int { + var str = string + if (str == null) { + // Write out a null character + os.write(LEDataOutputStream.writeIntBuf(1)) + os.write(0x00) + return 0 + } + + if (REPLACE) { + str = str.replace(SEP!!, CRLF) + } + + val initial = str.toByteArray(defaultCharset) + + val length = initial.size + 1 + os.write(LEDataOutputStream.writeIntBuf(length)) + os.write(initial) + os.write(0x00) + + return length + } + + /** + * Unpack date from 5 byte format. The five bytes at 'offset' are unpacked + * to a java.util.Date instance. + */ + fun readCDate(buf: ByteArray, offset: Int, calendar: Calendar = Calendar.getInstance()): PwDate { + val dateSize = 5 + val cDate = ByteArray(dateSize) + System.arraycopy(buf, offset, cDate, 0, dateSize) + + val readOffset = 0 + val dw1 = readUByte(cDate, readOffset) + val dw2 = readUByte(cDate, readOffset + 1) + val dw3 = readUByte(cDate, readOffset + 2) + val dw4 = readUByte(cDate, readOffset + 3) + val dw5 = readUByte(cDate, readOffset + 4) + + // Unpack 5 byte structure to date and time + val year = dw1 shl 6 or (dw2 shr 2) + val month = dw2 and 0x00000003 shl 2 or (dw3 shr 6) + + val day = dw3 shr 1 and 0x0000001F + val hour = dw3 and 0x00000001 shl 4 or (dw4 shr 4) + val minute = dw4 and 0x0000000F shl 2 or (dw5 shr 6) + val second = dw5 and 0x0000003F + + // File format is a 1 based month, java Calendar uses a zero based month + // File format is a 1 based day, java Calendar uses a 1 based day + calendar.set(year, month - 1, day, hour, minute, second) + + return PwDate(calendar.time) + } + + fun writeCDate(date: Date?, calendar: Calendar = Calendar.getInstance()): ByteArray? { + if (date == null) { + return null + } + + val buf = ByteArray(5) + calendar.time = date + + val year = calendar.get(Calendar.YEAR) + // File format is a 1 based month, java Calendar uses a zero based month + val month = calendar.get(Calendar.MONTH) + 1 + // File format is a 1 based day, java Calendar uses a 1 based day + val day = calendar.get(Calendar.DAY_OF_MONTH) + val hour = calendar.get(Calendar.HOUR_OF_DAY) + val minute = calendar.get(Calendar.MINUTE) + val second = calendar.get(Calendar.SECOND) + + buf[0] = writeUByte(year shr 6 and 0x0000003F) + buf[1] = writeUByte(year and 0x0000003F shl 2 or (month shr 2 and 0x00000003)) + buf[2] = (month and 0x00000003 shl 6 + or (day and 0x0000001F shl 1) or (hour shr 4 and 0x00000001)).toByte() + buf[3] = (hour and 0x0000000F shl 4 or (minute shr 2 and 0x0000000F)).toByte() + buf[4] = (minute and 0x00000003 shl 6 or (second and 0x0000003F)).toByte() + + return buf + } + + fun readPassword(buf: ByteArray, offset: Int): String { + return String(buf, offset, strlen(buf, offset), defaultCharset) + } + + @Throws(IOException::class) + fun writePassword(str: String, os: OutputStream): Int { + val initial = str.toByteArray(defaultCharset) + val length = initial.size + 1 + os.write(LEDataOutputStream.writeIntBuf(length)) + os.write(initial) + os.write(0x00) + return length + } + + fun readBytes(buf: ByteArray, offset: Int, len: Int): ByteArray { + val binaryData = ByteArray(len) + System.arraycopy(buf, offset, binaryData, 0, len) + return binaryData + } + + @Throws(IOException::class) + fun writeBytes(data: ByteArray?, dataLen: Int, os: OutputStream): Int { + os.write(LEDataOutputStream.writeIntBuf(dataLen)) + if (data != null) { + os.write(data) + } + return dataLen + } + + fun bytesToUuid(buf: ByteArray): UUID { + return LEDataInputStream.readUuid(buf, 0) + } + + fun uuidToBytes(uuid: UUID): ByteArray { + val buf = ByteArray(16) + LEDataOutputStream.writeLong(uuid.mostSignificantBits, buf, 0) + LEDataOutputStream.writeLong(uuid.leastSignificantBits, buf, 8) + return buf + } +}