diff --git a/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwEntryTestV4.java b/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwEntryTestV4.java index 3dc3c2718..1644ba56f 100644 --- a/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwEntryTestV4.java +++ b/app/src/androidTest/java/com/kunzisoft/keepass/tests/PwEntryTestV4.java @@ -19,18 +19,8 @@ */ package com.kunzisoft.keepass.tests; -import com.kunzisoft.keepass.database.AutoType; -import com.kunzisoft.keepass.database.element.PwEntryV4; -import com.kunzisoft.keepass.database.element.PwGroupV4; -import com.kunzisoft.keepass.database.element.PwIconCustom; -import com.kunzisoft.keepass.database.element.PwIconStandard; -import com.kunzisoft.keepass.database.security.ProtectedBinary; -import com.kunzisoft.keepass.database.security.ProtectedString; - import junit.framework.TestCase; -import java.util.UUID; - public class PwEntryTestV4 extends TestCase { public void testAssign() { /* diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.java b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.java index 5b9070006..4dc4ad970 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.java +++ b/app/src/main/java/com/kunzisoft/keepass/activities/EntryActivity.java @@ -42,7 +42,7 @@ import com.getkeepsafe.taptargetview.TapTargetView; import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.activities.lock.LockingHideActivity; import com.kunzisoft.keepass.app.App; -import com.kunzisoft.keepass.database.ExtraFields; +import com.kunzisoft.keepass.database.element.ExtraFields; import com.kunzisoft.keepass.database.element.Database; import com.kunzisoft.keepass.database.element.EntryVersioned; import com.kunzisoft.keepass.database.element.PwNodeId; @@ -61,6 +61,9 @@ import com.kunzisoft.keepass.view.EntryContentsView; import java.util.ArrayList; import java.util.Date; +import kotlin.Unit; +import kotlin.jvm.functions.Function2; + import static com.kunzisoft.keepass.settings.PreferencesUtil.isClipboardNotificationsEnable; import static com.kunzisoft.keepass.settings.PreferencesUtil.isFirstTimeAskAllowCopyPasswordAndProtectedFields; @@ -205,10 +208,10 @@ public class EntryActivity extends LockingHideActivity { // Add extra fields if (containsExtraFieldToCopy) { try { - mEntry.getFields().doActionToAllCustomProtectedField(new ExtraFields.ActionProtected() { + mEntry.getFields().doActionToAllCustomProtectedField(new Function2() { private int anonymousFieldNumber = 0; @Override - public void doAction(String key, ProtectedString value) { + public Unit invoke(String key, ProtectedString value) { //If value is not protected or allowed if (!value.isProtected() || PreferencesUtil.allowCopyPasswordAndProtectedFields(EntryActivity.this)) { notificationFields.add( @@ -219,6 +222,7 @@ public class EntryActivity extends LockingHideActivity { getResources())); anonymousFieldNumber++; } + return null; } }); } catch (ArrayIndexOutOfBoundsException e) { @@ -378,6 +382,7 @@ public class EntryActivity extends LockingHideActivity { getString(R.string.copy_field, label) ) ); + return null; }); } diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/EntryEditActivity.java b/app/src/main/java/com/kunzisoft/keepass/activities/EntryEditActivity.java index 6d3483eeb..66f53fcd0 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/EntryEditActivity.java +++ b/app/src/main/java/com/kunzisoft/keepass/activities/EntryEditActivity.java @@ -523,6 +523,7 @@ public class EntryEditActivity extends LockingHideActivity entryEditCustomField.setData(key, value); entryEditCustomField.setFontVisibility(visibilityFontActivated); container.addView(entryEditCustomField); + return null; }); } } diff --git a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.java b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.java index fba39248e..694634a49 100644 --- a/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.java +++ b/app/src/main/java/com/kunzisoft/keepass/activities/GroupActivity.java @@ -72,6 +72,7 @@ import com.kunzisoft.keepass.database.action.node.MoveEntryRunnable; import com.kunzisoft.keepass.database.action.node.MoveGroupRunnable; import com.kunzisoft.keepass.database.action.node.UpdateGroupRunnable; import com.kunzisoft.keepass.database.element.*; +import com.kunzisoft.keepass.database.security.ProtectedString; import com.kunzisoft.keepass.dialogs.AssignMasterKeyDialogFragment; import com.kunzisoft.keepass.dialogs.GroupEditDialogFragment; import com.kunzisoft.keepass.dialogs.IconPickerDialogFragment; @@ -92,6 +93,9 @@ import net.cachapa.expandablelayout.ExpandableLayout; import org.jetbrains.annotations.NotNull; +import kotlin.Unit; +import kotlin.jvm.functions.Function2; + public class GroupActivity extends LockingActivity implements GroupEditDialogFragment.EditGroupListener, IconPickerDialogFragment.IconPickerListener, @@ -534,9 +538,14 @@ public class GroupActivity extends LockingActivity entryModel.setUrl(entry.getUrl()); if (entry.containsCustomFields()) { entry.getFields() - .doActionToAllCustomProtectedField( - (key, value) -> entryModel.addCustomField( - new Field(key, value.toString()))); + .doActionToAllCustomProtectedField(new Function2() { + @Override + public Unit invoke(String key, ProtectedString value) { + entryModel.addCustomField( + new Field(key, value.toString())); + return null; + } + }); } return entryModel; } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/AutoType.java b/app/src/main/java/com/kunzisoft/keepass/database/AutoType.java deleted file mode 100644 index 2e8fb380f..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/AutoType.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2018 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.database; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.kunzisoft.keepass.utils.MemUtil; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class AutoType implements Parcelable { - private static final long OBF_OPT_NONE = 0; - - public boolean enabled = true; - public long obfuscationOptions = OBF_OPT_NONE; - public String defaultSequence = ""; - private HashMap windowSeqPairs = new HashMap<>(); - - public AutoType() {} - - public AutoType(AutoType autoType) { - this.enabled = autoType.enabled; - this.obfuscationOptions = autoType.obfuscationOptions; - this.defaultSequence = autoType.defaultSequence; - for (Map.Entry entry: autoType.windowSeqPairs.entrySet()) { - this.windowSeqPairs.put(entry.getKey(), entry.getValue()); - } - } - - public AutoType(Parcel in) { - this.enabled = in.readByte() != 0; - this.obfuscationOptions = in.readLong(); - this.defaultSequence = in.readString(); - this.windowSeqPairs = MemUtil.readStringParcelableMap(in); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeByte((byte) (enabled ? 1 : 0)); - dest.writeLong(obfuscationOptions); - dest.writeString(defaultSequence); - MemUtil.writeStringParcelableMap(dest, windowSeqPairs); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public AutoType createFromParcel(Parcel in) { - return new AutoType(in); - } - - @Override - public AutoType[] newArray(int size) { - return new AutoType[size]; - } - }; - - public void put(String key, String value) { - windowSeqPairs.put(key, value); - } - - public Set> entrySet() { - return windowSeqPairs.entrySet(); - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/BinaryPool.java b/app/src/main/java/com/kunzisoft/keepass/database/BinaryPool.java deleted file mode 100644 index 14e5f8df9..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/BinaryPool.java +++ /dev/null @@ -1,110 +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.database; - -import com.kunzisoft.keepass.database.element.GroupVersioned; -import com.kunzisoft.keepass.database.element.PwGroupV4; -import com.kunzisoft.keepass.database.security.ProtectedBinary; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -public class BinaryPool { - private HashMap pool = new HashMap<>(); - - public BinaryPool() { - } - - public BinaryPool(PwGroupV4 rootGroup) { - // TODO ? build(rootGroup); - } - - public ProtectedBinary get(int key) { - return pool.get(key); - } - - public ProtectedBinary put(int key, ProtectedBinary value) { - return pool.put(key, value); - } - - - public Set> entrySet() { - return pool.entrySet(); - } - - public void clear() { - for (Entry entry: pool.entrySet()) - entry.getValue().clear(); - pool.clear(); - } - - public Collection binaries() { - return pool.values(); - } - - private void add(Map dict) { - for (ProtectedBinary pb : dict.values()) { - add(pb); - } - - } - - public void add(ProtectedBinary pb) { - assert(pb != null); - if (findKey(pb) != -1) return; - - pool.put(findUnusedKey(), pb); - } - - public int findUnusedKey() { - int unusedKey = pool.size(); - while(get(unusedKey) != null) - unusedKey++; - return unusedKey; - } - - public int findKey(ProtectedBinary pb) { - for (Entry pair : pool.entrySet()) { - if (pair.getValue().equals(pb)) return pair.getKey(); - } - - return -1; - } - - private void build(GroupVersioned rootGroup) { - /* - rootGroup.doForEachChild(new EntryHandler() { - @Override - public boolean operate(EntryVersioned entryInterface) { - PwEntryV4 entry = entryInterface.getPwEntryV4(); - - for (PwEntryV4 histEntry : entry.getHistory()) { - add(histEntry.getBinaries()); - } - add(entry.getBinaries()); - return true; - } - }, null); - */ - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeader.java b/app/src/main/java/com/kunzisoft/keepass/database/CrsAlgorithm.kt similarity index 65% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeader.java rename to app/src/main/java/com/kunzisoft/keepass/database/CrsAlgorithm.kt index cd0c86e03..b50c1522d 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeader.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/CrsAlgorithm.kt @@ -17,16 +17,25 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database.element; +package com.kunzisoft.keepass.database -public abstract class PwDbHeader { +enum class CrsAlgorithm constructor(val id: Int) { - public static final int PWM_DBSIG_1 = 0x9AA2D903; + Null(0), + ArcFourVariant(1), + Salsa20(2), + ChaCha20(3); - /** Seed that gets hashed with the userkey to form the final key */ - public byte masterSeed[]; + companion object { + + fun fromId(num: Int): CrsAlgorithm? { + for (e in values()) { + if (e.id == num) { + return e + } + } + return null + } + } - /** IV used for content encryption */ - public byte encryptionIV[] = new byte[16]; - } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/ExtraFields.java b/app/src/main/java/com/kunzisoft/keepass/database/ExtraFields.java deleted file mode 100644 index 2bb63ca5f..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/ExtraFields.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2018 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.database; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.kunzisoft.keepass.database.security.ProtectedString; -import com.kunzisoft.keepass.utils.MemUtil; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import static com.kunzisoft.keepass.database.element.PwEntryV4.*; - -public class ExtraFields implements Parcelable { - - private Map fields; - - public ExtraFields() { - fields = new HashMap<>(); - } - - public ExtraFields(ExtraFields extraFields) { - this(); - for (Map.Entry entry: extraFields.fields.entrySet()) { - fields.put(entry.getKey(), new ProtectedString(entry.getValue())); - } - } - - public ExtraFields(Parcel in) { - fields = MemUtil.readStringParcelableMap(in, ProtectedString.class); - } - - @Override - public int describeContents() { - return 0; - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - MemUtil.writeStringParcelableMap(dest, flags, fields); - } - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public ExtraFields createFromParcel(Parcel in) { - return new ExtraFields(in); - } - - @Override - public ExtraFields[] newArray(int size) { - return new ExtraFields[size]; - } - }; - - public boolean containsCustomFields() { - return !getCustomProtectedFields().keySet().isEmpty(); - } - - public boolean containsCustomFieldsProtected() { - for (Map.Entry field : getCustomProtectedFields().entrySet()) { - if (field.getValue().isProtected()) - return true; - } - return false; - } - - public boolean containsCustomFieldsNotProtected() { - for (Map.Entry field : getCustomProtectedFields().entrySet()) { - if (!field.getValue().isProtected()) - return true; - } - return false; - } - - public String getProtectedStringValue(String key) { - ProtectedString value = fields.get(key); - if ( value == null ) return ""; - return value.toString(); - } - - public void putProtectedString(String key, ProtectedString protectedString) { - fields.put(key, protectedString); - } - - public void putProtectedString(String key, String value, boolean protect) { - ProtectedString ps = new ProtectedString(protect, value); - fields.put(key, ps); - } - - /** - * @return list of standard and customized fields - */ - public Map getListOfAllFields() { - return fields; - } - - public void doActionToAllCustomProtectedField(ActionProtected actionProtected) { - for (Map.Entry field : getCustomProtectedFields().entrySet()) { - actionProtected.doAction(field.getKey(), field.getValue()); - } - } - - public interface ActionProtected { - void doAction(String key, ProtectedString value); - } - - private Map getCustomProtectedFields() { - Map protectedFields = new HashMap<>(); - if (fields.size() > 0) { - for (Map.Entry pair : fields.entrySet()) { - String key = pair.getKey(); - if (isNotStandardField(key)) { - protectedFields.put(key, pair.getValue()); - } - } - } - return protectedFields; - } - - public void removeAllCustomFields() { - Iterator> iter = fields.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry pair = iter.next(); - if (isNotStandardField(pair.getKey())) { - iter.remove(); - } - } - } - - private static boolean isNotStandardField(String key) { - return !key.equals(STR_TITLE) && !key.equals(STR_USERNAME) - && !key.equals(STR_PASSWORD) && !key.equals(STR_URL) - && !key.equals(STR_NOTES); - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/MemoryProtectionConfig.java b/app/src/main/java/com/kunzisoft/keepass/database/MemoryProtectionConfig.java deleted file mode 100644 index 1f31f5276..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/MemoryProtectionConfig.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2018 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.database; - -import com.kunzisoft.keepass.database.element.PwDefsV4; - -public class MemoryProtectionConfig { - - public boolean protectTitle = false; - public boolean protectUserName = false; - public boolean protectPassword = false; - public boolean protectUrl = false; - public boolean protectNotes = false; - - public boolean autoEnableVisualHiding = false; - - public boolean isProtected(String field) { - if (field.equalsIgnoreCase(PwDefsV4.TITLE_FIELD)) return protectTitle; - if (field.equalsIgnoreCase(PwDefsV4.USERNAME_FIELD)) return protectUserName; - if (field.equalsIgnoreCase(PwDefsV4.PASSWORD_FIELD)) return protectPassword; - if (field.equalsIgnoreCase(PwDefsV4.URL_FIELD)) return protectUrl; - if (field.equalsIgnoreCase(PwDefsV4.NOTES_FIELD)) return protectNotes; - - return false; - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/NodeHandler.java b/app/src/main/java/com/kunzisoft/keepass/database/NodeHandler.kt similarity index 87% rename from app/src/main/java/com/kunzisoft/keepass/database/NodeHandler.java rename to app/src/main/java/com/kunzisoft/keepass/database/NodeHandler.kt index 55aed8d20..bf0a46f2c 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/NodeHandler.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/NodeHandler.kt @@ -17,14 +17,13 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database; +package com.kunzisoft.keepass.database /** "Delegate" class for operating on each group when traversing all of * them * @author bpellin - * */ -public abstract class NodeHandler { - public abstract boolean operate(T group); +abstract class NodeHandler { + abstract fun operate(node: T): Boolean } \ No newline at end of file diff --git a/app/src/main/java/com/kunzisoft/keepass/database/ObjectNameResource.java b/app/src/main/java/com/kunzisoft/keepass/database/ObjectNameResource.kt similarity index 84% rename from app/src/main/java/com/kunzisoft/keepass/database/ObjectNameResource.java rename to app/src/main/java/com/kunzisoft/keepass/database/ObjectNameResource.kt index 745d605e2..c2c0cb9f7 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/ObjectNameResource.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/ObjectNameResource.kt @@ -17,13 +17,13 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database; +package com.kunzisoft.keepass.database -import android.content.res.Resources; +import android.content.res.Resources /** * Interface to generify items with a name resource, that can be (for example) visible in a list */ -public interface ObjectNameResource { - String getName(Resources resources); +interface ObjectNameResource { + fun getName(resources: Resources): String } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/PwCompressionAlgorithm.java b/app/src/main/java/com/kunzisoft/keepass/database/PwCompressionAlgorithm.java deleted file mode 100644 index d12f15cc9..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/PwCompressionAlgorithm.java +++ /dev/null @@ -1,47 +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.database; - -public enum PwCompressionAlgorithm { - - None(0), - Gzip(1); - - // Note: We can get away with using int's to store unsigned 32-bit ints - // since we won't do arithmetic on these values (also unlikely to - // reach negative ids). - public final int id; - public static final int count = 2; - - private PwCompressionAlgorithm(int num) { - id = num; - } - - public static PwCompressionAlgorithm fromId(int num) { - for ( PwCompressionAlgorithm e : PwCompressionAlgorithm.values() ) { - if ( e.id == num ) { - return e; - } - } - - return null; - } - -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/CrsAlgorithm.java b/app/src/main/java/com/kunzisoft/keepass/database/PwCompressionAlgorithm.kt similarity index 58% rename from app/src/main/java/com/kunzisoft/keepass/database/CrsAlgorithm.java rename to app/src/main/java/com/kunzisoft/keepass/database/PwCompressionAlgorithm.kt index 81da5be75..a292d5e90 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/CrsAlgorithm.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/PwCompressionAlgorithm.kt @@ -17,30 +17,26 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database; +package com.kunzisoft.keepass.database -public enum CrsAlgorithm { - - Null(0), - ArcFourVariant(1), - Salsa20(2), - ChaCha20(3); +// Note: We can get away with using int's to store unsigned 32-bit ints +// since we won't do arithmetic on these values (also unlikely to +// reach negative ids). +enum class PwCompressionAlgorithm constructor(val id: Int) { - public static final int count = 4; - public final int id; - - private CrsAlgorithm(int num) { - id = num; - } + None(0), + Gzip(1); - public static CrsAlgorithm fromId(int num) { - for ( CrsAlgorithm e : CrsAlgorithm.values() ) { - if ( e.id == num ) { - return e; - } - } - - return null; - } + companion object { + + fun fromId(num: Int): PwCompressionAlgorithm? { + for (e in values()) { + if (e.id == num) { + return e + } + } + return null + } + } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.java b/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.java deleted file mode 100644 index d9d616bf0..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.java +++ /dev/null @@ -1,394 +0,0 @@ -/* - * Copyright 2018 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.database; - -import com.kunzisoft.keepass.database.element.EntryVersioned; -import com.kunzisoft.keepass.database.element.GroupVersioned; -import com.kunzisoft.keepass.database.element.NodeVersioned; - -import java.util.Comparator; - -public enum SortNodeEnum { - DB, TITLE, USERNAME, CREATION_TIME, LAST_MODIFY_TIME, LAST_ACCESS_TIME; - - public Comparator getNodeComparator(boolean ascending, boolean groupsBefore) { - switch (this) { - case DB: - return new NodeCreationComparator(ascending, groupsBefore); // TODO Sort - default: - case TITLE: - return new NodeTitleComparator(ascending, groupsBefore); - case USERNAME: - return new NodeCreationComparator(ascending, groupsBefore); // TODO Sort - case CREATION_TIME: - return new NodeCreationComparator(ascending, groupsBefore); - case LAST_MODIFY_TIME: - return new NodeLastModificationComparator(ascending, groupsBefore); - case LAST_ACCESS_TIME: - return new NodeLastAccessComparator(ascending, groupsBefore); - } - } - - private static abstract class NodeComparator implements Comparator { - boolean ascending; - boolean groupsBefore; - - NodeComparator(boolean ascending, boolean groupsBefore) { - this.ascending = ascending; - this.groupsBefore = groupsBefore; - } - - int compareWith(Comparator comparatorGroup, - Comparator comparatorEntry, - NodeVersioned object1, - NodeVersioned object2, - int resultOfNodeMethodCompare) { - if (object1.equals(object2)) - return 0; - - if (object1 instanceof GroupVersioned) { - if (object2 instanceof GroupVersioned) { - return comparatorGroup - .compare((GroupVersioned) object1, (GroupVersioned) object2); - } else if (object2 instanceof EntryVersioned) { - if(groupsBefore) - return -1; - else - return 1; - } else { - return -1; - } - } else if (object1 instanceof EntryVersioned) { - if(object2 instanceof EntryVersioned) { - return comparatorEntry - .compare((EntryVersioned) object1, (EntryVersioned) object2); - } else if (object2 instanceof GroupVersioned) { - if(groupsBefore) - return 1; - else - return -1; - } else { - return -1; - } - } - - // If same name, can be different - if (resultOfNodeMethodCompare == 0) - return object1.hashCode() - object2.hashCode(); - return resultOfNodeMethodCompare; - } - } - - /** - * Comparator of Node by Title, Groups first, Entries second - */ - public static class NodeTitleComparator extends NodeComparator { - - NodeTitleComparator(boolean ascending, boolean groupsBefore) { - super(ascending, groupsBefore); - } - - public int compare(NodeVersioned object1, NodeVersioned object2) { - - return compareWith( - new GroupNameComparator(ascending), - new EntryNameComparator(ascending), - object1, - object2, - object1.getTitle() - .compareToIgnoreCase(object2.getTitle())); - } - } - - /** - * Comparator of node by creation, Groups first, Entries second - */ - public static class NodeCreationComparator extends NodeComparator { - - - NodeCreationComparator(boolean ascending, boolean groupsBefore) { - super(ascending, groupsBefore); - } - - @Override - public int compare(NodeVersioned object1, NodeVersioned object2) { - - return compareWith( - new GroupCreationComparator(ascending), - new EntryCreationComparator(ascending), - object1, - object2, - object1.getCreationTime().getDate() - .compareTo(object2.getCreationTime().getDate())); - } - } - - /** - * Comparator of node by last modification, Groups first, Entries second - */ - public static class NodeLastModificationComparator extends NodeComparator { - - NodeLastModificationComparator(boolean ascending, boolean groupsBefore) { - super(ascending, groupsBefore); - } - - @Override - public int compare(NodeVersioned object1, NodeVersioned object2) { - - return compareWith( - new GroupLastModificationComparator(ascending), - new EntryLastModificationComparator(ascending), - object1, - object2, - object1.getLastModificationTime().getDate() - .compareTo(object2.getLastModificationTime().getDate())); - } - } - - /** - * Comparator of node by last access, Groups first, Entries second - */ - public static class NodeLastAccessComparator extends NodeComparator { - - NodeLastAccessComparator(boolean ascending, boolean groupsBefore) { - super(ascending, groupsBefore); - } - - @Override - public int compare(NodeVersioned object1, NodeVersioned object2) { - - return compareWith( - new GroupLastAccessComparator(ascending), - new EntryLastAccessComparator(ascending), - object1, - object2, - object1.getLastAccessTime().getDate() - .compareTo(object2.getLastAccessTime().getDate())); - } - } - - private static abstract class AscendingComparator implements Comparator { - - private boolean ascending; - - AscendingComparator(boolean ascending) { - this.ascending = ascending; - } - - int compareWithAscending(int basicCompareResult) { - // If descending, revert - if (!ascending) - return -basicCompareResult; - - return basicCompareResult; - } - } - - /** - * Group comparator by name - */ - public static class GroupNameComparator extends AscendingComparator { - - GroupNameComparator(boolean ascending) { - super(ascending); - } - - public int compare(GroupVersioned object1, GroupVersioned object2) { - if (object1.equals(object2)) - return 0; - - int groupNameComp = object1.getTitle().compareToIgnoreCase(object2.getTitle()); - // If same name, can be different - if (groupNameComp == 0) { - return object1.hashCode() - object2.hashCode(); - } - - return compareWithAscending(groupNameComp); - } - } - - /** - * Group comparator by name - */ - public static class GroupCreationComparator extends AscendingComparator { - - GroupCreationComparator(boolean ascending) { - super(ascending); - } - - public int compare(GroupVersioned object1, GroupVersioned object2) { - if (object1.equals(object2)) - return 0; - - int groupCreationComp = object1.getCreationTime().getDate() - .compareTo(object2.getCreationTime().getDate()); - // If same creation, can be different - if (groupCreationComp == 0) { - return object1.hashCode() - object2.hashCode(); - } - - return compareWithAscending(groupCreationComp); - } - } - - /** - * Group comparator by last modification - */ - public static class GroupLastModificationComparator extends AscendingComparator { - - GroupLastModificationComparator(boolean ascending) { - super(ascending); - } - - public int compare(GroupVersioned object1, GroupVersioned object2) { - if (object1.equals(object2)) - return 0; - - int groupLastModificationComp = object1.getLastModificationTime().getDate() - .compareTo(object2.getLastModificationTime().getDate()); - // If same creation, can be different - if (groupLastModificationComp == 0) { - return object1.hashCode() - object2.hashCode(); - } - - return compareWithAscending(groupLastModificationComp); - } - } - - /** - * Group comparator by last access - */ - public static class GroupLastAccessComparator extends AscendingComparator { - - GroupLastAccessComparator(boolean ascending) { - super(ascending); - } - - public int compare(GroupVersioned object1, GroupVersioned object2) { - if (object1.equals(object2)) - return 0; - - int groupLastAccessComp = object1.getLastAccessTime().getDate() - .compareTo(object2.getLastAccessTime().getDate()); - // If same creation, can be different - if (groupLastAccessComp == 0) { - return object1.hashCode() - object2.hashCode(); - } - - return compareWithAscending(groupLastAccessComp); - } - } - - /** - * Comparator of Entry by Name - */ - public static class EntryNameComparator extends AscendingComparator { - - EntryNameComparator(boolean ascending) { - super(ascending); - } - - public int compare(EntryVersioned object1, EntryVersioned object2) { - if (object1.equals(object2)) - return 0; - - int entryTitleComp = object1.getTitle().compareToIgnoreCase(object2.getTitle()); - // If same title, can be different - if (entryTitleComp == 0) { - return object1.hashCode() - object2.hashCode(); - } - - return compareWithAscending(entryTitleComp); - } - } - - /** - * Comparator of Entry by Creation - */ - public static class EntryCreationComparator extends AscendingComparator { - - EntryCreationComparator(boolean ascending) { - super(ascending); - } - - public int compare(EntryVersioned object1, EntryVersioned object2) { - if (object1.equals(object2)) - return 0; - - int entryCreationComp = object1.getCreationTime().getDate() - .compareTo(object2.getCreationTime().getDate()); - // If same creation, can be different - if (entryCreationComp == 0) { - return object1.hashCode() - object2.hashCode(); - } - - return compareWithAscending(entryCreationComp); - } - } - - /** - * Comparator of Entry by Last Modification - */ - public static class EntryLastModificationComparator extends AscendingComparator { - - EntryLastModificationComparator(boolean ascending) { - super(ascending); - } - - public int compare(EntryVersioned object1, EntryVersioned object2) { - if (object1.equals(object2)) - return 0; - - int entryLastModificationComp = object1.getLastModificationTime().getDate() - .compareTo(object2.getLastModificationTime().getDate()); - // If same creation, can be different - if (entryLastModificationComp == 0) { - return object1.hashCode() - object2.hashCode(); - } - - return compareWithAscending(entryLastModificationComp); - } - } - - /** - * Comparator of Entry by Last Access - */ - public static class EntryLastAccessComparator extends AscendingComparator { - - EntryLastAccessComparator(boolean ascending) { - super(ascending); - } - - public int compare(EntryVersioned object1, EntryVersioned object2) { - if (object1.equals(object2)) - return 0; - - int entryLastAccessComp = object1.getLastAccessTime().getDate() - .compareTo(object2.getLastAccessTime().getDate()); - // If same creation, can be different - if (entryLastAccessComp == 0) { - return object1.hashCode() - object2.hashCode(); - } - - return compareWithAscending(entryLastAccessComp); - } - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.kt b/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.kt new file mode 100644 index 000000000..5afd0ea7e --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/SortNodeEnum.kt @@ -0,0 +1,310 @@ +/* + * Copyright 2018 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.database + +import com.kunzisoft.keepass.database.element.EntryVersioned +import com.kunzisoft.keepass.database.element.GroupVersioned +import com.kunzisoft.keepass.database.element.NodeVersioned + +import java.util.Comparator + +enum class SortNodeEnum { + DB, TITLE, USERNAME, CREATION_TIME, LAST_MODIFY_TIME, LAST_ACCESS_TIME; + + fun getNodeComparator(ascending: Boolean, groupsBefore: Boolean): Comparator { + return when (this) { + DB -> NodeCreationComparator(ascending, groupsBefore) // TODO Sort + TITLE -> NodeTitleComparator(ascending, groupsBefore) + USERNAME -> NodeCreationComparator(ascending, groupsBefore) // TODO Sort + CREATION_TIME -> NodeCreationComparator(ascending, groupsBefore) + LAST_MODIFY_TIME -> NodeLastModificationComparator(ascending, groupsBefore) + LAST_ACCESS_TIME -> NodeLastAccessComparator(ascending, groupsBefore) + } + } + + abstract class NodeComparator internal constructor(internal var ascending: Boolean, private var groupsBefore: Boolean) : Comparator { + + internal fun compareWith(comparatorGroup: Comparator, + comparatorEntry: Comparator, + object1: NodeVersioned, + object2: NodeVersioned, + resultOfNodeMethodCompare: Int): Int { + if (object1 == object2) + return 0 + + if (object1 is GroupVersioned) { + return if (object2 is GroupVersioned) { + comparatorGroup + .compare(object1, object2) + } else if (object2 is EntryVersioned) { + if (groupsBefore) + -1 + else + 1 + } else { + -1 + } + } else if (object1 is EntryVersioned) { + return if (object2 is EntryVersioned) { + comparatorEntry + .compare(object1, object2) + } else if (object2 is GroupVersioned) { + if (groupsBefore) + 1 + else + -1 + } else { + -1 + } + } + + // If same name, can be different + return if (resultOfNodeMethodCompare == 0) object1.hashCode() - object2.hashCode() else resultOfNodeMethodCompare + } + } + + /** + * Comparator of Node by Title, Groups first, Entries second + */ + class NodeTitleComparator internal constructor(ascending: Boolean, groupsBefore: Boolean) : NodeComparator(ascending, groupsBefore) { + + override fun compare(object1: NodeVersioned, object2: NodeVersioned): Int { + + return compareWith( + GroupNameComparator(ascending), + EntryNameComparator(ascending), + object1, + object2, + object1.title + .compareTo(object2.title, ignoreCase = true)) + } + } + + /** + * Comparator of node by creation, Groups first, Entries second + */ + class NodeCreationComparator internal constructor(ascending: Boolean, groupsBefore: Boolean) : NodeComparator(ascending, groupsBefore) { + + override fun compare(object1: NodeVersioned, object2: NodeVersioned): Int { + + return compareWith( + GroupCreationComparator(ascending), + EntryCreationComparator(ascending), + object1, + object2, + object1.creationTime.date + .compareTo(object2.creationTime.date)) + } + } + + /** + * Comparator of node by last modification, Groups first, Entries second + */ + class NodeLastModificationComparator internal constructor(ascending: Boolean, groupsBefore: Boolean) : NodeComparator(ascending, groupsBefore) { + + override fun compare(object1: NodeVersioned, object2: NodeVersioned): Int { + + return compareWith( + GroupLastModificationComparator(ascending), + EntryLastModificationComparator(ascending), + object1, + object2, + object1.lastModificationTime.date + .compareTo(object2.lastModificationTime.date)) + } + } + + /** + * Comparator of node by last access, Groups first, Entries second + */ + class NodeLastAccessComparator internal constructor(ascending: Boolean, groupsBefore: Boolean) : NodeComparator(ascending, groupsBefore) { + + override fun compare(object1: NodeVersioned, object2: NodeVersioned): Int { + + return compareWith( + GroupLastAccessComparator(ascending), + EntryLastAccessComparator(ascending), + object1, + object2, + object1.lastAccessTime.date + .compareTo(object2.lastAccessTime.date)) + } + } + + abstract class AscendingComparator internal constructor(private val ascending: Boolean) : Comparator { + + internal fun compareWithAscending(basicCompareResult: Int): Int { + // If descending, revert + return if (!ascending) -basicCompareResult else basicCompareResult + + } + } + + /** + * Group comparator by name + */ + class GroupNameComparator internal constructor(ascending: Boolean) : AscendingComparator(ascending) { + + override fun compare(object1: GroupVersioned, object2: GroupVersioned): Int { + if (object1 == object2) + return 0 + + val groupNameComp = object1.title.compareTo(object2.title, ignoreCase = true) + // If same name, can be different + return if (groupNameComp == 0) { + object1.hashCode() - object2.hashCode() + } else compareWithAscending(groupNameComp) + + } + } + + /** + * Group comparator by name + */ + class GroupCreationComparator internal constructor(ascending: Boolean) : AscendingComparator(ascending) { + + override fun compare(object1: GroupVersioned, object2: GroupVersioned): Int { + if (object1 == object2) + return 0 + + val groupCreationComp = object1.creationTime.date + .compareTo(object2.creationTime.date) + // If same creation, can be different + return if (groupCreationComp == 0) { + object1.hashCode() - object2.hashCode() + } else compareWithAscending(groupCreationComp) + + } + } + + /** + * Group comparator by last modification + */ + class GroupLastModificationComparator internal constructor(ascending: Boolean) : AscendingComparator(ascending) { + + override fun compare(object1: GroupVersioned, object2: GroupVersioned): Int { + if (object1 == object2) + return 0 + + val groupLastModificationComp = object1.lastModificationTime.date + .compareTo(object2.lastModificationTime.date) + // If same creation, can be different + return if (groupLastModificationComp == 0) { + object1.hashCode() - object2.hashCode() + } else compareWithAscending(groupLastModificationComp) + + } + } + + /** + * Group comparator by last access + */ + class GroupLastAccessComparator internal constructor(ascending: Boolean) : AscendingComparator(ascending) { + + override fun compare(object1: GroupVersioned, object2: GroupVersioned): Int { + if (object1 == object2) + return 0 + + val groupLastAccessComp = object1.lastAccessTime.date + .compareTo(object2.lastAccessTime.date) + // If same creation, can be different + return if (groupLastAccessComp == 0) { + object1.hashCode() - object2.hashCode() + } else compareWithAscending(groupLastAccessComp) + + } + } + + /** + * Comparator of Entry by Name + */ + class EntryNameComparator internal constructor(ascending: Boolean) : AscendingComparator(ascending) { + + override fun compare(object1: EntryVersioned, object2: EntryVersioned): Int { + if (object1 == object2) + return 0 + + val entryTitleComp = object1.title.compareTo(object2.title, ignoreCase = true) + // If same title, can be different + return if (entryTitleComp == 0) { + object1.hashCode() - object2.hashCode() + } else compareWithAscending(entryTitleComp) + + } + } + + /** + * Comparator of Entry by Creation + */ + class EntryCreationComparator internal constructor(ascending: Boolean) : AscendingComparator(ascending) { + + override fun compare(object1: EntryVersioned, object2: EntryVersioned): Int { + if (object1 == object2) + return 0 + + val entryCreationComp = object1.creationTime.date + .compareTo(object2.creationTime.date) + // If same creation, can be different + return if (entryCreationComp == 0) { + object1.hashCode() - object2.hashCode() + } else compareWithAscending(entryCreationComp) + + } + } + + /** + * Comparator of Entry by Last Modification + */ + class EntryLastModificationComparator internal constructor(ascending: Boolean) : AscendingComparator(ascending) { + + override fun compare(object1: EntryVersioned, object2: EntryVersioned): Int { + if (object1 == object2) + return 0 + + val entryLastModificationComp = object1.lastModificationTime.date + .compareTo(object2.lastModificationTime.date) + // If same creation, can be different + return if (entryLastModificationComp == 0) { + object1.hashCode() - object2.hashCode() + } else compareWithAscending(entryLastModificationComp) + + } + } + + /** + * Comparator of Entry by Last Access + */ + class EntryLastAccessComparator internal constructor(ascending: Boolean) : AscendingComparator(ascending) { + + override fun compare(object1: EntryVersioned, object2: EntryVersioned): Int { + if (object1 == object2) + return 0 + + val entryLastAccessComp = object1.lastAccessTime.date + .compareTo(object2.lastAccessTime.date) + // If same creation, can be different + return if (entryLastAccessComp == 0) { + object1.hashCode() - object2.hashCode() + } else compareWithAscending(entryLastAccessComp) + + } + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.java b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.java deleted file mode 100644 index ddc70d1d4..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.kunzisoft.keepass.database.cursor; - -import android.database.MatrixCursor; -import android.provider.BaseColumns; - -import com.kunzisoft.keepass.database.element.*; - -import java.util.UUID; - -public abstract class EntryCursor extends MatrixCursor { - - protected long entryId; - public static final String _ID = BaseColumns._ID; - public static final String COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS = "UUID_most_significant_bits"; - public static final String COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS = "UUID_least_significant_bits"; - public static final String COLUMN_INDEX_TITLE = "title"; - public static final String COLUMN_INDEX_ICON_STANDARD = "icon_standard"; - public static final String COLUMN_INDEX_ICON_CUSTOM_UUID_MOST_SIGNIFICANT_BITS = "icon_custom_UUID_most_significant_bits"; - public static final String COLUMN_INDEX_ICON_CUSTOM_UUID_LEAST_SIGNIFICANT_BITS = "icon_custom_UUID_least_significant_bits"; - public static final String COLUMN_INDEX_USERNAME = "username"; - public static final String COLUMN_INDEX_PASSWORD = "password"; - public static final String COLUMN_INDEX_URL = "URL"; - public static final String COLUMN_INDEX_NOTES = "notes"; - - public EntryCursor() { - super(new String[]{ _ID, - COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS, - COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS, - COLUMN_INDEX_TITLE, - COLUMN_INDEX_ICON_STANDARD, - COLUMN_INDEX_ICON_CUSTOM_UUID_MOST_SIGNIFICANT_BITS, - COLUMN_INDEX_ICON_CUSTOM_UUID_LEAST_SIGNIFICANT_BITS, - COLUMN_INDEX_USERNAME, - COLUMN_INDEX_PASSWORD, - COLUMN_INDEX_URL, - COLUMN_INDEX_NOTES}); - entryId = 0; - } - - public abstract void addEntry(PwEntryV entry); - - public void populateEntry(PwEntryV pwEntry, PwIconFactory iconFactory) { - pwEntry.setNodeId(new PwNodeIdUUID( - new UUID(getLong(getColumnIndex(EntryCursor.COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS)), - getLong(getColumnIndex(EntryCursor.COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS))))); - pwEntry.setTitle(getString(getColumnIndex(EntryCursor.COLUMN_INDEX_TITLE))); - - PwIconStandard iconStandard = iconFactory.getIcon(getInt(getColumnIndex(EntryCursor.COLUMN_INDEX_ICON_STANDARD))); - pwEntry.setIcon(iconStandard); - - pwEntry.setUsername(getString(getColumnIndex(EntryCursor.COLUMN_INDEX_USERNAME))); - pwEntry.setPassword(getString(getColumnIndex(EntryCursor.COLUMN_INDEX_PASSWORD))); - pwEntry.setUrl(getString(getColumnIndex(EntryCursor.COLUMN_INDEX_URL))); - pwEntry.setNotes(getString(getColumnIndex(EntryCursor.COLUMN_INDEX_NOTES))); - } - -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.kt b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.kt new file mode 100644 index 000000000..67f89fd51 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursor.kt @@ -0,0 +1,57 @@ +package com.kunzisoft.keepass.database.cursor + +import android.database.MatrixCursor +import android.provider.BaseColumns + +import com.kunzisoft.keepass.database.element.* + +import java.util.UUID + +abstract class EntryCursor> : MatrixCursor(arrayOf( + _ID, + COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS, + COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS, + COLUMN_INDEX_TITLE, + COLUMN_INDEX_ICON_STANDARD, + COLUMN_INDEX_ICON_CUSTOM_UUID_MOST_SIGNIFICANT_BITS, + COLUMN_INDEX_ICON_CUSTOM_UUID_LEAST_SIGNIFICANT_BITS, + COLUMN_INDEX_USERNAME, + COLUMN_INDEX_PASSWORD, + COLUMN_INDEX_URL, + COLUMN_INDEX_NOTES + )) { + + protected var entryId: Long = 0 + + abstract fun addEntry(entry: PwEntryV) + + open fun populateEntry(pwEntry: PwEntryV, iconFactory: PwIconFactory) { + pwEntry.nodeId = PwNodeIdUUID( + UUID(getLong(getColumnIndex(COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS)), + getLong(getColumnIndex(COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS)))) + pwEntry.title = getString(getColumnIndex(COLUMN_INDEX_TITLE)) + + val iconStandard = iconFactory.getIcon(getInt(getColumnIndex(COLUMN_INDEX_ICON_STANDARD))) + pwEntry.icon = iconStandard + + pwEntry.username = getString(getColumnIndex(COLUMN_INDEX_USERNAME)) + pwEntry.password = getString(getColumnIndex(COLUMN_INDEX_PASSWORD)) + pwEntry.url = getString(getColumnIndex(COLUMN_INDEX_URL)) + pwEntry.notes = getString(getColumnIndex(COLUMN_INDEX_NOTES)) + } + + companion object { + const val _ID = BaseColumns._ID + const val COLUMN_INDEX_UUID_MOST_SIGNIFICANT_BITS = "UUID_most_significant_bits" + const val COLUMN_INDEX_UUID_LEAST_SIGNIFICANT_BITS = "UUID_least_significant_bits" + const val COLUMN_INDEX_TITLE = "title" + const val COLUMN_INDEX_ICON_STANDARD = "icon_standard" + const val COLUMN_INDEX_ICON_CUSTOM_UUID_MOST_SIGNIFICANT_BITS = "icon_custom_UUID_most_significant_bits" + const val COLUMN_INDEX_ICON_CUSTOM_UUID_LEAST_SIGNIFICANT_BITS = "icon_custom_UUID_least_significant_bits" + const val COLUMN_INDEX_USERNAME = "username" + const val COLUMN_INDEX_PASSWORD = "password" + const val COLUMN_INDEX_URL = "URL" + const val COLUMN_INDEX_NOTES = "notes" + } + +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV3.java b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV3.java deleted file mode 100644 index 839ed1c0a..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV3.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.kunzisoft.keepass.database.cursor; - -import com.kunzisoft.keepass.database.element.PwDatabase; -import com.kunzisoft.keepass.database.element.PwEntryV3; - -public class EntryCursorV3 extends EntryCursor { - - public void addEntry(PwEntryV3 entry) { - addRow(new Object[] {entryId, - entry.getId().getMostSignificantBits(), - entry.getId().getLeastSignificantBits(), - entry.getTitle(), - entry.getIcon().getIconId(), - PwDatabase.UUID_ZERO.getMostSignificantBits(), - PwDatabase.UUID_ZERO.getLeastSignificantBits(), - entry.getUsername(), - entry.getPassword(), - entry.getUrl(), - entry.getNotes()}); - entryId++; - } - -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV3.kt new file mode 100644 index 000000000..9ef52fbe5 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV3.kt @@ -0,0 +1,25 @@ +package com.kunzisoft.keepass.database.cursor + +import com.kunzisoft.keepass.database.element.PwDatabase +import com.kunzisoft.keepass.database.element.PwEntryV3 + +class EntryCursorV3 : EntryCursor() { + + override fun addEntry(entry: PwEntryV3) { + addRow(arrayOf( + entryId, + entry.id.mostSignificantBits, + entry.id.leastSignificantBits, + entry.title, + entry.icon.iconId, + PwDatabase.UUID_ZERO.mostSignificantBits, + PwDatabase.UUID_ZERO.leastSignificantBits, + entry.username, + entry.password, + entry.url, + entry.notes + )) + entryId++ + } + +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV4.java b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV4.java deleted file mode 100644 index e2eb4033c..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV4.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.kunzisoft.keepass.database.cursor; - -import com.kunzisoft.keepass.database.element.PwEntryV4; -import com.kunzisoft.keepass.database.element.PwIconCustom; -import com.kunzisoft.keepass.database.element.PwIconFactory; - -import java.util.UUID; - -public class EntryCursorV4 extends EntryCursor { - - private ExtraFieldCursor extraFieldCursor; - - public EntryCursorV4() { - super(); - extraFieldCursor = new ExtraFieldCursor(); - } - - public void addEntry(PwEntryV4 entry) { - addRow(new Object[] {entryId, - entry.getId().getMostSignificantBits(), - entry.getId().getLeastSignificantBits(), - entry.getTitle(), - entry.getIcon().getIconId(), - entry.getIconCustom().getUuid().getMostSignificantBits(), - entry.getIconCustom().getUuid().getLeastSignificantBits(), - entry.getUsername(), - entry.getPassword(), - entry.getUrl(), - entry.getNotes()}); - - entry.getFields().doActionToAllCustomProtectedField((key, value) -> { - extraFieldCursor.addExtraField(entryId, key, value); - }); - - entryId++; - } - - public void populateEntry(PwEntryV4 pwEntry, PwIconFactory iconFactory) { - super.populateEntry(pwEntry, iconFactory); - - // Retrieve custom icon - PwIconCustom iconCustom = iconFactory.getIcon( - new UUID(getLong(getColumnIndex(EntryCursor.COLUMN_INDEX_ICON_CUSTOM_UUID_MOST_SIGNIFICANT_BITS)), - getLong(getColumnIndex(EntryCursor.COLUMN_INDEX_ICON_CUSTOM_UUID_LEAST_SIGNIFICANT_BITS)))); - pwEntry.setIconCustom(iconCustom); - - // Retrieve extra fields - if (extraFieldCursor.moveToFirst()) { - while (!extraFieldCursor.isAfterLast()) { - // Add a new extra field only if entryId is the one we want - if (extraFieldCursor.getLong(extraFieldCursor.getColumnIndex(ExtraFieldCursor.FOREIGN_KEY_ENTRY_ID)) - == getLong(getColumnIndex(EntryCursor._ID))) { - extraFieldCursor.populateExtraFieldInEntry(pwEntry); - } - extraFieldCursor.moveToNext(); - } - } - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV4.kt new file mode 100644 index 000000000..370cc207e --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/cursor/EntryCursorV4.kt @@ -0,0 +1,56 @@ +package com.kunzisoft.keepass.database.cursor + +import com.kunzisoft.keepass.database.element.PwEntryV4 +import com.kunzisoft.keepass.database.element.PwIconFactory + +import java.util.UUID + +class EntryCursorV4 : EntryCursor() { + + private val extraFieldCursor: ExtraFieldCursor = ExtraFieldCursor() + + override fun addEntry(entry: PwEntryV4) { + addRow(arrayOf( + entryId, + entry.id.mostSignificantBits, + entry.id.leastSignificantBits, + entry.title, + entry.icon.iconId, + entry.iconCustom.uuid.mostSignificantBits, + entry.iconCustom.uuid.leastSignificantBits, + entry.username, + entry.password, + entry.url, + entry.notes + )) + + entry.fields.doActionToAllCustomProtectedField { key, value -> + extraFieldCursor.addExtraField(entryId, key, value) + } + + entryId++ + } + + override fun populateEntry(pwEntry: PwEntryV4, iconFactory: PwIconFactory) { + super.populateEntry(pwEntry, iconFactory) + + // Retrieve custom icon + val iconCustom = iconFactory.getIcon( + UUID(getLong(getColumnIndex(COLUMN_INDEX_ICON_CUSTOM_UUID_MOST_SIGNIFICANT_BITS)), + getLong(getColumnIndex(COLUMN_INDEX_ICON_CUSTOM_UUID_LEAST_SIGNIFICANT_BITS)))) + pwEntry.iconCustom = iconCustom + + // Retrieve extra fields + if (extraFieldCursor.moveToFirst()) { + while (!extraFieldCursor.isAfterLast) { + // Add a new extra field only if entryId is the one we want + if (extraFieldCursor.getLong(extraFieldCursor + .getColumnIndex(ExtraFieldCursor.FOREIGN_KEY_ENTRY_ID)) + == getLong(getColumnIndex(_ID))) { + extraFieldCursor.populateExtraFieldInEntry(pwEntry) + } + extraFieldCursor.moveToNext() + } + } + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.java b/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.java deleted file mode 100644 index c5159968a..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.kunzisoft.keepass.database.cursor; - -import android.database.MatrixCursor; -import android.provider.BaseColumns; - -import com.kunzisoft.keepass.database.element.PwEntryV4; -import com.kunzisoft.keepass.database.security.ProtectedString; - -public class ExtraFieldCursor extends MatrixCursor { - - private long fieldId; - public static final String _ID = BaseColumns._ID; - public static final String FOREIGN_KEY_ENTRY_ID = "entry_id"; - public static final String COLUMN_LABEL = "label"; - public static final String COLUMN_PROTECTION = "protection"; - public static final String COLUMN_VALUE = "value"; - - public ExtraFieldCursor() { - super(new String[]{ _ID, - FOREIGN_KEY_ENTRY_ID, - COLUMN_LABEL, - COLUMN_PROTECTION, - COLUMN_VALUE}); - fieldId = 0; - } - - public synchronized void addExtraField(long entryId, String label, ProtectedString value) { - addRow(new Object[] {fieldId, - entryId, - label, - (value.isProtected()) ? 1 : 0, - value.toString()}); - fieldId++; - } - - public void populateExtraFieldInEntry(PwEntryV4 pwEntry) { - - pwEntry.addExtraField(getString(getColumnIndex(ExtraFieldCursor.COLUMN_LABEL)), - new ProtectedString((getInt(getColumnIndex(ExtraFieldCursor.COLUMN_PROTECTION)) > 0), - getString(getColumnIndex(ExtraFieldCursor.COLUMN_VALUE)))); - - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.kt b/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.kt new file mode 100644 index 000000000..a79321a61 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/cursor/ExtraFieldCursor.kt @@ -0,0 +1,38 @@ +package com.kunzisoft.keepass.database.cursor + +import android.database.MatrixCursor +import android.provider.BaseColumns + +import com.kunzisoft.keepass.database.element.PwEntryV4 +import com.kunzisoft.keepass.database.security.ProtectedString + +class ExtraFieldCursor : MatrixCursor(arrayOf( + _ID, + FOREIGN_KEY_ENTRY_ID, + COLUMN_LABEL, + COLUMN_PROTECTION, + COLUMN_VALUE + )) { + + private var fieldId: Long = 0 + + @Synchronized + fun addExtraField(entryId: Long, label: String, value: ProtectedString) { + addRow(arrayOf(fieldId, entryId, label, if (value.isProtected) 1 else 0, value.toString())) + fieldId++ + } + + fun populateExtraFieldInEntry(pwEntry: PwEntryV4) { + pwEntry.addExtraField(getString(getColumnIndex(COLUMN_LABEL)), + ProtectedString(getInt(getColumnIndex(COLUMN_PROTECTION)) > 0, + getString(getColumnIndex(COLUMN_VALUE)))) + } + + companion object { + const val _ID = BaseColumns._ID + const val FOREIGN_KEY_ENTRY_ID = "entry_id" + const val COLUMN_LABEL = "label" + const val COLUMN_PROTECTION = "protection" + const val COLUMN_VALUE = "value" + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/AutoType.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/AutoType.kt new file mode 100644 index 000000000..3479f759f --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/AutoType.kt @@ -0,0 +1,87 @@ +/* + * Copyright 2018 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.database.element + +import android.os.Parcel +import android.os.Parcelable + +import com.kunzisoft.keepass.utils.MemUtil + +import java.util.HashMap + +class AutoType : Parcelable { + + var enabled = true + var obfuscationOptions = OBF_OPT_NONE + var defaultSequence = "" + private var windowSeqPairs = HashMap() + + constructor() + + constructor(autoType: AutoType) { + this.enabled = autoType.enabled + this.obfuscationOptions = autoType.obfuscationOptions + this.defaultSequence = autoType.defaultSequence + for ((key, value) in autoType.windowSeqPairs) { + this.windowSeqPairs[key] = value + } + } + + constructor(parcel: Parcel) { + this.enabled = parcel.readByte().toInt() != 0 + this.obfuscationOptions = parcel.readLong() + this.defaultSequence = parcel.readString() + this.windowSeqPairs = MemUtil.readStringParcelableMap(parcel) + } + + override fun describeContents(): Int { + return 0 + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + dest.writeByte((if (enabled) 1 else 0).toByte()) + dest.writeLong(obfuscationOptions) + dest.writeString(defaultSequence) + MemUtil.writeStringParcelableMap(dest, windowSeqPairs) + } + + fun put(key: String, value: String) { + windowSeqPairs[key] = value + } + + fun entrySet(): Set> { + return windowSeqPairs.entries + } + + companion object { + private const val OBF_OPT_NONE: Long = 0 + + @JvmField + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): AutoType { + return AutoType(parcel) + } + + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } + } + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/BinaryPool.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/BinaryPool.kt new file mode 100644 index 000000000..5a90d01e8 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/BinaryPool.kt @@ -0,0 +1,70 @@ +/* + * 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.database.element + +import com.kunzisoft.keepass.database.security.ProtectedBinary +import java.util.HashMap +import kotlin.collections.Map.Entry + +class BinaryPool { + // TODO SparseArray + private val pool = HashMap() + + operator fun get(key: Int): ProtectedBinary? { + return pool[key] + } + + fun put(key: Int, value: ProtectedBinary) { + pool[key] = value + } + + fun entrySet(): Set> { + return pool.entries + } + + fun clear() { + for ((_, value) in pool) + value.clear() + pool.clear() + } + + fun binaries(): Collection { + return pool.values + } + + fun add(protectedBinary: ProtectedBinary) { + if (findKey(protectedBinary) != -1) return + pool[findUnusedKey()] = protectedBinary + } + + fun findUnusedKey(): Int { + 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 + } + return -1 + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt index 0bd1b7742..86e1561c1 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/Database.kt @@ -331,8 +331,12 @@ class Database { if (searchResult != null) { for (entry in searchResult.getChildEntries()) { if (!entry.isMetaStream) { // TODO metastream - cursorV3?.addEntry(entry.pwEntryV3) - cursorV4?.addEntry(entry.pwEntryV4) + entry.pwEntryV3?.let { + cursorV3?.addEntry(it) + } + entry.pwEntryV4?.let { + cursorV4?.addEntry(it) + } } } } @@ -341,14 +345,22 @@ class Database { } fun getEntryFrom(cursor: Cursor): EntryVersioned? { - val iconFactory = pwDatabaseV3?.getIconFactory() ?: pwDatabaseV4?.getIconFactory() + val iconFactory = pwDatabaseV3?.getIconFactory() ?: pwDatabaseV4?.getIconFactory() ?: PwIconFactory() val entry = createEntry() // TODO invert field reference manager entry?.let { entryVersioned -> startManageEntry(entryVersioned) - pwDatabaseV3?.let { (cursor as EntryCursorV3).populateEntry(entryVersioned.pwEntryV3, iconFactory) } - pwDatabaseV4?.let { (cursor as EntryCursorV4).populateEntry(entryVersioned.pwEntryV4, iconFactory) } + pwDatabaseV3?.let { + entryVersioned.pwEntryV3?.let { entryV3 -> + (cursor as EntryCursorV3).populateEntry(entryV3, iconFactory) + } + } + pwDatabaseV4?.let { + entryVersioned.pwEntryV4?.let { entryV4 -> + (cursor as EntryCursorV4).populateEntry(entryV4, iconFactory) + } + } stopManageEntry(entryVersioned) } @@ -416,8 +428,7 @@ class Database { fun closeAndClear(context: Context) { drawFactory.clearCache() // Delete the cache of the database if present - if (pwDatabaseV4 != null) - pwDatabaseV4!!.clearCache() + pwDatabaseV4?.clearCache() // In all cases, delete all the files in the temp dir try { FileUtils.cleanDirectory(context.filesDir) @@ -617,15 +628,15 @@ class Database { fun deleteGroup(group: GroupVersioned) { group.doForEachChildAndForIt( object : NodeHandler() { - override fun operate(entry: EntryVersioned): Boolean { - deleteEntry(entry) + override fun operate(node: EntryVersioned): Boolean { + deleteEntry(node) return true } }, object : NodeHandler() { - override fun operate(group: GroupVersioned): Boolean { - group.parent?.let { - removeGroupFrom(group, it) + override fun operate(node: GroupVersioned): Boolean { + node.parent?.let { + removeGroupFrom(node, it) } return true } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersioned.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersioned.kt index 1c6fef28c..affea85f5 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersioned.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/EntryVersioned.kt @@ -2,7 +2,6 @@ package com.kunzisoft.keepass.database.element import android.os.Parcel import android.os.Parcelable -import com.kunzisoft.keepass.database.ExtraFields import com.kunzisoft.keepass.database.security.ProtectedString import java.util.* import kotlin.collections.ArrayList diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/ExtraFields.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/ExtraFields.kt new file mode 100644 index 000000000..e833d6c6d --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/ExtraFields.kt @@ -0,0 +1,152 @@ +/* + * Copyright 2018 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.database.element + +import android.os.Parcel +import android.os.Parcelable + +import com.kunzisoft.keepass.database.security.ProtectedString +import com.kunzisoft.keepass.utils.MemUtil + +import java.util.HashMap + +import com.kunzisoft.keepass.database.element.PwEntryV4.Companion.STR_TITLE +import com.kunzisoft.keepass.database.element.PwEntryV4.Companion.STR_USERNAME +import com.kunzisoft.keepass.database.element.PwEntryV4.Companion.STR_PASSWORD +import com.kunzisoft.keepass.database.element.PwEntryV4.Companion.STR_URL +import com.kunzisoft.keepass.database.element.PwEntryV4.Companion.STR_NOTES + +class ExtraFields : Parcelable { + + private var fields: MutableMap = HashMap() + + /** + * @return list of standard and customized fields + */ + val listOfAllFields: Map + get() = fields + + private val customProtectedFields: Map + get() { + val protectedFields = HashMap() + if (fields.isNotEmpty()) { + for ((key, value) in fields) { + if (isNotStandardField(key)) { + protectedFields[key] = value + } + } + } + return protectedFields + } + + constructor() + + constructor(extraFields: ExtraFields) : this() { + for ((key, value) in extraFields.fields) { + fields[key] = ProtectedString(value) + } + } + + constructor(parcel: Parcel) { + fields = MemUtil.readStringParcelableMap(parcel, ProtectedString::class.java) + } + + override fun describeContents(): Int { + return 0 + } + + override fun writeToParcel(dest: Parcel, flags: Int) { + MemUtil.writeStringParcelableMap(dest, flags, fields) + } + + fun containsCustomFields(): Boolean { + return customProtectedFields.keys.isNotEmpty() + } + + fun containsCustomFieldsProtected(): Boolean { + for ((_, value) in customProtectedFields) { + if (value.isProtected) + return true + } + return false + } + + fun containsCustomFieldsNotProtected(): Boolean { + for ((_, value) in customProtectedFields) { + if (!value.isProtected) + return true + } + return false + } + + fun getProtectedStringValue(key: String): String { + val value = fields[key] ?: return "" + return value.toString() + } + + fun putProtectedString(key: String, protectedString: ProtectedString) { + fields[key] = protectedString + } + + fun putProtectedString(key: String, value: String, protect: Boolean) { + val ps = ProtectedString(protect, value) + fields[key] = ps + } + + fun doActionToAllCustomProtectedField(actionProtected: (key: String, value: ProtectedString)-> Unit) { + for ((key, value) in customProtectedFields) { + actionProtected.invoke(key, value) + } + } + + interface ActionProtected { + fun doAction(key: String, value: ProtectedString) + } + + fun removeAllCustomFields() { + val iterator = fields.entries.iterator() + while (iterator.hasNext()) { + val pair = iterator.next() + if (isNotStandardField(pair.key)) { + iterator.remove() + } + } + } + + companion object { + + @JvmField + val CREATOR: Parcelable.Creator = object : Parcelable.Creator { + override fun createFromParcel(parcel: Parcel): ExtraFields { + return ExtraFields(parcel) + } + + override fun newArray(size: Int): Array { + return arrayOfNulls(size) + } + } + + private fun isNotStandardField(key: String): Boolean { + return (key != STR_TITLE && key != STR_USERNAME + && key != STR_PASSWORD && key != STR_URL + && key != STR_NOTES) + } + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/MemoryProtectionConfig.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/MemoryProtectionConfig.kt new file mode 100644 index 000000000..1e4dbda13 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/MemoryProtectionConfig.kt @@ -0,0 +1,48 @@ +/* + * Copyright 2018 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.database.element + +class MemoryProtectionConfig { + + var protectTitle = false + var protectUserName = false + var protectPassword = false + var protectUrl = false + var protectNotes = false + + var autoEnableVisualHiding = false + + fun isProtected(field: String): Boolean { + if (field.equals(ProtectDefinition.TITLE_FIELD, ignoreCase = true)) return protectTitle + if (field.equals(ProtectDefinition.USERNAME_FIELD, ignoreCase = true)) return protectUserName + if (field.equals(ProtectDefinition.PASSWORD_FIELD, ignoreCase = true)) return protectPassword + if (field.equals(ProtectDefinition.URL_FIELD, ignoreCase = true)) return protectUrl + return if (field.equals(ProtectDefinition.NOTES_FIELD, ignoreCase = true)) protectNotes else false + + } + + object ProtectDefinition { + const val TITLE_FIELD = "Title" + const val USERNAME_FIELD = "UserName" + const val PASSWORD_FIELD = "Password" + const val URL_FIELD = "URL" + const val NOTES_FIELD = "Notes" + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV3.java b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV3.java index 8399b0fb4..eef5ea7a9 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV3.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDatabaseV3.java @@ -232,16 +232,6 @@ public class PwDatabaseV3 extends PwDatabase { return new PwEntryV3(); } - // TODO: This could still be refactored cleaner - public void copyEncrypted(byte[] buf, int offset, int size) { - // No-op - } - - // TODO: This could still be refactored cleaner - public void copyHeader(PwDbHeaderV3 header) { - // No-op - } - @Override public boolean isBackup(PwGroupV3 group) { while (group != null) { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDefsV4.java b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeader.kt similarity index 68% rename from app/src/main/java/com/kunzisoft/keepass/database/element/PwDefsV4.java rename to app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeader.kt index 0ac29a07f..0a2148c1e 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDefsV4.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeader.kt @@ -17,18 +17,23 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database.element; +package com.kunzisoft.keepass.database.element -public class PwDefsV4 { +abstract class PwDbHeader { - public static final String TITLE_FIELD = "Title"; + /** + * Seed that gets hashed with the userkey to form the final key + */ + var masterSeed: ByteArray? = null - public static final String USERNAME_FIELD = "UserName"; + /** + * IV used for content encryption + */ + var encryptionIV = ByteArray(16) - public static final String PASSWORD_FIELD = "Password"; + companion object { - public static final String URL_FIELD = "URL"; - - public static final String NOTES_FIELD = "Notes"; + const val PWM_DBSIG_1 = -0x655d26fd + } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeaderV3.java b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeaderV3.java index 6bdfdf1d8..3f57f5bc7 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeaderV3.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeaderV3.java @@ -65,8 +65,10 @@ public class PwDbHeaderV3 extends PwDbHeader { /** Size of byte buffer needed to hold this struct. */ public static final int BUF_SIZE = 124; - /** Used for the dwKeyEncRounds AES transformations */ - public byte transformSeed[] = new byte[32]; + /** + * Used for the dwKeyEncRounds AES transformations + */ + public byte[] transformSeed = new byte[32]; public int signature1; // = PWM_DBSIG_1 public int signature2; // = DBSIG_2 @@ -78,8 +80,10 @@ public class PwDbHeaderV3 extends PwDbHeader { /** Number of entries in the database */ public int numEntries; - /** SHA-256 hash of the database, used for integrity check */ - public byte contentsHash[] = new byte[32]; + /** + * SHA-256 hash of the database, used for integrity check + */ + public byte[] contentsHash = new byte[32]; public int numKeyEncRounds; @@ -88,14 +92,14 @@ public class PwDbHeaderV3 extends PwDbHeader { * @param buf * @throws IOException */ - public void loadFromFile( byte buf[], int offset ) throws IOException { - signature1 = LEDataInputStream.readInt( buf, offset + 0 ); + public void loadFromFile(byte[] buf, int offset ) throws IOException { + signature1 = LEDataInputStream.readInt( buf, offset); signature2 = LEDataInputStream.readInt( buf, offset + 4 ); flags = LEDataInputStream.readInt( buf, offset + 8 ); version = LEDataInputStream.readInt( buf, offset + 12 ); - System.arraycopy( buf, offset + 16, masterSeed, 0, 16 ); - System.arraycopy( buf, offset + 32, encryptionIV, 0, 16 ); + System.arraycopy( buf, offset + 16, getMasterSeed(), 0, 16 ); + System.arraycopy( buf, offset + 32, getEncryptionIV(), 0, 16 ); numGroups = LEDataInputStream.readInt( buf, offset + 48 ); numEntries = LEDataInputStream.readInt( buf, offset + 52 ); @@ -111,11 +115,11 @@ public class PwDbHeaderV3 extends PwDbHeader { } public PwDbHeaderV3() { - masterSeed = new byte[16]; + setMasterSeed(new byte[16]); } public static boolean matchesHeader(int sig1, int sig2) { - return (sig1 == PWM_DBSIG_1) && (sig2 == DBSIG_2); + return (sig1 == PwDbHeader.PWM_DBSIG_1) && (sig2 == DBSIG_2); } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeaderV4.java b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeaderV4.java index f11765814..e60a8b26a 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeaderV4.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/PwDbHeaderV4.java @@ -96,7 +96,7 @@ public class PwDbHeaderV4 extends PwDbHeader { public PwDbHeaderV4(PwDatabaseV4 databaseV4) { this.db = databaseV4; this.version = getMinKdbxVersion(databaseV4); // Only for writing - this.masterSeed = new byte[32]; + this.setMasterSeed(new byte[32]); } public long getVersion() { @@ -112,11 +112,11 @@ public class PwDbHeaderV4 extends PwDbHeader { boolean hasCustomData = false; @Override - public boolean operate(PwGroupV4 group) { - if (group == null) { + public boolean operate(PwGroupV4 node) { + if (node == null) { return true; } - if (group.containsCustomData()) { + if (node.containsCustomData()) { hasCustomData = true; return false; } @@ -242,7 +242,7 @@ public class PwDbHeaderV4 extends PwDbHeader { break; case PwDbHeaderV4Fields.MasterSeed: - masterSeed = fieldData; + setMasterSeed(fieldData); break; case PwDbHeaderV4Fields.TransformSeed: @@ -256,7 +256,7 @@ public class PwDbHeaderV4 extends PwDbHeader { break; case PwDbHeaderV4Fields.EncryptionIV: - encryptionIV = fieldData; + setEncryptionIV(fieldData); break; case PwDbHeaderV4Fields.InnerRandomstreamKey: @@ -319,11 +319,11 @@ public class PwDbHeaderV4 extends PwDbHeader { } int flag = LEDataInputStream.readInt(pbFlags, 0); - if ( flag < 0 || flag >= PwCompressionAlgorithm.count ) { + if ( flag < 0 || flag >= PwCompressionAlgorithm.values().length ) { throw new IOException("Unrecognized compression flag."); } - db.setCompressionAlgorithm(PwCompressionAlgorithm.fromId(flag)); + db.setCompressionAlgorithm(PwCompressionAlgorithm.Companion.fromId(flag)); } public void setRandomStreamID(byte[] streamID) throws IOException { @@ -332,11 +332,11 @@ public class PwDbHeaderV4 extends PwDbHeader { } int id = LEDataInputStream.readInt(streamID, 0); - if ( id < 0 || id >= CrsAlgorithm.count ) { + if ( id < 0 || id >= CrsAlgorithm.values().length) { throw new IOException("Invalid stream id."); } - innerRandomStream = CrsAlgorithm.fromId(id); + innerRandomStream = CrsAlgorithm.Companion.fromId(id); } /** @@ -351,7 +351,7 @@ public class PwDbHeaderV4 extends PwDbHeader { } public static boolean matchesHeader(int sig1, int sig2) { - return (sig1 == PWM_DBSIG_1) && ( (sig2 == DBSIG_PRE2) || (sig2 == DBSIG_2) ); + return (sig1 == PwDbHeader.PWM_DBSIG_1) && ( (sig2 == DBSIG_PRE2) || (sig2 == DBSIG_2) ); } public static byte[] computeHeaderHmac(byte[] header, byte[] key) throws IOException{ diff --git a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV4.kt index a35cca539..7eacb931f 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV4.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/element/PwEntryV4.kt @@ -21,8 +21,6 @@ package com.kunzisoft.keepass.database.element import android.os.Parcel import android.os.Parcelable -import com.kunzisoft.keepass.database.AutoType -import com.kunzisoft.keepass.database.ExtraFields import com.kunzisoft.keepass.database.security.ProtectedBinary import com.kunzisoft.keepass.database.security.ProtectedString import com.kunzisoft.keepass.utils.MemUtil diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/ArcFourException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/ArcFourException.kt similarity index 79% rename from app/src/main/java/com/kunzisoft/keepass/database/exception/ArcFourException.java rename to app/src/main/java/com/kunzisoft/keepass/database/exception/ArcFourException.kt index ddc89a682..75e06921d 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/ArcFourException.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/ArcFourException.kt @@ -17,13 +17,11 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database.exception; +package com.kunzisoft.keepass.database.exception -public class ArcFourException extends InvalidDBException { - - /** - * - */ - private static final long serialVersionUID = 2103983626687861237L; +class ArcFourException : InvalidDBException() { + companion object { + private const val serialVersionUID = 2103983626687861237L + } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/ContentFileNotFoundException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/ContentFileNotFoundException.kt similarity index 55% rename from app/src/main/java/com/kunzisoft/keepass/database/exception/ContentFileNotFoundException.java rename to app/src/main/java/com/kunzisoft/keepass/database/exception/ContentFileNotFoundException.kt index 1c297218b..5d3ace33d 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/ContentFileNotFoundException.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/ContentFileNotFoundException.kt @@ -17,31 +17,30 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database.exception; +package com.kunzisoft.keepass.database.exception -import android.net.Uri; +import android.net.Uri -import com.kunzisoft.keepass.utils.EmptyUtils; +import com.kunzisoft.keepass.utils.EmptyUtils -import java.io.FileNotFoundException; +import java.io.FileNotFoundException /** * Created by bpellin on 3/14/16. */ -public class ContentFileNotFoundException extends FileNotFoundException { - public static FileNotFoundException getInstance(Uri uri) { - if (uri == null) { return new FileNotFoundException(); } +class ContentFileNotFoundException : FileNotFoundException() { + companion object { + fun getInstance(uri: Uri?): FileNotFoundException { + if (uri == null) { + return FileNotFoundException() + } - String scheme = uri.getScheme(); + val scheme = uri.scheme + + return if (!EmptyUtils.isNullOrEmpty(scheme) && scheme!!.equals("content", ignoreCase = true)) { + ContentFileNotFoundException() + } else FileNotFoundException() - if (!EmptyUtils.isNullOrEmpty(scheme) && scheme.equalsIgnoreCase("content")) { - return new ContentFileNotFoundException(); } - - return new FileNotFoundException(); - } - - public ContentFileNotFoundException() { - super(); } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidAlgorithmException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidAlgorithmException.java deleted file mode 100644 index bf389ab0f..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidAlgorithmException.java +++ /dev/null @@ -1,32 +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.database.exception; - -public class InvalidAlgorithmException extends InvalidDBException { - /** - * - */ - private static final long serialVersionUID = 3062682891863487208L; - - public InvalidAlgorithmException() { - super(); - } - -} \ No newline at end of file diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidAlgorithmException.kt b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidAlgorithmException.kt new file mode 100644 index 000000000..3a784f2d3 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidAlgorithmException.kt @@ -0,0 +1,27 @@ +/* + * 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.database.exception + +class InvalidAlgorithmException : InvalidDBException() { + companion object { + private const val serialVersionUID = 3062682891863487208L + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBSignatureException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBException.kt similarity index 74% rename from app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBSignatureException.java rename to app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBException.kt index 6b65c7bf6..4d836b281 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBSignatureException.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBException.kt @@ -17,16 +17,16 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database.exception; +package com.kunzisoft.keepass.database.exception -public class InvalidDBSignatureException extends InvalidDBException { - /** - * - */ - private static final long serialVersionUID = -5358923878743513758L; +open class InvalidDBException : Exception { - public InvalidDBSignatureException() { - super(); - } + constructor(str: String) : super(str) + + constructor() : super() + + companion object { + private const val serialVersionUID = 5191964825154190923L + } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InconsistentDBException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBSignatureException.kt similarity index 76% rename from app/src/main/java/com/kunzisoft/keepass/database/exception/InconsistentDBException.java rename to app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBSignatureException.kt index 317f9f803..dd312b91a 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/InconsistentDBException.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBSignatureException.kt @@ -17,14 +17,11 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database.exception; +package com.kunzisoft.keepass.database.exception -public class InconsistentDBException extends Exception { - - public InconsistentDBException(String msg) { - super(msg); - } - - private static final long serialVersionUID = 4879502365625912291L; +class InvalidDBSignatureException : InvalidDBException() { + companion object { + private const val serialVersionUID = -5358923878743513758L + } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBVersionException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBVersionException.java deleted file mode 100644 index 8f9f2f04b..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBVersionException.java +++ /dev/null @@ -1,32 +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.database.exception; - -public class InvalidDBVersionException extends InvalidDBException { - /** - * - */ - private static final long serialVersionUID = -4260650987856400586L; - - public InvalidDBVersionException() { - super(); - } - -} \ No newline at end of file diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBVersionException.kt b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBVersionException.kt new file mode 100644 index 000000000..43f558389 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBVersionException.kt @@ -0,0 +1,27 @@ +/* + * 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.database.exception + +class InvalidDBVersionException : InvalidDBException() { + companion object { + private const val serialVersionUID = -4260650987856400586L + } + +} \ No newline at end of file diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidKeyFileException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidKeyFileException.kt similarity index 75% rename from app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidKeyFileException.java rename to app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidKeyFileException.kt index 88c5db652..44bfadbcf 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidKeyFileException.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidKeyFileException.kt @@ -16,15 +16,10 @@ * You should have received a copy of the GNU General Public License * along with KeePass DX. If not, see . * - */package com.kunzisoft.keepass.database.exception; + */package com.kunzisoft.keepass.database.exception -public class InvalidKeyFileException extends InvalidDBException { - /** - * - */ - private static final long serialVersionUID = 5540694419562294464L; - - public InvalidKeyFileException() { - super(); - } +open class InvalidKeyFileException : InvalidDBException() { + companion object { + private const val serialVersionUID = 5540694419562294464L + } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidPasswordException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidPasswordException.java deleted file mode 100644 index 0b5f475c9..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidPasswordException.java +++ /dev/null @@ -1,36 +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.database.exception; - -public class InvalidPasswordException extends InvalidDBException { - - /** - * - */ - private static final long serialVersionUID = -8729476180242058319L; - - public InvalidPasswordException(String str) { - super(str); - } - - public InvalidPasswordException() { - super(); - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidPasswordException.kt b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidPasswordException.kt new file mode 100644 index 000000000..967ef7f77 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidPasswordException.kt @@ -0,0 +1,26 @@ +/* + * 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.database.exception + +class InvalidPasswordException : InvalidDBException() { + companion object { + private const val serialVersionUID = -8729476180242058319L + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/KeyFileEmptyException.kt b/app/src/main/java/com/kunzisoft/keepass/database/exception/KeyFileEmptyException.kt new file mode 100644 index 000000000..9688a5251 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/KeyFileEmptyException.kt @@ -0,0 +1,26 @@ +/* + * 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.database.exception + +class KeyFileEmptyException : InvalidKeyFileException() { + companion object { + private const val serialVersionUID = -1630780661204212325L + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/PwDbOutputException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/PwDbOutputException.java deleted file mode 100644 index e82c6fdfa..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/PwDbOutputException.java +++ /dev/null @@ -1,37 +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.database.exception; - -public class PwDbOutputException extends Exception { - public PwDbOutputException(String string) { - super(string); - } - - public PwDbOutputException(String string, Exception e) { super(string, e); } - - public PwDbOutputException(Exception e) { - super(e); - } - - /** - * - */ - private static final long serialVersionUID = 3321212743159473368L; -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/PwDbOutputException.kt similarity index 69% rename from app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBException.java rename to app/src/main/java/com/kunzisoft/keepass/database/exception/PwDbOutputException.kt index 3e42b7167..ccd06efa9 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/InvalidDBException.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/PwDbOutputException.kt @@ -17,21 +17,16 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database.exception; +package com.kunzisoft.keepass.database.exception -public class InvalidDBException extends Exception { +class PwDbOutputException : Exception { + constructor(string: String) : super(string) - public InvalidDBException(String str) { - super(str); - } + constructor(string: String, e: Exception) : super(string, e) - public InvalidDBException() { - super(); - } - - /** - * - */ - private static final long serialVersionUID = 5191964825154190923L; + constructor(e: Exception) : super(e) + companion object { + private const val serialVersionUID = 3321212743159473368L + } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/SamsungClipboardException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/SamsungClipboardException.java deleted file mode 100644 index 0bf93fe3f..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/SamsungClipboardException.java +++ /dev/null @@ -1,37 +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.database.exception; - -public class SamsungClipboardException extends Exception { - - public SamsungClipboardException(String message) { - super(message); - } - - public SamsungClipboardException(Exception e) { - super(e); - } - - /** - * - */ - private static final long serialVersionUID = -3168837280393843509L; - -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/KeyFileEmptyException.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/SamsungClipboardException.kt similarity index 75% rename from app/src/main/java/com/kunzisoft/keepass/database/exception/KeyFileEmptyException.java rename to app/src/main/java/com/kunzisoft/keepass/database/exception/SamsungClipboardException.kt index 1926f6ca0..74f08db0b 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/KeyFileEmptyException.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/SamsungClipboardException.kt @@ -17,15 +17,11 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database.exception; +package com.kunzisoft.keepass.database.exception -public class KeyFileEmptyException extends InvalidKeyFileException { - /** - * - */ - private static final long serialVersionUID = -1630780661204212325L; +class SamsungClipboardException(e: Exception) : Exception(e) { + companion object { + private const val serialVersionUID = -3168837280393843509L + } - public KeyFileEmptyException() { - super(); - } } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.java b/app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.java deleted file mode 100644 index 917e23e57..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.kunzisoft.keepass.database.exception; - -import java.io.IOException; - -public class UnknownKDF extends IOException { - - private static String message = "Unknown key derivation function"; - - public UnknownKDF() { - super(message); - } - - public UnknownKDF(Exception e) { - super(message, e); - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.kt b/app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.kt new file mode 100644 index 000000000..2897148c5 --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/exception/UnknownKDF.kt @@ -0,0 +1,9 @@ +package com.kunzisoft.keepass.database.exception + +import java.io.IOException + +class UnknownKDF : IOException(message) { + companion object { + private const val message = "Unknown key derivation function" + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/iterator/EntrySearchStringIteratorV3.java b/app/src/main/java/com/kunzisoft/keepass/database/iterator/EntrySearchStringIteratorV3.java deleted file mode 100644 index 945865092..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/iterator/EntrySearchStringIteratorV3.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * 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.database.iterator; - -import com.kunzisoft.keepass.database.element.PwEntryV3; -import com.kunzisoft.keepass.database.search.SearchParameters; - -import java.util.NoSuchElementException; - -public class EntrySearchStringIteratorV3 extends EntrySearchStringIterator { - - private PwEntryV3 mEntry; - private SearchParameters mSearchParameters; - - public EntrySearchStringIteratorV3(PwEntryV3 entry) { - this(entry, new SearchParameters()); - } - - public EntrySearchStringIteratorV3(PwEntryV3 entry, SearchParameters searchParameters) { - this.mEntry = entry; - this.mSearchParameters = searchParameters; - } - - private static final int title = 0; - private static final int url = 1; - private static final int username = 2; - private static final int comment = 3; - private static final int maxEntries = 4; - - private int current = 0; - - @Override - public boolean hasNext() { - return current < maxEntries; - } - - @Override - public String next() { - // Past the end of the list - if (current == maxEntries) { - throw new NoSuchElementException("Past final string"); - } - - useSearchParameters(); - - String str = getCurrentString(); - current++; - return str; - } - - private void useSearchParameters() { - - if (mSearchParameters == null) { return; } - - boolean found = false; - while (!found) { - switch (current) { - case title: - found = mSearchParameters.getSearchInTitles(); - break; - case url: - found = mSearchParameters.getSearchInUrls(); - break; - case username: - found = mSearchParameters.getSearchInUserNames(); - break; - case comment: - found = mSearchParameters.getSearchInNotes(); - break; - default: - found = true; - } - - if (!found) { current++; } - } - } - - private String getCurrentString() { - switch (current) { - case title: - return mEntry.getTitle(); - case url: - return mEntry.getUrl(); - case username: - return mEntry.getUsername(); - case comment: - return mEntry.getNotes(); - default: - return ""; - } - } - -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/iterator/EntrySearchStringIteratorV3.kt b/app/src/main/java/com/kunzisoft/keepass/database/iterator/EntrySearchStringIteratorV3.kt new file mode 100644 index 000000000..2ff81e61b --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/iterator/EntrySearchStringIteratorV3.kt @@ -0,0 +1,95 @@ +/* + * 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.database.iterator + +import com.kunzisoft.keepass.database.element.PwEntryV3 +import com.kunzisoft.keepass.database.search.SearchParameters + +import java.util.NoSuchElementException + +class EntrySearchStringIteratorV3 + +@JvmOverloads +constructor(private val mEntry: PwEntryV3, + private val mSearchParameters: SearchParameters? = SearchParameters()) + : EntrySearchStringIterator() { + + private var current = 0 + + private val currentString: String + get() { + return when (current) { + title -> mEntry.title + url -> mEntry.url + username -> mEntry.username + comment -> mEntry.notes + else -> "" + } + } + + override fun hasNext(): Boolean { + return current < maxEntries + } + + override fun next(): String { + // Past the end of the list + if (current == maxEntries) { + throw NoSuchElementException("Past final string") + } + + useSearchParameters() + + val str = currentString + current++ + return str + } + + private fun useSearchParameters() { + + if (mSearchParameters == null) { + return + } + + var found = false + while (!found) { + found = when (current) { + title -> mSearchParameters.searchInTitles + url -> mSearchParameters.searchInUrls + username -> mSearchParameters.searchInUserNames + comment -> mSearchParameters.searchInNotes + else -> true + } + + if (!found) { + current++ + } + } + } + + companion object { + + private const val title = 0 + private const val url = 1 + private const val username = 2 + private const val comment = 3 + private const val maxEntries = 4 + } + +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/load/Importer.java b/app/src/main/java/com/kunzisoft/keepass/database/load/Importer.kt similarity index 50% rename from app/src/main/java/com/kunzisoft/keepass/database/load/Importer.java rename to app/src/main/java/com/kunzisoft/keepass/database/load/Importer.kt index 1b60c2e88..93ad10914 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/load/Importer.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/load/Importer.kt @@ -17,28 +17,28 @@ * along with KeePass DX. If not, see . * */ -package com.kunzisoft.keepass.database.load; +package com.kunzisoft.keepass.database.load -import com.kunzisoft.keepass.database.element.PwDatabase; -import com.kunzisoft.keepass.database.exception.InvalidDBException; -import com.kunzisoft.keepass.tasks.ProgressTaskUpdater; +import com.kunzisoft.keepass.database.element.PwDatabase +import com.kunzisoft.keepass.database.exception.InvalidDBException +import com.kunzisoft.keepass.tasks.ProgressTaskUpdater -import java.io.IOException; -import java.io.InputStream; +import java.io.IOException +import java.io.InputStream -public abstract class Importer { +abstract class Importer> { - /** - * Load a versioned database file, return contents in a new PwDatabase. - * - * @param inStream Existing file to load. - * @param password Pass phrase for infile. - * @return new PwDatabase container. - * - * @throws IOException on any file error. - * @throws InvalidDBException on database error. - */ - public abstract PwDb openDatabase(InputStream inStream, String password, InputStream keyInputStream, ProgressTaskUpdater updater) - throws IOException, InvalidDBException; + /** + * Load a versioned database file, return contents in a new PwDatabase. + * + * @param inStream Existing file to load. + * @param password Pass phrase for infile. + * @return new PwDatabase container. + * + * @throws IOException on any file error. + * @throws InvalidDBException on database error. + */ + @Throws(IOException::class, InvalidDBException::class) + abstract fun openDatabase(inStream: InputStream, password: String?, keyInputStream: InputStream?, updater: ProgressTaskUpdater?): PwDb } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/load/ImporterV3.java b/app/src/main/java/com/kunzisoft/keepass/database/load/ImporterV3.java index 966166e9b..3ece28c78 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/load/ImporterV3.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/load/ImporterV3.java @@ -45,6 +45,7 @@ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA package com.kunzisoft.keepass.database.load; +import android.support.annotation.NonNull; import android.util.Log; import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.crypto.CipherFactory; @@ -76,8 +77,9 @@ public class ImporterV3 extends Importer { private PwDatabaseV3 databaseToOpen; + @NonNull @Override - public PwDatabaseV3 openDatabase(InputStream inStream, + public PwDatabaseV3 openDatabase(@NonNull InputStream inStream, String password, InputStream kfIs, ProgressTaskUpdater progressTaskUpdater) @@ -116,14 +118,11 @@ public class ImporterV3 extends Importer { } else { throw new InvalidAlgorithmException(); } - - // Copy for testing - databaseToOpen.copyHeader(hdr); databaseToOpen.setNumberKeyEncryptionRounds(hdr.numKeyEncRounds); // Generate transformedMasterKey from masterKey - databaseToOpen.makeFinalKey(hdr.masterSeed, hdr.transformSeed, databaseToOpen.getNumberKeyEncryptionRounds()); + databaseToOpen.makeFinalKey(hdr.getMasterSeed(), hdr.transformSeed, databaseToOpen.getNumberKeyEncryptionRounds()); if (progressTaskUpdater != null) progressTaskUpdater.updateMessage(R.string.decrypting_db); @@ -145,7 +144,7 @@ public class ImporterV3 extends Importer { } try { - cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec( databaseToOpen.getFinalKey(), "AES" ), new IvParameterSpec( hdr.encryptionIV ) ); + cipher.init( Cipher.DECRYPT_MODE, new SecretKeySpec( databaseToOpen.getFinalKey(), "AES" ), new IvParameterSpec(hdr.getEncryptionIV()) ); } catch (InvalidKeyException e1) { throw new IOException("Invalid key"); } catch (InvalidAlgorithmParameterException e1) { @@ -164,9 +163,6 @@ public class ImporterV3 extends Importer { throw new InvalidPasswordException(); } - // Copy decrypted data for testing - databaseToOpen.copyEncrypted(filebuf, PwDbHeaderV3.BUF_SIZE, encryptedPartSize); - MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); diff --git a/app/src/main/java/com/kunzisoft/keepass/database/load/ImporterV4.java b/app/src/main/java/com/kunzisoft/keepass/database/load/ImporterV4.java index 3a22633b8..b865feace 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/load/ImporterV4.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/load/ImporterV4.java @@ -19,6 +19,8 @@ */ package com.kunzisoft.keepass.database.load; +import android.support.annotation.NonNull; + import biz.source_code.base64Coder.Base64Coder; import com.kunzisoft.keepass.R; import com.kunzisoft.keepass.crypto.CipherFactory; @@ -72,8 +74,9 @@ public class ImporterV4 extends Importer { this.streamDir = streamDir; } + @NonNull @Override - public PwDatabaseV4 openDatabase(InputStream inStream, + public PwDatabaseV4 openDatabase(@NonNull InputStream inStream, String password, InputStream keyInputStream, ProgressTaskUpdater progressTaskUpdater) @@ -93,7 +96,7 @@ public class ImporterV4 extends Importer { byte[] pbHeader = hh.header; mDatabase.retrieveMasterKey(password, keyInputStream); - mDatabase.makeFinalKey(header.masterSeed); + mDatabase.makeFinalKey(header.getMasterSeed()); if (progressTaskUpdater != null) progressTaskUpdater.updateMessage(R.string.decrypting_db); @@ -103,7 +106,7 @@ public class ImporterV4 extends Importer { engine = CipherFactory.getInstance(mDatabase.getDataCipher()); mDatabase.setDataEngine(engine); mDatabase.setEncryptionAlgorithm(engine.getPwEncryptionAlgorithm()); - cipher = engine.getCipher(Cipher.DECRYPT_MODE, mDatabase.getFinalKey(), header.encryptionIV); + cipher = engine.getCipher(Cipher.DECRYPT_MODE, mDatabase.getFinalKey(), header.getEncryptionIV()); } catch (NoSuchAlgorithmException|NoSuchPaddingException|InvalidKeyException|InvalidAlgorithmParameterException e) { throw new IOException("Invalid algorithm.", e); } @@ -432,17 +435,17 @@ public class ImporterV4 extends Importer { case MemoryProtection: if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemProtTitle) ) { - mDatabase.getMemoryProtection().protectTitle = ReadBool(xpp, false); + mDatabase.getMemoryProtection().setProtectTitle(ReadBool(xpp, false)); } else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemProtUserName) ) { - mDatabase.getMemoryProtection().protectUserName = ReadBool(xpp, false); + mDatabase.getMemoryProtection().setProtectUserName(ReadBool(xpp, false)); } else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemProtPassword) ) { - mDatabase.getMemoryProtection().protectPassword = ReadBool(xpp, false); + mDatabase.getMemoryProtection().setProtectPassword(ReadBool(xpp, false)); } else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemProtURL) ) { - mDatabase.getMemoryProtection().protectUrl = ReadBool(xpp, false); + mDatabase.getMemoryProtection().setProtectUrl(ReadBool(xpp, false)); } else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemProtNotes) ) { - mDatabase.getMemoryProtection().protectNotes = ReadBool(xpp, false); + mDatabase.getMemoryProtection().setProtectNotes(ReadBool(xpp, false)); } else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemProtAutoHide) ) { - mDatabase.getMemoryProtection().autoEnableVisualHiding = ReadBool(xpp, false); + mDatabase.getMemoryProtection().setAutoEnableVisualHiding(ReadBool(xpp, false)); } else { ReadUnknown(xpp); } @@ -687,11 +690,11 @@ public class ImporterV4 extends Importer { case EntryAutoType: if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemAutoTypeEnabled) ) { - ctxEntry.getAutoType().enabled = ReadBool(xpp, true); + ctxEntry.getAutoType().setEnabled(ReadBool(xpp, true)); } else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemAutoTypeObfuscation) ) { - ctxEntry.getAutoType().obfuscationOptions = ReadUInt(xpp, 0); + ctxEntry.getAutoType().setObfuscationOptions(ReadUInt(xpp, 0)); } else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemAutoTypeDefaultSeq) ) { - ctxEntry.getAutoType().defaultSequence = ReadString(xpp); + ctxEntry.getAutoType().setDefaultSequence(ReadString(xpp)); } else if ( name.equalsIgnoreCase(PwDatabaseV4XML.ElemAutoTypeItem) ) { return SwitchContext(ctx, KdbContext.EntryAutoTypeItem, xpp); } else { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutputV3.java b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutputV3.java index 687af8b43..ad40de81d 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutputV3.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutputV3.java @@ -39,8 +39,8 @@ public class PwDbHeaderOutputV3 { mOS.write(LEDataOutputStream.writeIntBuf(mHeader.signature2)); mOS.write(LEDataOutputStream.writeIntBuf(mHeader.flags)); mOS.write(LEDataOutputStream.writeIntBuf(mHeader.version)); - mOS.write(mHeader.masterSeed); - mOS.write(mHeader.encryptionIV); + mOS.write(mHeader.getMasterSeed()); + mOS.write(mHeader.getEncryptionIV()); mOS.write(LEDataOutputStream.writeIntBuf(mHeader.numGroups)); mOS.write(LEDataOutputStream.writeIntBuf(mHeader.numEntries)); } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutputV4.java b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutputV4.java index abeb66e70..eee7b7b2a 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutputV4.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbHeaderOutputV4.java @@ -63,7 +63,7 @@ public class PwDbHeaderOutputV4 extends PwDbHeaderOutput { } try { - d.makeFinalKey(header.masterSeed); + d.makeFinalKey(header.getMasterSeed()); } catch (IOException e) { throw new PwDbOutputException(e); } @@ -92,8 +92,8 @@ public class PwDbHeaderOutputV4 extends PwDbHeaderOutput { writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.CipherID, Types.UUIDtoBytes(db.getDataCipher())); - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.CompressionFlags, LEDataOutputStream.writeIntBuf(db.getCompressionAlgorithm().id)); - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.MasterSeed, header.masterSeed); + writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.CompressionFlags, LEDataOutputStream.writeIntBuf(db.getCompressionAlgorithm().getId())); + writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.MasterSeed, header.getMasterSeed()); if (header.getVersion() < PwDbHeaderV4.FILE_VERSION_32_4) { writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.TransformSeed, header.getTransformSeed()); @@ -102,14 +102,14 @@ public class PwDbHeaderOutputV4 extends PwDbHeaderOutput { writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.KdfParameters, KdfParameters.serialize(db.getKdfParameters())); } - if (header.encryptionIV.length > 0) { - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.EncryptionIV, header.encryptionIV); + if (header.getEncryptionIV().length > 0) { + writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.EncryptionIV, header.getEncryptionIV()); } if (header.getVersion() < PwDbHeaderV4.FILE_VERSION_32_4) { writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.InnerRandomstreamKey, header.innerRandomStreamKey); writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.StreamStartBytes, header.streamStartBytes); - writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.InnerRandomStreamID, LEDataOutputStream.writeIntBuf(header.innerRandomStream.id)); + writeHeaderField(PwDbHeaderV4.PwDbHeaderV4Fields.InnerRandomStreamID, LEDataOutputStream.writeIntBuf(header.innerRandomStream.getId())); } if (db.containsPublicCustomData()) { diff --git a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbInnerHeaderOutputV4.java b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbInnerHeaderOutputV4.java index 836330391..851b72987 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbInnerHeaderOutputV4.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbInnerHeaderOutputV4.java @@ -43,7 +43,7 @@ public class PwDbInnerHeaderOutputV4 { public void output() throws IOException { los.write(PwDbHeaderV4.PwDbInnerHeaderV4Fields.InnerRandomStreamID); los.writeInt(4); - los.writeInt(header.innerRandomStream.id); + los.writeInt(header.innerRandomStream.getId()); int streamKeySize = header.innerRandomStreamKey.length; los.write(PwDbHeaderV4.PwDbInnerHeaderV4Fields.InnerRandomstreamKey); diff --git a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbOutput.java b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbOutput.java index 2cbcca5d8..6b8d5ab89 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbOutput.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbOutput.java @@ -41,8 +41,8 @@ public abstract class PwDbOutput
{ } catch (NoSuchAlgorithmException e) { throw new PwDbOutputException("Does not support secure random number generation."); } - random.nextBytes(header.encryptionIV); - random.nextBytes(header.masterSeed); + random.nextBytes(header.getEncryptionIV()); + random.nextBytes(header.getMasterSeed()); return random; } diff --git a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbV3Output.java b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbV3Output.java index 017f7340f..b8cda3f05 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbV3Output.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbV3Output.java @@ -50,7 +50,7 @@ public class PwDbV3Output extends PwDbOutput { public byte[] getFinalKey(PwDbHeader header) throws PwDbOutputException { try { PwDbHeaderV3 h3 = (PwDbHeaderV3) header; - mDatabaseV3.makeFinalKey(h3.masterSeed, h3.transformSeed, mDatabaseV3.getNumberKeyEncryptionRounds()); + mDatabaseV3.makeFinalKey(h3.getMasterSeed(), h3.transformSeed, mDatabaseV3.getNumberKeyEncryptionRounds()); return mDatabaseV3.getFinalKey(); } catch (IOException e) { throw new PwDbOutputException("Key creation failed.", e); @@ -81,7 +81,7 @@ public class PwDbV3Output extends PwDbOutput { } try { - cipher.init( Cipher.ENCRYPT_MODE, new SecretKeySpec(finalKey, "AES" ), new IvParameterSpec(header.encryptionIV) ); + cipher.init( Cipher.ENCRYPT_MODE, new SecretKeySpec(finalKey, "AES" ), new IvParameterSpec(header.getEncryptionIV()) ); CipherOutputStream cos = new CipherOutputStream(mOS, cipher); BufferedOutputStream bos = new BufferedOutputStream(cos); outputPlanGroupAndEntries(bos); diff --git a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbV4Output.java b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbV4Output.java index 036533337..1b9e6f8f1 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbV4Output.java +++ b/app/src/main/java/com/kunzisoft/keepass/database/save/PwDbV4Output.java @@ -153,12 +153,12 @@ public class PwDbV4Output extends PwDbOutput { }, new NodeHandler() { @Override - public boolean operate(PwGroupV4 group) { + public boolean operate(PwGroupV4 node) { while (true) { try { - if (group.getParent() == groupStack.peek()) { - groupStack.push(group); - startGroup(group); + if (node.getParent() == groupStack.peek()) { + groupStack.push(node); + startGroup(node); break; } else { groupStack.pop(); @@ -239,7 +239,7 @@ public class PwDbV4Output extends PwDbOutput { try { //mPM.makeFinalKey(header.masterSeed, mPM.kdfParameters); - cipher = engine.getCipher(Cipher.ENCRYPT_MODE, mPM.getFinalKey(), header.encryptionIV); + cipher = engine.getCipher(Cipher.ENCRYPT_MODE, mPM.getFinalKey(), header.getEncryptionIV()); } catch (Exception e) { throw new PwDbOutputException("Invalid algorithm.", e); } @@ -250,13 +250,13 @@ public class PwDbV4Output extends PwDbOutput { @Override protected SecureRandom setIVs(PwDbHeaderV4 header) throws PwDbOutputException { SecureRandom random = super.setIVs(header); - random.nextBytes(header.masterSeed); + random.nextBytes(header.getMasterSeed()); int ivLength = engine.ivLength(); - if (ivLength != header.encryptionIV.length) { - header.encryptionIV = new byte[ivLength]; + if (ivLength != header.getEncryptionIV().length) { + header.setEncryptionIV(new byte[ivLength]); } - random.nextBytes(header.encryptionIV); + random.nextBytes(header.getEncryptionIV()); if (mPM.getKdfParameters() == null) { mPM.setKdfParameters(KdfFactory.aesKdf.getDefaultParameters()); @@ -539,11 +539,11 @@ public class PwDbV4Output extends PwDbOutput { xml.startTag(null, name); - writeObject(PwDatabaseV4XML.ElemAutoTypeEnabled, autoType.enabled); - writeObject(PwDatabaseV4XML.ElemAutoTypeObfuscation, autoType.obfuscationOptions); + writeObject(PwDatabaseV4XML.ElemAutoTypeEnabled, autoType.getEnabled()); + writeObject(PwDatabaseV4XML.ElemAutoTypeObfuscation, autoType.getObfuscationOptions()); - if (autoType.defaultSequence.length() > 0) { - writeObject(PwDatabaseV4XML.ElemAutoTypeDefaultSeq, autoType.defaultSequence, true); + if (autoType.getDefaultSequence().length() > 0) { + writeObject(PwDatabaseV4XML.ElemAutoTypeDefaultSeq, autoType.getDefaultSequence(), true); } for (Entry pair : autoType.entrySet()) { @@ -575,20 +575,20 @@ public class PwDbV4Output extends PwDbOutput { xml.startTag(null, PwDatabaseV4XML.ElemValue); boolean protect = value.isProtected(); if (isEntryString) { - if (key.equals(PwDefsV4.TITLE_FIELD)) { - protect = mPM.getMemoryProtection().protectTitle; + if (key.equals(MemoryProtectionConfig.ProtectDefinition.TITLE_FIELD)) { + protect = mPM.getMemoryProtection().getProtectTitle(); } - else if (key.equals(PwDefsV4.USERNAME_FIELD)) { - protect = mPM.getMemoryProtection().protectUserName; + else if (key.equals(MemoryProtectionConfig.ProtectDefinition.USERNAME_FIELD)) { + protect = mPM.getMemoryProtection().getProtectUserName(); } - else if (key.equals(PwDefsV4.PASSWORD_FIELD)) { - protect = mPM.getMemoryProtection().protectPassword; + else if (key.equals(MemoryProtectionConfig.ProtectDefinition.PASSWORD_FIELD)) { + protect = mPM.getMemoryProtection().getProtectPassword(); } - else if (key.equals(PwDefsV4.URL_FIELD)) { - protect = mPM.getMemoryProtection().protectUrl; + else if (key.equals(MemoryProtectionConfig.ProtectDefinition.URL_FIELD)) { + protect = mPM.getMemoryProtection().getProtectUrl(); } - else if (key.equals(PwDefsV4.NOTES_FIELD)) { - protect = mPM.getMemoryProtection().protectNotes; + else if (key.equals(MemoryProtectionConfig.ProtectDefinition.NOTES_FIELD)) { + protect = mPM.getMemoryProtection().getProtectNotes(); } } @@ -651,11 +651,11 @@ public class PwDbV4Output extends PwDbOutput { xml.startTag(null, name); - writeObject(PwDatabaseV4XML.ElemProtTitle, value.protectTitle); - writeObject(PwDatabaseV4XML.ElemProtUserName, value.protectUserName); - writeObject(PwDatabaseV4XML.ElemProtPassword, value.protectPassword); - writeObject(PwDatabaseV4XML.ElemProtURL, value.protectUrl); - writeObject(PwDatabaseV4XML.ElemProtNotes, value.protectNotes); + writeObject(PwDatabaseV4XML.ElemProtTitle, value.getProtectTitle()); + writeObject(PwDatabaseV4XML.ElemProtUserName, value.getProtectUserName()); + writeObject(PwDatabaseV4XML.ElemProtPassword, value.getProtectPassword()); + writeObject(PwDatabaseV4XML.ElemProtURL, value.getProtectUrl()); + writeObject(PwDatabaseV4XML.ElemProtNotes, value.getProtectNotes()); xml.endTag(null, name); diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/EntrySearchHandlerV4.java b/app/src/main/java/com/kunzisoft/keepass/database/search/EntrySearchHandlerV4.java deleted file mode 100644 index b2142b206..000000000 --- a/app/src/main/java/com/kunzisoft/keepass/database/search/EntrySearchHandlerV4.java +++ /dev/null @@ -1,115 +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.database.search; - -import com.kunzisoft.keepass.database.NodeHandler; -import com.kunzisoft.keepass.database.element.PwEntryV4; -import com.kunzisoft.keepass.database.element.PwGroupV4; -import com.kunzisoft.keepass.database.iterator.EntrySearchStringIterator; -import com.kunzisoft.keepass.database.iterator.EntrySearchStringIteratorV4; -import com.kunzisoft.keepass.utils.StringUtil; -import com.kunzisoft.keepass.utils.UuidUtil; - -import java.util.Date; -import java.util.List; -import java.util.Locale; - -public class EntrySearchHandlerV4 extends NodeHandler { - - private List mListStorage; - private SearchParametersV4 mSearchParametersV4; - protected Date now; - - public EntrySearchHandlerV4(SearchParametersV4 searchParametersV4, List listStorage) { - this.mListStorage = listStorage; - this.mSearchParametersV4 = searchParametersV4; - this.now = new Date(); - } - - @Override - public boolean operate(PwEntryV4 entry) { - if (mSearchParametersV4.getRespectEntrySearchingDisabled() && !entry.isSearchingEnabled()) { - return true; - } - - if (mSearchParametersV4.getExcludeExpired() && entry.isExpires() && now.after(entry.getExpiryTime().getDate())) { - return true; - } - - String term = mSearchParametersV4.getSearchString(); - if (mSearchParametersV4.getIgnoreCase()) { - term = term.toLowerCase(); - } - - if (searchStrings(entry, term)) { - mListStorage.add(entry); - return true; - } - - if (mSearchParametersV4.getSearchInGroupNames()) { - PwGroupV4 parent = entry.getParent(); - if (parent != null) { - String groupName = parent.getTitle(); - if (mSearchParametersV4.getIgnoreCase()) { - groupName = groupName.toLowerCase(); - } - - if (groupName.contains(term)) { - mListStorage.add(entry); - return true; - } - } - } - - if (searchID(entry)) { - mListStorage.add(entry); - return true; - } - - return true; - } - - private boolean searchID(PwEntryV4 entry) { - if (mSearchParametersV4.getSearchInUUIDs()) { - String hex = UuidUtil.toHexString(entry.getId()); - return StringUtil.INSTANCE.indexOfIgnoreCase(hex, mSearchParametersV4.getSearchString(), Locale.ENGLISH) >= 0; - } - - return false; - } - - private boolean searchStrings(PwEntryV4 entry, String term) { - EntrySearchStringIterator iterator = new EntrySearchStringIteratorV4(entry, mSearchParametersV4); - while (iterator.hasNext()) { - String str = iterator.next(); - if (str.length() > 0) { - if (mSearchParametersV4.getIgnoreCase()) { - str = str.toLowerCase(); - } - - if (str.contains(term)) { - return true; - } - } - } - - return false; - } -} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/EntrySearchHandlerV4.kt b/app/src/main/java/com/kunzisoft/keepass/database/search/EntrySearchHandlerV4.kt new file mode 100644 index 000000000..4b5d3b41b --- /dev/null +++ b/app/src/main/java/com/kunzisoft/keepass/database/search/EntrySearchHandlerV4.kt @@ -0,0 +1,103 @@ +/* + * 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.database.search + +import com.kunzisoft.keepass.database.NodeHandler +import com.kunzisoft.keepass.database.element.PwEntryV4 +import com.kunzisoft.keepass.database.iterator.EntrySearchStringIteratorV4 +import com.kunzisoft.keepass.utils.StringUtil +import com.kunzisoft.keepass.utils.UuidUtil + +import java.util.Date +import java.util.Locale + +class EntrySearchHandlerV4(private val mSearchParametersV4: SearchParametersV4, private val mListStorage: MutableList) : NodeHandler() { + + private var now: Date = Date() + + override fun operate(node: PwEntryV4): Boolean { + if (mSearchParametersV4.respectEntrySearchingDisabled && !node.isSearchingEnabled) { + return true + } + + if (mSearchParametersV4.excludeExpired && node.isExpires && now.after(node.expiryTime.date)) { + return true + } + + var term = mSearchParametersV4.searchString + if (mSearchParametersV4.ignoreCase) { + term = term.toLowerCase() + } + + if (searchStrings(node, term)) { + mListStorage.add(node) + return true + } + + if (mSearchParametersV4.searchInGroupNames) { + val parent = node.parent + if (parent != null) { + var groupName = parent.title + if (mSearchParametersV4.ignoreCase) { + groupName = groupName.toLowerCase() + } + + if (groupName.contains(term)) { + mListStorage.add(node) + return true + } + } + } + + if (searchID(node)) { + mListStorage.add(node) + return true + } + + return true + } + + private fun searchID(entry: PwEntryV4): Boolean { + if (mSearchParametersV4.searchInUUIDs) { + val hex = UuidUtil.toHexString(entry.id) + return StringUtil.indexOfIgnoreCase(hex, mSearchParametersV4.searchString, Locale.ENGLISH) >= 0 + } + + return false + } + + private fun searchStrings(entry: PwEntryV4, term: String): Boolean { + val iterator = EntrySearchStringIteratorV4(entry, mSearchParametersV4) + while (iterator.hasNext()) { + var str = iterator.next() + if (str.isNotEmpty()) { + if (mSearchParametersV4.ignoreCase) { + str = str.toLowerCase() + } + + if (str.contains(term)) { + return true + } + } + } + + return false + } +} diff --git a/app/src/main/java/com/kunzisoft/keepass/database/search/SearchDbHelper.kt b/app/src/main/java/com/kunzisoft/keepass/database/search/SearchDbHelper.kt index 422572359..a963eae38 100644 --- a/app/src/main/java/com/kunzisoft/keepass/database/search/SearchDbHelper.kt +++ b/app/src/main/java/com/kunzisoft/keepass/database/search/SearchDbHelper.kt @@ -60,10 +60,10 @@ class SearchDbHelper(private val isOmitBackup: Boolean) { } }, object : NodeHandler() { - override fun operate(group: GroupVersioned): Boolean { + override fun operate(node: GroupVersioned): Boolean { return when { incrementEntry >= max -> false - database.isGroupSearchable(group, isOmitBackup) -> true + database.isGroupSearchable(node, isOmitBackup) -> true else -> incrementEntry < max } }