From eb6d76800cab2d1501886be9be13b8ac771ecdcc Mon Sep 17 00:00:00 2001 From: Brian Pellin Date: Mon, 30 Oct 2017 22:07:22 -0500 Subject: [PATCH] Add working kdbxv4 write support --- .../com/keepassdroid/tests/database/Kdb4.java | 18 +- app/src/main/assets/test-kdbxv4.kdbx | Bin 0 -> 1957 bytes .../collections/VariantDictionary.java | 230 ++++++++++++------ .../crypto/PwStreamCipherFactory.java | 6 +- .../crypto/keyDerivation/KdfParameters.java | 11 + .../keepassdroid/database/PwDatabaseV4.java | 66 ++++- .../keepassdroid/database/PwDbHeaderV4.java | 15 +- .../database/load/ImporterV4.java | 9 +- .../database/save/PwDbHeaderOutputV4.java | 82 ++++++- .../save/PwDbInnerHeaderOutputV4.java | 74 ++++++ .../database/save/PwDbV4Output.java | 123 +++++++--- .../stream/HmacBlockOutputStream.java | 128 ++++++++++ .../keepassdroid/stream/MacOutputStream.java | 67 +++++ .../java/com/keepassdroid/utils/DateUtil.java | 4 + .../crypto/engines/ChaCha7539Engine.java | 146 +++++++++++ 15 files changed, 833 insertions(+), 146 deletions(-) create mode 100644 app/src/main/assets/test-kdbxv4.kdbx create mode 100644 app/src/main/java/com/keepassdroid/database/save/PwDbInnerHeaderOutputV4.java create mode 100644 app/src/main/java/com/keepassdroid/stream/HmacBlockOutputStream.java create mode 100644 app/src/main/java/com/keepassdroid/stream/MacOutputStream.java create mode 100644 app/src/main/java/org/spongycastle/crypto/engines/ChaCha7539Engine.java diff --git a/app/src/androidTest/java/com/keepassdroid/tests/database/Kdb4.java b/app/src/androidTest/java/com/keepassdroid/tests/database/Kdb4.java index 14214e1db..f37d02dcb 100644 --- a/app/src/androidTest/java/com/keepassdroid/tests/database/Kdb4.java +++ b/app/src/androidTest/java/com/keepassdroid/tests/database/Kdb4.java @@ -69,14 +69,22 @@ public class Kdb4 extends AndroidTestCase { } - public void testSaving() throws IOException, InvalidDBException, PwDbOutputException { + public void testSavingKDBXV3() throws IOException, InvalidDBException, PwDbOutputException { + testSaving("test.kdbx", "12345", "test-out.kdbx"); + } + + public void testSavingKDBXV4() throws IOException, InvalidDBException, PwDbOutputException { + testSaving("test-kdbxv4.kdbx", "1", "test-kdbxv4-out.kdbx"); + } + + private void testSaving(String inputFile, String password, String outputFile) throws IOException, InvalidDBException, PwDbOutputException { Context ctx = getContext(); AssetManager am = ctx.getAssets(); - InputStream is = am.open("test.kdbx", AssetManager.ACCESS_STREAMING); + InputStream is = am.open(inputFile, AssetManager.ACCESS_STREAMING); ImporterV4 importer = new ImporterV4(); - PwDatabaseV4 db = importer.openDatabase(is, "12345", null); + PwDatabaseV4 db = importer.openDatabase(is, password, null); is.close(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); @@ -86,12 +94,12 @@ public class Kdb4 extends AndroidTestCase { byte[] data = bos.toByteArray(); - FileOutputStream fos = new FileOutputStream(TestUtil.getSdPath("test-out.kdbx"), false); + FileOutputStream fos = new FileOutputStream(TestUtil.getSdPath(outputFile), false); InputStream bis = new ByteArrayInputStream(data); bis = new CopyInputStream(bis, fos); importer = new ImporterV4(); - db = importer.openDatabase(bis, "12345", null); + db = importer.openDatabase(bis, password, null); bis.close(); fos.close(); diff --git a/app/src/main/assets/test-kdbxv4.kdbx b/app/src/main/assets/test-kdbxv4.kdbx new file mode 100644 index 0000000000000000000000000000000000000000..092d9beeb1487ed678671350434685a64969518a GIT binary patch literal 1957 zcmV;W2U_?8*`k_f`%AR|00aO65C8xGF~RcYzi~rQzE}kzYW!ON0|Wp70096100bZa z004q>aR|#+Et3bZd5d#Sc5koawLYQSgq>4lK$q4uvdjyM000000YU`;001OaRY^n; z0002*V{PAzDMU+=_o<`<;|dG}0RR91Rs;Y5022TJ00jX6002n{000020000000005 z0RR91O$Y!00000G0000000aR5002+~000020000&0RR91Qy>5U08#&sV6CD5wF@Eo zDFcgTKsR3A*D}B@a&ZcTFAO-*cBJSEj z8-7Sm@-%0MnXsqS4rYFI(7us(`O%S|YrcKU1KfDaBeBL#;$T$^yn1NmAnC>Gd5XCQ z4yXo})F1yuP_qy-*Cn-3pMw3b)-ikJjO)$&Owd}7HhMgODiz-zqU75in0MdDe|Y)hixrB{X*i0GPkC|!u^D=M)@lF5F)$B9umPsNCVhL@hbqR~5?p|Ty9E;8_7~)UyE5+w8-t`8 zFpgNJwnYaGWT}2!qHw}NX1~HAo80L7dT84JwSRE$IbA}++o_`cuT`u^U>eGDMJ=gY z4GU^#C(t*}{T#H_>&Q#TZ(PmIE1>Znsi+|ddi|~t1dk#r(ZelQ)(mYdspa%`lLsGZ zEcm*9RIHXtw%T!C-tQKY4y%kLyy71jmW6H#kfbM<4iV-XQvB#x1^Ek zLPG4MBY#(M=?#>aBVlmP%1U8cp*C`drg~f6(kA@!gpdysTxKW+rm(Rpv{S(ndp&e` zn7*qM>p38@oD0T)YvzNmC<*&vfg6D@fI9GyLj_qh+L5!BGgo6fSNP68wl(=vHg~`n!N^{Jqr(lL3Ji*T|rI6kY znv@Y9+K3UvkNT#(vi67$ZPE=Y6H@$YTOO%(;IgopwSwo=YLDTcnKp*cAVad*TeC#2 zeWNJD8w?4N@I0?=hNHGi^&(?Fj0nIfIpgqPmp2^HB|=`2^L=-kM2BsPc+}PyrgM5{ zwtRH{h$HF!VP=b0!fXwwn}0$D6|z8(HsI7!H^I-?E@f<8VMW9C2(pWktZB2bswxY# z3eq575ykyK_hMtTMB4Hpqcu&^tEOPW=5cxpz}QQa$g-JlY~rmJ`h(m@x((R$#omqD z3}oTb_(si{x{f0-DV3FSjmwktV>1FzYquw8r^^Aq7cL0LiO$M zYbdc9p0O{Wt+iqPA_0e5PqT8I%FD%wT%^pzxlk<7Yf+!^O)~mtP9znvqoLQldOPyy zRk$>OZp;Q(Jxucf)ZV2?5X$xZ2$qBEI@A4er!W)|3jqR6rR|vxl%?;ndVnKa$Nsj} zyeYOV@ljXeUrY0BBTt*dr7aB}&2QY+RF$Wa<8vwd2xsx}r2d_Fk{?lzKf0RqQ^^VY zJTZ95b2$tq^LyJfXijJYF)eZK21`O$#R)X?R$Y~QmYBU{VsNi!D)?}r?SdK_9v%CD zY~bwOe1bqvZpxX!l&O`7?vo@GfJm$~UK7pORKf`e%XZ%1okg>yp6;%8$35D&iNt2- zqJoF`Cj|L?Q0b$msxD<`li`-L9V4NpA;-1|Pki}&HU;P28BIeApFxUdoD!F%zGPGW zSTD_Ig1$u!g=gE-q0DDiW9rR0P4j8)YX43V*_4&v!#&7G;Jv_(SySGfg&_*x7s`ZI zvuyCskbrUbIS`yPbzx(ou}NlRZ@GmQUuBW%qqg_w3%uJkBR_sXDD(|}x?CVKm)q&y zONUHqMJg7$Rs6UC`f#FtZtz7_&%`m42O=l~z*l^kwK$@E!K|kwSH<-NdG2m*Vp7mz zVoOPUu7MY%J^F#|`FDB-DR*}CMum-E0zvoRvdbeSn=fm51EEcBBcHRn+n<ujcbdn%fjI+qIsbw0`Q~pC_13QY|Fiu6Hpf@W4PqyR000000ydaz literal 0 HcmV?d00001 diff --git a/app/src/main/java/com/keepassdroid/collections/VariantDictionary.java b/app/src/main/java/com/keepassdroid/collections/VariantDictionary.java index adf3ecb36..473dce2a3 100644 --- a/app/src/main/java/com/keepassdroid/collections/VariantDictionary.java +++ b/app/src/main/java/com/keepassdroid/collections/VariantDictionary.java @@ -20,8 +20,10 @@ package com.keepassdroid.collections; import com.keepassdroid.stream.LEDataInputStream; +import com.keepassdroid.stream.LEDataOutputStream; import java.io.IOException; +import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -31,64 +33,60 @@ public class VariantDictionary { private static final int VdmCritical = 0xFF00; private static final int VdmInfo = 0x00FF; - private Map dict = new HashMap(); + private Map dict = new HashMap(); - private enum VdType { - None(0x00), - UInt32(0x04), - UInt64(0x05), - Bool(0x08), - Int32(0x0C), - Int64(0x0D), - String(0x18), - ByteArray(0x42); + private class VdType { + public static final byte None = 0x00; + public static final byte UInt32 = 0x04; + public static final byte UInt64 =0x05; + public static final byte Bool =0x08; + public static final byte Int32 =0x0C; + public static final byte Int64 =0x0D; + public static final byte String =0x18; + public static final byte ByteArray =0x42; + public final byte type; + public final Object value; - private final byte value; - - VdType(int value) { - this.value = (byte) value; + VdType(byte type, Object value) { + this.type = type; + this.value = value; } - boolean equals(byte type) { - return type == value; + } + + private Object getValue(String name) { + VdType val = dict.get(name); + if (val == null) { + return null; } - byte getValue() { - return value; - } + return val.value; + } + private void putType(byte type, String name, Object value) { + dict.put(name, new VdType(type, value)); } - public void setUInt32(String name, long value) { - dict.put(name, value); - } - public long getUInt32(String name) { return (long)dict.get(name); } + public void setUInt32(String name, long value) { putType(VdType.UInt32, name, value); } + public long getUInt32(String name) { return (long)dict.get(name).value; } - public void setUInt64(String name, long value) { - dict.put(name, value); - } - public long getUInt64(String name) { return (long)dict.get(name); } + public void setUInt64(String name, long value) { putType(VdType.UInt64, name, value); } + public long getUInt64(String name) { return (long)dict.get(name).value; } - public void setBool(String name, boolean value) { - dict.put(name, value); - } + public void setBool(String name, boolean value) { putType(VdType.Bool, name, value); } + public boolean getBool(String name) { return (boolean)dict.get(name).value; } - public void setInt32(String name, int value) { - dict.put(name, value); - } + public void setInt32(String name, int value) { putType(VdType.Int32 ,name, value); } + public int getInt32(String name) { return (int)dict.get(name).value; } - public void setInt64(String name, long value) { - dict.put(name, value); - } + public void setInt64(String name, long value) { putType(VdType.Int64 ,name, value); } + public long getInt64(String name) { return (long)dict.get(name).value; } - public void setString(String name, String value) { - dict.put(name, value); - } + public void setString(String name, String value) { putType(VdType.String ,name, value); } + public String getString(String name) { return (String)getValue(name); } - public void setByteArray(String name, byte[] value) { - dict.put(name, value); - } - public byte[] getByteArray(String name) { return (byte[])dict.get(name); } + public void setByteArray(String name, byte[] value) { putType(VdType.ByteArray, name, value); } + public byte[] getByteArray(String name) { return (byte[])getValue(name); } public static VariantDictionary deserialize(LEDataInputStream lis) throws IOException { VariantDictionary d = new VariantDictionary(); @@ -105,7 +103,7 @@ public class VariantDictionary { } byte bType = (byte)type; - if (VdType.None.equals(bType)) { + if (bType == VdType.None) { break; } @@ -122,51 +120,125 @@ public class VariantDictionary { throw new IOException("Invalid format"); } - if (VdType.UInt32.equals(bType)) { - if (valueLen == 4) { - d.setUInt32(name, LEDataInputStream.readUInt(valueBuf, 0)); - } - } - else if (VdType.UInt64.equals(bType)) { - if (valueLen == 8) { - d.setUInt64(name, LEDataInputStream.readLong(valueBuf, 0)); - } - } - else if (VdType.Bool.equals(bType)) { - if (valueLen == 1) { - d.setBool(name, valueBuf[0] != 0); - } - } - else if (VdType.Int32.equals(bType)) { - if (valueLen == 4) { - d.setInt32(name, LEDataInputStream.readInt(valueBuf, 0)); - } - } - else if (VdType.Int64.equals(bType)) { - if (valueLen == 8) { - d.setInt64(name, LEDataInputStream.readLong(valueBuf, 0)); - } - } - else if (VdType.String.equals(bType)) { - d.setString(name, new String(valueBuf, "UTF-8")); - } - else if (VdType.ByteArray.equals(bType)) { - d.setByteArray(name, valueBuf); - } - else { - assert(false); + switch (bType) { + case VdType.UInt32: + if (valueLen == 4) { + d.setUInt32(name, LEDataInputStream.readUInt(valueBuf, 0)); + } + break; + case VdType.UInt64: + if (valueLen == 8) { + d.setUInt64(name, LEDataInputStream.readLong(valueBuf, 0)); + } + break; + case VdType.Bool: + if (valueLen == 1) { + d.setBool(name, valueBuf[0] != 0); + } + break; + case VdType.Int32: + if (valueLen == 4) { + d.setInt32(name, LEDataInputStream.readInt(valueBuf, 0)); + } + break; + case VdType.Int64: + if (valueLen == 8) { + d.setInt64(name, LEDataInputStream.readLong(valueBuf, 0)); + } + break; + case VdType.String: + d.setString(name, new String(valueBuf, "UTF-8")); + break; + case VdType.ByteArray: + d.setByteArray(name, valueBuf); + break; + default: + assert (false); + break; } } return d; } + public static void serialize(VariantDictionary d, LEDataOutputStream los) throws IOException{ + if (los == null) { + assert(false); + return; + } + + los.writeUShort(VdVersion); + + for (Map.Entry entry: d.dict.entrySet()) { + String name = entry.getKey(); + byte[] nameBuf = null; + try { + nameBuf = name.getBytes("UTF-8"); + } catch (UnsupportedEncodingException e) { + assert(false); + throw new IOException("Couldn't encode parameter name."); + } + + VdType vd = entry.getValue(); + + los.write(vd.type); + los.writeInt(nameBuf.length); + los.write(nameBuf); + + byte[] buf; + switch (vd.type) { + case VdType.UInt32: + los.writeInt(4); + los.writeUInt((long)vd.value); + break; + case VdType.UInt64: + los.writeInt(8); + los.writeLong((long)vd.value); + break; + case VdType.Bool: + los.writeInt(1); + byte bool = (boolean)vd.value ? (byte)1 : (byte)0; + los.write(bool); + break; + case VdType.Int32: + los.writeInt(4); + los.writeInt((int)vd.value); + break; + case VdType.Int64: + los.writeInt(8); + los.writeLong((long)vd.value); + break; + case VdType.String: + String value = (String)vd.value; + buf = value.getBytes("UTF-8"); + los.writeInt(buf.length); + los.write(buf); + break; + case VdType.ByteArray: + buf = (byte[])vd.value; + los.writeInt(buf.length); + los.write(buf); + break; + default: + assert(false); + break; + } + } + + los.write(VdType.None); + + } + public void copyTo(VariantDictionary d) { - for (Map.Entry entry : d.dict.entrySet()) { + for (Map.Entry entry : d.dict.entrySet()) { String key = entry.getKey(); - Object value = entry.getValue(); + VdType value = entry.getValue(); dict.put(key, value); } } +; + public int size() { + return dict.size(); + } } diff --git a/app/src/main/java/com/keepassdroid/crypto/PwStreamCipherFactory.java b/app/src/main/java/com/keepassdroid/crypto/PwStreamCipherFactory.java index b4c776f48..66e792c3e 100644 --- a/app/src/main/java/com/keepassdroid/crypto/PwStreamCipherFactory.java +++ b/app/src/main/java/com/keepassdroid/crypto/PwStreamCipherFactory.java @@ -20,7 +20,7 @@ package com.keepassdroid.crypto; import org.spongycastle.crypto.StreamCipher; -import org.spongycastle.crypto.engines.ChaChaEngine; +import org.spongycastle.crypto.engines.ChaCha7539Engine; import org.spongycastle.crypto.engines.Salsa20Engine; import org.spongycastle.crypto.params.KeyParameter; import org.spongycastle.crypto.params.ParametersWithIV; @@ -65,9 +65,9 @@ public class PwStreamCipherFactory { System.arraycopy(hash, 32, iv, 0, 12); KeyParameter keyParam = new KeyParameter(key32); - ParametersWithIV ivParam = new ParametersWithIV(keyParam, SALSA_IV); + ParametersWithIV ivParam = new ParametersWithIV(keyParam, iv); - StreamCipher cipher = new ChaChaEngine(); + StreamCipher cipher = new ChaCha7539Engine(); cipher.init(true, ivParam); return cipher; diff --git a/app/src/main/java/com/keepassdroid/crypto/keyDerivation/KdfParameters.java b/app/src/main/java/com/keepassdroid/crypto/keyDerivation/KdfParameters.java index c3f9fe201..9befdd1d9 100644 --- a/app/src/main/java/com/keepassdroid/crypto/keyDerivation/KdfParameters.java +++ b/app/src/main/java/com/keepassdroid/crypto/keyDerivation/KdfParameters.java @@ -21,9 +21,11 @@ package com.keepassdroid.crypto.keyDerivation; import com.keepassdroid.collections.VariantDictionary; import com.keepassdroid.stream.LEDataInputStream; +import com.keepassdroid.stream.LEDataOutputStream; import com.keepassdroid.utils.Types; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.UUID; @@ -59,4 +61,13 @@ public class KdfParameters extends VariantDictionary { } + public static byte[] serialize(KdfParameters kdf) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + LEDataOutputStream los = new LEDataOutputStream(bos); + + KdfParameters.serialize(kdf, los); + + return bos.toByteArray(); + } + } diff --git a/app/src/main/java/com/keepassdroid/database/PwDatabaseV4.java b/app/src/main/java/com/keepassdroid/database/PwDatabaseV4.java index 1baa0a8be..a470191ec 100644 --- a/app/src/main/java/com/keepassdroid/database/PwDatabaseV4.java +++ b/app/src/main/java/com/keepassdroid/database/PwDatabaseV4.java @@ -24,6 +24,7 @@ import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.acl.Group; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; @@ -101,7 +102,7 @@ public class PwDatabaseV4 extends PwDatabase { public List customIcons = new ArrayList(); public Map customData = new HashMap(); public KdfParameters kdfParameters = KdfFactory.getDefaultParameters(); - public VariantDictionary publicCustomData; + public VariantDictionary publicCustomData = new VariantDictionary(); public String localizedAppName = "KeePassDroid"; @@ -459,4 +460,67 @@ public class PwDatabaseV4 extends PwDatabase { return filename.substring(0, lastExtDot); } + + private class GroupHasCustomData extends GroupHandler { + + public boolean hasCustomData = false; + + @Override + public boolean operate(PwGroup group) { + if (group == null) { + return true; + } + PwGroupV4 g4 = (PwGroupV4) group; + if (g4.customData.size() > 0) { + hasCustomData = true; + return false; + } + + return true; + } + } + + private class EntryHasCustomData extends EntryHandler { + + public boolean hasCustomData = false; + + @Override + public boolean operate(PwEntry entry) { + if (entry == null) { + return true; + } + + PwEntryV4 e4 = (PwEntryV4)entry; + if (e4.customData.size() > 0) { + hasCustomData = true; + return false; + } + + return true; + } + } + + public int getMinKdbxVersion() { + if (!AesKdf.CIPHER_UUID.equals(kdfParameters.kdfUUID)) { + return PwDbHeaderV4.FILE_VERSION_32; + } + + if (publicCustomData.size() > 0) { + return PwDbHeaderV4.FILE_VERSION_32; + } + + EntryHasCustomData entryHandler = new EntryHasCustomData(); + GroupHasCustomData groupHandler = new GroupHasCustomData(); + + if (rootGroup == null ) { + return PwDbHeaderV4.FILE_VERSION_32_3; + } + rootGroup.preOrderTraverseTree(groupHandler, entryHandler); + if (groupHandler.hasCustomData || entryHandler.hasCustomData) { + return PwDbHeaderV4.FILE_VERSION_32; + } + + return PwDbHeaderV4.FILE_VERSION_32_3; + } + } \ No newline at end of file diff --git a/app/src/main/java/com/keepassdroid/database/PwDbHeaderV4.java b/app/src/main/java/com/keepassdroid/database/PwDbHeaderV4.java index 3c25ae259..eb8eb619e 100644 --- a/app/src/main/java/com/keepassdroid/database/PwDbHeaderV4.java +++ b/app/src/main/java/com/keepassdroid/database/PwDbHeaderV4.java @@ -22,14 +22,18 @@ package com.keepassdroid.database; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.OutputStream; import java.security.DigestInputStream; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.List; import com.keepassdroid.crypto.keyDerivation.AesKdf; import com.keepassdroid.crypto.keyDerivation.KdfParameters; import com.keepassdroid.database.exception.InvalidDBVersionException; +import com.keepassdroid.database.security.ProtectedBinary; import com.keepassdroid.stream.CopyInputStream; import com.keepassdroid.stream.HmacBlockStream; import com.keepassdroid.stream.LEDataInputStream; @@ -87,14 +91,15 @@ public class PwDbHeaderV4 extends PwDbHeader { } private PwDatabaseV4 db; - public byte[] protectedStreamKey = new byte[32]; + public byte[] innerRandomStreamKey = new byte[32]; public byte[] streamStartBytes = new byte[32]; public CrsAlgorithm innerRandomStream; public long version; + public List binaries = new ArrayList(); public PwDbHeaderV4(PwDatabaseV4 d) { db = d; - + version = d.getMinKdbxVersion(); masterSeed = new byte[32]; } @@ -198,7 +203,7 @@ public class PwDbHeaderV4 extends PwDbHeader { case PwDbHeaderV4Fields.InnerRandomstreamKey: assert(version < PwDbHeaderV4.FILE_VERSION_32_4); - protectedStreamKey = fieldData; + innerRandomStreamKey = fieldData; break; case PwDbHeaderV4Fields.StreamStartBytes: @@ -310,10 +315,6 @@ public class PwDbHeaderV4 extends PwDbHeader { return hmac.doFinal(header); } - public void setMinimumVersion() { - - } - public byte[] getTransformSeed() { assert(version < FILE_VERSION_32_4); diff --git a/app/src/main/java/com/keepassdroid/database/load/ImporterV4.java b/app/src/main/java/com/keepassdroid/database/load/ImporterV4.java index b52d7a587..cedffb36b 100644 --- a/app/src/main/java/com/keepassdroid/database/load/ImporterV4.java +++ b/app/src/main/java/com/keepassdroid/database/load/ImporterV4.java @@ -40,7 +40,6 @@ import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import org.spongycastle.crypto.StreamCipher; -import org.spongycastle.util.encoders.Base64Encoder; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; @@ -52,7 +51,6 @@ import com.keepassdroid.crypto.CipherFactory; import com.keepassdroid.crypto.PwStreamCipherFactory; import com.keepassdroid.crypto.engine.CipherEngine; import com.keepassdroid.database.BinaryPool; -import com.keepassdroid.database.CrsAlgorithm; import com.keepassdroid.database.ITimeLogger; import com.keepassdroid.database.PwCompressionAlgorithm; import com.keepassdroid.database.PwDatabaseV4; @@ -111,6 +109,7 @@ public class ImporterV4 extends Importer { db = createDB(); PwDbHeaderV4 header = new PwDbHeaderV4(db); + header.binaries.clear(); PwDbHeaderV4.HeaderAndHash hh = header.loadFromFile(inStream); version = header.version; @@ -192,12 +191,12 @@ public class ImporterV4 extends Importer { LoadInnerHeader(isXml, header); } - if ( header.protectedStreamKey == null ) { + if ( header.innerRandomStreamKey == null ) { assert(false); throw new IOException("Invalid stream key."); } - randomStream = PwStreamCipherFactory.getInstance(header.innerRandomStream, header.protectedStreamKey); + randomStream = PwStreamCipherFactory.getInstance(header.innerRandomStream, header.innerRandomStreamKey); if ( randomStream == null ) { throw new ArcFourException(); @@ -243,7 +242,7 @@ public class ImporterV4 extends Importer { header.setRandomStreamID(data); break; case PwDbHeaderV4.PwDbInnerHeaderV4Fields.InnerRandomstreamKey: - header.protectedStreamKey = data; + header.innerRandomStreamKey = data; break; case PwDbHeaderV4.PwDbInnerHeaderV4Fields.Binary: if (data.length < 1) throw new IOException("Invalid binary format"); diff --git a/app/src/main/java/com/keepassdroid/database/save/PwDbHeaderOutputV4.java b/app/src/main/java/com/keepassdroid/database/save/PwDbHeaderOutputV4.java index 548b120a9..a7d51359e 100644 --- a/app/src/main/java/com/keepassdroid/database/save/PwDbHeaderOutputV4.java +++ b/app/src/main/java/com/keepassdroid/database/save/PwDbHeaderOutputV4.java @@ -19,44 +19,74 @@ */ package com.keepassdroid.database.save; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.DigestOutputStream; +import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import com.keepassdroid.collections.VariantDictionary; +import com.keepassdroid.crypto.keyDerivation.KdfParameters; import com.keepassdroid.database.PwDatabaseV4; import com.keepassdroid.database.PwDbHeader; import com.keepassdroid.database.PwDbHeaderV4; import com.keepassdroid.database.PwDbHeaderV4.PwDbHeaderV4Fields; import com.keepassdroid.database.exception.PwDbOutputException; +import com.keepassdroid.stream.HmacBlockStream; import com.keepassdroid.stream.LEDataOutputStream; +import com.keepassdroid.stream.MacOutputStream; import com.keepassdroid.utils.Types; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + public class PwDbHeaderOutputV4 extends PwDbHeaderOutput { private PwDbHeaderV4 header; private LEDataOutputStream los; + private MacOutputStream mos; private DigestOutputStream dos; private PwDatabaseV4 db; + public byte[] headerHmac; private static byte[] EndHeaderValue = {'\r', '\n', '\r', '\n'}; public PwDbHeaderOutputV4(PwDatabaseV4 d, PwDbHeaderV4 h, OutputStream os) throws PwDbOutputException { db = d; header = h; - + MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new PwDbOutputException("SHA-256 not implemented here."); } - + + try { + d.makeFinalKey(header.masterSeed, d.kdfParameters); + } catch (IOException e) { + throw new PwDbOutputException(e); + } + + Mac hmac; + try { + hmac = Mac.getInstance("HmacSHA256"); + SecretKeySpec signingKey = new SecretKeySpec(HmacBlockStream.GetHmacKey64(db.hmacKey, Types.ULONG_MAX_VALUE), "HmacSHA256"); + hmac.init(signingKey); + } catch (NoSuchAlgorithmException e) { + throw new PwDbOutputException(e); + } catch (InvalidKeyException e) { + throw new PwDbOutputException(e); + } + dos = new DigestOutputStream(os, md); - los = new LEDataOutputStream(dos); + mos = new MacOutputStream(dos, hmac); + los = new LEDataOutputStream(mos); } public void output() throws IOException { + los.writeUInt(PwDbHeader.PWM_DBSIG_1); los.writeUInt(PwDbHeaderV4.DBSIG_2); los.writeUInt(header.version); @@ -65,16 +95,36 @@ public class PwDbHeaderOutputV4 extends PwDbHeaderOutput { writeHeaderField(PwDbHeaderV4Fields.CipherID, Types.UUIDtoBytes(db.dataCipher)); writeHeaderField(PwDbHeaderV4Fields.CompressionFlags, LEDataOutputStream.writeIntBuf(db.compressionAlgorithm.id)); writeHeaderField(PwDbHeaderV4Fields.MasterSeed, header.masterSeed); - writeHeaderField(PwDbHeaderV4Fields.TransformSeed, header.getTransformSeed()); - writeHeaderField(PwDbHeaderV4Fields.TransformRounds, LEDataOutputStream.writeLongBuf(db.numKeyEncRounds)); - writeHeaderField(PwDbHeaderV4Fields.EncryptionIV, header.encryptionIV); - writeHeaderField(PwDbHeaderV4Fields.InnerRandomstreamKey, header.protectedStreamKey); - writeHeaderField(PwDbHeaderV4Fields.StreamStartBytes, header.streamStartBytes); - writeHeaderField(PwDbHeaderV4Fields.InnerRandomStreamID, LEDataOutputStream.writeIntBuf(header.innerRandomStream.id)); + + if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { + writeHeaderField(PwDbHeaderV4Fields.TransformSeed, header.getTransformSeed()); + writeHeaderField(PwDbHeaderV4Fields.TransformRounds, LEDataOutputStream.writeLongBuf(db.numKeyEncRounds)); + } else { + writeHeaderField(PwDbHeaderV4Fields.KdfParameters, KdfParameters.serialize(db.kdfParameters)); + } + + if (header.encryptionIV.length > 0) { + writeHeaderField(PwDbHeaderV4Fields.EncryptionIV, header.encryptionIV); + } + + if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { + writeHeaderField(PwDbHeaderV4Fields.InnerRandomstreamKey, header.innerRandomStreamKey); + writeHeaderField(PwDbHeaderV4Fields.StreamStartBytes, header.streamStartBytes); + writeHeaderField(PwDbHeaderV4Fields.InnerRandomStreamID, LEDataOutputStream.writeIntBuf(header.innerRandomStream.id)); + } + + if (db.publicCustomData.size() > 0) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + LEDataOutputStream los = new LEDataOutputStream(bos); + VariantDictionary.serialize(db.publicCustomData, los); + writeHeaderField(PwDbHeaderV4Fields.PublicCustomData, bos.toByteArray()); + } + writeHeaderField(PwDbHeaderV4Fields.EndOfHeader, EndHeaderValue); los.flush(); hashOfHeader = dos.getMessageDigest().digest(); + headerHmac = mos.getMac(); } private void writeHeaderField(byte fieldId, byte[] pbData) throws IOException { @@ -82,11 +132,19 @@ public class PwDbHeaderOutputV4 extends PwDbHeaderOutput { los.write(fieldId); if (pbData != null) { - los.writeUShort(pbData.length); + writeHeaderFieldSize(pbData.length); los.write(pbData); } else { - los.writeUShort(0); + writeHeaderFieldSize(0); } } - + + private void writeHeaderFieldSize(int size) throws IOException { + if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { + los.writeUShort(size); + } else { + los.writeInt(size); + } + + } } diff --git a/app/src/main/java/com/keepassdroid/database/save/PwDbInnerHeaderOutputV4.java b/app/src/main/java/com/keepassdroid/database/save/PwDbInnerHeaderOutputV4.java new file mode 100644 index 000000000..19a90b608 --- /dev/null +++ b/app/src/main/java/com/keepassdroid/database/save/PwDbInnerHeaderOutputV4.java @@ -0,0 +1,74 @@ +/* + * Copyright 2017 Brian Pellin. + * + * This file is part of KeePassDroid. + * + * KeePassDroid 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 2 of the License, or + * (at your option) any later version. + * + * KeePassDroid 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 KeePassDroid. If not, see . + * + */ +package com.keepassdroid.database.save; + +import com.keepassdroid.database.PwDatabaseV4; +import com.keepassdroid.database.PwDbHeaderV4; +import com.keepassdroid.database.PwDbHeaderV4.PwDbInnerHeaderV4Fields; +import com.keepassdroid.database.PwDbHeaderV4.KdbxBinaryFlags; +import com.keepassdroid.database.security.ProtectedBinary; +import com.keepassdroid.stream.LEDataOutputStream; + +import java.io.IOException; +import java.io.OutputStream; +import java.util.Arrays; + +public class PwDbInnerHeaderOutputV4 { + private PwDatabaseV4 db; + private PwDbHeaderV4 header; + private LEDataOutputStream los; + + public PwDbInnerHeaderOutputV4(PwDatabaseV4 db, PwDbHeaderV4 header, OutputStream os) { + this.db = db; + this.header = header; + + this.los = new LEDataOutputStream(os); + } + + public void output() throws IOException { + los.write(PwDbInnerHeaderV4Fields.InnerRandomStreamID); + los.writeInt(4); + los.writeInt(header.innerRandomStream.id); + + int streamKeySize = header.innerRandomStreamKey.length; + los.write(PwDbInnerHeaderV4Fields.InnerRandomstreamKey); + los.writeInt(streamKeySize); + los.write(header.innerRandomStreamKey); + + for (ProtectedBinary bin : header.binaries) { + byte flag = KdbxBinaryFlags.None; + if (bin.isProtected()) { + flag |= KdbxBinaryFlags.Protected; + } + + byte[] binData = bin.getData(); + los.write(PwDbInnerHeaderV4Fields.Binary); + los.writeInt(bin.length() + 1); + los.write(flag); + los.write(binData); + + Arrays.fill(binData, (byte)0); + } + + los.write(PwDbInnerHeaderV4Fields.EndOfHeader); + los.writeInt(0); + } + +} diff --git a/app/src/main/java/com/keepassdroid/database/save/PwDbV4Output.java b/app/src/main/java/com/keepassdroid/database/save/PwDbV4Output.java index dd6e36e18..333ce5522 100644 --- a/app/src/main/java/com/keepassdroid/database/save/PwDbV4Output.java +++ b/app/src/main/java/com/keepassdroid/database/save/PwDbV4Output.java @@ -23,6 +23,7 @@ import static com.keepassdroid.database.PwDatabaseV4XML.*; import java.io.IOException; import java.io.OutputStream; +import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Date; import java.util.List; @@ -35,6 +36,7 @@ import java.util.zip.GZIPOutputStream; import javax.crypto.Cipher; import javax.crypto.CipherOutputStream; +import org.joda.time.DateTime; import org.spongycastle.crypto.StreamCipher; import org.xmlpull.v1.XmlSerializer; @@ -69,6 +71,9 @@ import com.keepassdroid.database.exception.PwDbOutputException; import com.keepassdroid.database.security.ProtectedBinary; import com.keepassdroid.database.security.ProtectedString; import com.keepassdroid.stream.HashedBlockOutputStream; +import com.keepassdroid.stream.HmacBlockOutputStream; +import com.keepassdroid.stream.LEDataOutputStream; +import com.keepassdroid.utils.DateUtil; import com.keepassdroid.utils.EmptyUtils; import com.keepassdroid.utils.MemUtil; import com.keepassdroid.utils.Types; @@ -81,7 +86,9 @@ public class PwDbV4Output extends PwDbOutput { private XmlSerializer xml; private PwDbHeaderV4 header; private byte[] hashOfHeader; - + private byte[] headerHmac; + private CipherEngine engine = null; + protected PwDbV4Output(PwDatabaseV4 pm, OutputStream os) { super(os); @@ -91,30 +98,53 @@ public class PwDbV4Output extends PwDbOutput { @Override public void output() throws PwDbOutputException { - - header = (PwDbHeaderV4) outputHeader(mOS); - - CipherOutputStream cos = attachStreamEncryptor(header, mOS); - - OutputStream compressed; - try { - cos.write(header.streamStartBytes); - - HashedBlockOutputStream hashed = new HashedBlockOutputStream(cos); - - if ( mPM.compressionAlgorithm == PwCompressionAlgorithm.Gzip ) { - compressed = new GZIPOutputStream(hashed); - } else { - compressed = hashed; + try { + try { + engine = CipherFactory.getInstance(mPM.dataCipher); + } catch (NoSuchAlgorithmException e) { + throw new PwDbOutputException("No such cipher", e); } - - outputDatabase(compressed); - compressed.close(); - } catch (IllegalArgumentException e) { - throw new PwDbOutputException(e); - } catch (IllegalStateException e) { - throw new PwDbOutputException(e); + header = (PwDbHeaderV4) outputHeader(mOS); + + OutputStream osPlain; + if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { + CipherOutputStream cos = attachStreamEncryptor(header, mOS); + cos.write(header.streamStartBytes); + + HashedBlockOutputStream hashed = new HashedBlockOutputStream(cos); + osPlain = hashed; + } else { + mOS.write(hashOfHeader); + mOS.write(headerHmac); + + HmacBlockOutputStream hbos = new HmacBlockOutputStream(mOS, mPM.hmacKey); + osPlain = attachStreamEncryptor(header, hbos); + } + + OutputStream osXml; + try { + + + if (mPM.compressionAlgorithm == PwCompressionAlgorithm.Gzip) { + osXml = new GZIPOutputStream(osPlain); + } else { + osXml = osPlain; + } + + if (header.version >= PwDbHeaderV4.FILE_VERSION_32_4) { + PwDbInnerHeaderOutputV4 ihOut = new PwDbInnerHeaderOutputV4((PwDatabaseV4)mPM, header, osXml); + ihOut.output(); + } + + + outputDatabase(osXml); + osXml.close(); + } catch (IllegalArgumentException e) { + throw new PwDbOutputException(e); + } catch (IllegalStateException e) { + throw new PwDbOutputException(e); + } } catch (IOException e) { throw new PwDbOutputException(e); } @@ -241,8 +271,10 @@ public class PwDbV4Output extends PwDbOutput { writeObject(ElemHistoryMaxSize, mPM.historyMaxSize); writeObject(ElemLastSelectedGroup, mPM.lastSelectedGroup); writeObject(ElemLastTopVisibleGroup, mPM.lastTopVisibleGroup); - - writeBinPool(); + + if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { + writeBinPool(); + } writeList(ElemCustomData, mPM.customData); xml.endTag(null, ElemMeta); @@ -251,11 +283,9 @@ public class PwDbV4Output extends PwDbOutput { private CipherOutputStream attachStreamEncryptor(PwDbHeaderV4 header, OutputStream os) throws PwDbOutputException { Cipher cipher; - CipherEngine engine; try { - mPM.makeFinalKey(header.masterSeed, header.getTransformSeed(), (int)mPM.numKeyEncRounds); + //mPM.makeFinalKey(header.masterSeed, mPM.kdfParameters); - engine = CipherFactory.getInstance(mPM.dataCipher); cipher = engine.getCipher(Cipher.ENCRYPT_MODE, mPM.finalKey, header.encryptionIV); } catch (Exception e) { throw new PwDbOutputException("Invalid algorithm.", e); @@ -272,19 +302,34 @@ public class PwDbV4Output extends PwDbOutput { PwDbHeaderV4 h = (PwDbHeaderV4) header; random.nextBytes(h.masterSeed); + + int ivLength = engine.ivLength(); + if (ivLength != h.encryptionIV.length) { + h.encryptionIV = new byte[ivLength]; + } random.nextBytes(h.encryptionIV); UUID kdfUUID = mPM.kdfParameters.kdfUUID; KdfEngine kdf = KdfFactory.get(kdfUUID); kdf.randomize(mPM.kdfParameters); - random.nextBytes(h.protectedStreamKey); - h.innerRandomStream = CrsAlgorithm.Salsa20; - randomStream = PwStreamCipherFactory.getInstance(h.innerRandomStream, h.protectedStreamKey); + if (h.version < PwDbHeaderV4.FILE_VERSION_32_4) { + h.innerRandomStream = CrsAlgorithm.Salsa20; + h.innerRandomStreamKey = new byte[32]; + } else { + h.innerRandomStream = CrsAlgorithm.ChaCha20; + h.innerRandomStreamKey = new byte[64]; + } + random.nextBytes(h.innerRandomStreamKey); + + randomStream = PwStreamCipherFactory.getInstance(h.innerRandomStream, h.innerRandomStreamKey); if (randomStream == null) { throw new PwDbOutputException("Invalid random cipher"); } - random.nextBytes(h.streamStartBytes); + + if ( h.version < PwDbHeaderV4.FILE_VERSION_32_4) { + random.nextBytes(h.streamStartBytes); + } return random; } @@ -293,7 +338,7 @@ public class PwDbV4Output extends PwDbOutput { public PwDbHeader outputHeader(OutputStream os) throws PwDbOutputException { PwDbHeaderV4 header = new PwDbHeaderV4(mPM); setIVs(header); - + PwDbHeaderOutputV4 pho = new PwDbHeaderOutputV4(mPM, header, os); try { pho.output(); @@ -302,6 +347,7 @@ public class PwDbV4Output extends PwDbOutput { } hashOfHeader = pho.getHashOfHeader(); + headerHmac = pho.headerHmac; return header; } @@ -433,7 +479,16 @@ public class PwDbV4Output extends PwDbOutput { } private void writeObject(String name, Date value) throws IllegalArgumentException, IllegalStateException, IOException { - writeObject(name, PwDatabaseV4XML.dateFormat.format(value)); + if (header.version < PwDbHeaderV4.FILE_VERSION_32_4) { + writeObject(name, PwDatabaseV4XML.dateFormat.format(value)); + } else { + DateTime dt = new DateTime(value); + long seconds = DateUtil.convertDateToKDBX4Time(dt); + byte[] buf = LEDataOutputStream.writeLongBuf(seconds); + String b64 = new String(Base64Coder.encode(buf)); + writeObject(name, b64); + } + } private void writeObject(String name, long value) throws IllegalArgumentException, IllegalStateException, IOException { diff --git a/app/src/main/java/com/keepassdroid/stream/HmacBlockOutputStream.java b/app/src/main/java/com/keepassdroid/stream/HmacBlockOutputStream.java new file mode 100644 index 000000000..b115ce5fc --- /dev/null +++ b/app/src/main/java/com/keepassdroid/stream/HmacBlockOutputStream.java @@ -0,0 +1,128 @@ +/* + * Copyright 2017 Brian Pellin. + * + * This file is part of KeePassDroid. + * + * KeePassDroid 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 2 of the License, or + * (at your option) any later version. + * + * KeePassDroid 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 KeePassDroid. If not, see . + * + */ +package com.keepassdroid.stream; + +import java.io.IOException; +import java.io.OutputStream; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +public class HmacBlockOutputStream extends OutputStream { + private static final int DEFAULT_BUFFER_SIZE = 1024 * 1024; + private LEDataOutputStream baseStream; + private byte[] key; + + private byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; + private int bufferPos = 0; + private long blockIndex = 0; + + public HmacBlockOutputStream(OutputStream os, byte[] key) { + this.baseStream = new LEDataOutputStream(os); + this.key = key; + } + + @Override + public void close() throws IOException { + if (bufferPos == 0) { + WriteSafeBlock(); + } else { + WriteSafeBlock(); + WriteSafeBlock(); + } + + baseStream.flush();; + baseStream.close(); + } + + @Override + public void flush() throws IOException { + baseStream.flush(); + } + + @Override + public void write(byte[] outBuffer) throws IOException { + write(outBuffer, 0, outBuffer.length); + } + + @Override + public void write(byte[] outBuffer, int offset, int count) throws IOException { + while (count > 0) { + if (bufferPos == buffer.length) { + WriteSafeBlock(); + } + + int copy = Math.min(buffer.length - bufferPos, count); + assert(copy > 0); + + System.arraycopy(outBuffer, offset, buffer, bufferPos, copy); + offset += copy; + bufferPos += copy; + + count -= copy; + } + } + + @Override + public void write(int oneByte) throws IOException { + byte[] outByte = new byte[1]; + write(outByte, 0, 1); + } + + private void WriteSafeBlock() throws IOException { + byte[] bufBlockIndex = LEDataOutputStream.writeLongBuf(blockIndex); + byte[] blockSizeBuf = LEDataOutputStream.writeIntBuf(bufferPos); + + byte[] blockHmac; + byte[] blockKey = HmacBlockStream.GetHmacKey64(key, blockIndex); + + Mac hmac; + try { + hmac = Mac.getInstance("HmacSHA256"); + SecretKeySpec signingKey = new SecretKeySpec(blockKey, "HmacSHA256"); + hmac.init(signingKey); + } catch (NoSuchAlgorithmException e) { + throw new IOException("Invalid Hmac"); + } catch (InvalidKeyException e) { + throw new IOException("Invalid HMAC"); + } + + hmac.update(bufBlockIndex); + hmac.update(blockSizeBuf); + + if (bufferPos > 0) { + hmac.update(buffer, 0, bufferPos); + } + + blockHmac = hmac.doFinal(); + + baseStream.write(blockHmac); + baseStream.write(blockSizeBuf); + + if (bufferPos > 0) { + baseStream.write(buffer, 0, bufferPos); + } + + blockIndex++; + bufferPos = 0; + } +} diff --git a/app/src/main/java/com/keepassdroid/stream/MacOutputStream.java b/app/src/main/java/com/keepassdroid/stream/MacOutputStream.java new file mode 100644 index 000000000..2d51fcfab --- /dev/null +++ b/app/src/main/java/com/keepassdroid/stream/MacOutputStream.java @@ -0,0 +1,67 @@ +/* + * Copyright 2017 Brian Pellin. + * + * This file is part of KeePassDroid. + * + * KeePassDroid 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 2 of the License, or + * (at your option) any later version. + * + * KeePassDroid 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 KeePassDroid. If not, see . + * + */ +package com.keepassdroid.stream; + +import java.io.IOException; +import java.io.OutputStream; + +import javax.crypto.Mac; + +public class MacOutputStream extends OutputStream { + private Mac mac; + private OutputStream os; + + public MacOutputStream(OutputStream os, Mac mac) { + this.mac = mac; + this.os = os; + } + + @Override + public void flush() throws IOException { + os.flush(); + } + + @Override + public void close() throws IOException { + os.close(); + } + + @Override + public void write(int oneByte) throws IOException { + mac.update((byte) oneByte); + os.write(oneByte); + } + + @Override + public void write(byte[] buffer, int offset, int count) throws IOException { + mac.update(buffer, offset, count); + os.write(buffer, offset, count); + } + + @Override + public void write(byte[] buffer) throws IOException { + mac.update(buffer, 0, buffer.length); + os.write(buffer); + } + + public byte[] getMac() { + return mac.doFinal(); + } +} diff --git a/app/src/main/java/com/keepassdroid/utils/DateUtil.java b/app/src/main/java/com/keepassdroid/utils/DateUtil.java index 84f9c12d3..da442af86 100644 --- a/app/src/main/java/com/keepassdroid/utils/DateUtil.java +++ b/app/src/main/java/com/keepassdroid/utils/DateUtil.java @@ -30,4 +30,8 @@ public class DateUtil { public static Date convertKDBX4Time(long seconds) { return dotNetEpoch.plus(seconds).toDate(); } + + public static long convertDateToKDBX4Time(DateTime dt) { + return (dt.getMillis() / 1000) - (dotNetEpoch.getMillis() / 1000); + } } diff --git a/app/src/main/java/org/spongycastle/crypto/engines/ChaCha7539Engine.java b/app/src/main/java/org/spongycastle/crypto/engines/ChaCha7539Engine.java new file mode 100644 index 000000000..677a537db --- /dev/null +++ b/app/src/main/java/org/spongycastle/crypto/engines/ChaCha7539Engine.java @@ -0,0 +1,146 @@ +/* Reworked version of the bouncycastle ChaCh7539 engine that isn't in spongycastle 1.55 */ +package org.spongycastle.crypto.engines; + +import org.spongycastle.util.Pack; +import org.spongycastle.util.Strings; + +/** + * Implementation of Daniel J. Bernstein's ChaCha stream cipher. + */ +public class ChaCha7539Engine extends Salsa20Engine +{ + /** + * Creates a 20 rounds ChaCha engine. + */ + public ChaCha7539Engine() + { + super(); + } + + public String getAlgorithmName() + { + return "ChaCha7539-" + rounds; + } + + protected int getNonceSize() + { + return 12; + } + + protected void advanceCounter(long diff) + { + int hi = (int)(diff >>> 32); + int lo = (int)diff; + + if (hi > 0) + { + throw new IllegalStateException("attempt to increase counter past 2^32."); + } + + int oldState = engineState[12]; + + engineState[12] += lo; + + if (oldState != 0 && engineState[12] < oldState) + { + throw new IllegalStateException("attempt to increase counter past 2^32."); + } + } + + protected void advanceCounter() + { + if (++engineState[12] == 0) + { + throw new IllegalStateException("attempt to increase counter past 2^32."); + } + } + + protected void retreatCounter(long diff) + { + int hi = (int)(diff >>> 32); + int lo = (int)diff; + + if (hi != 0) + { + throw new IllegalStateException("attempt to reduce counter past zero."); + } + + if ((engineState[12] & 0xffffffffL) >= (lo & 0xffffffffL)) + { + engineState[12] -= lo; + } + else + { + throw new IllegalStateException("attempt to reduce counter past zero."); + } + } + + protected void retreatCounter() + { + if (engineState[12] == 0) + { + throw new IllegalStateException("attempt to reduce counter past zero."); + } + + --engineState[12]; + } + + protected long getCounter() + { + return engineState[12] & 0xffffffffL; + } + + protected void resetCounter() + { + engineState[12] = 0; + } + + private static int[] littleEndianToInt(byte[] bs, int off, int count) + { + int[] ns = new int[count]; + for (int i = 0; i < ns.length; ++i) + { + ns[i] = Pack.littleEndianToInt(bs, off); + off += 4; + } + return ns; + } + + + private final static int[] TAU_SIGMA = ChaCha7539Engine.littleEndianToInt(Strings.toByteArray("expand 16-byte k" + "expand 32-byte k"), 0, 8); + + protected void packTauOrSigma(int keyLength, int[] state, int stateOffset) + { + int tsOff = (keyLength - 16) / 4; + state[stateOffset ] = TAU_SIGMA[tsOff ]; + state[stateOffset + 1] = TAU_SIGMA[tsOff + 1]; + state[stateOffset + 2] = TAU_SIGMA[tsOff + 2]; + state[stateOffset + 3] = TAU_SIGMA[tsOff + 3]; + } + + protected void setKey(byte[] keyBytes, byte[] ivBytes) + { + if (keyBytes != null) + { + if (keyBytes.length != 32) + { + throw new IllegalArgumentException(getAlgorithmName() + " requires 256 bit key"); + } + + packTauOrSigma(keyBytes.length, engineState, 0); + + // Key + Pack.littleEndianToInt(keyBytes, 0, engineState, 4, 8); + } + + // IV + Pack.littleEndianToInt(ivBytes, 0, engineState, 13, 3); + } + + protected void generateKeyStream(byte[] output) + { + ChaChaEngine.chachaCore(rounds, engineState, x); + Pack.intToLittleEndian(x, output, 0); + } +} +