Added unit tests (all passing unfortunately)

UI improvements
Write mode still doesn't work
This commit is contained in:
2017-09-25 18:34:27 +02:00
parent 34996da19d
commit 22ea657885
72 changed files with 2563 additions and 63 deletions

View File

@@ -0,0 +1,102 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\NUnit3TestAdapter.3.8.0\build\net35\NUnit3TestAdapter.props" Condition="Exists('..\packages\NUnit3TestAdapter.3.8.0\build\net35\NUnit3TestAdapter.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{0BD8B544-EB60-461F-9A71-605A6DFCBB19}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>KeePass2PCL.Test.Desktop</RootNamespace>
<AssemblyName>KeePass2PCL.Test.Desktop</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>full</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Reference Include="Castle.Core, Version=4.1.1.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>..\packages\Castle.Core.4.1.1\lib\net45\Castle.Core.dll</HintPath>
</Reference>
<Reference Include="gdk-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f, processorArchitecture=MSIL" />
<Reference Include="glib-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f, processorArchitecture=MSIL" />
<Reference Include="Moq, Version=4.7.99.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\packages\Moq.4.7.99\lib\net45\Moq.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=3.7.1.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.7.1\lib\net45\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="PCLCrypto, Version=2.0.0.0, Culture=neutral, PublicKeyToken=d4421c8a4786956c, processorArchitecture=MSIL">
<HintPath>..\packages\PCLCrypto.2.0.147\lib\net45\PCLCrypto.dll</HintPath>
</Reference>
<Reference Include="PInvoke.BCrypt, Version=0.5.0.0, Culture=neutral, PublicKeyToken=9e300f9f87f04a7a, processorArchitecture=MSIL">
<HintPath>..\packages\PInvoke.BCrypt.0.5.97\lib\net45\PInvoke.BCrypt.dll</HintPath>
</Reference>
<Reference Include="PInvoke.Kernel32, Version=0.5.0.0, Culture=neutral, PublicKeyToken=9e300f9f87f04a7a, processorArchitecture=MSIL">
<HintPath>..\packages\PInvoke.Kernel32.0.5.97\lib\net45\PInvoke.Kernel32.dll</HintPath>
</Reference>
<Reference Include="PInvoke.NCrypt, Version=0.5.0.0, Culture=neutral, PublicKeyToken=9e300f9f87f04a7a, processorArchitecture=MSIL">
<HintPath>..\packages\PInvoke.NCrypt.0.5.97\lib\net45\PInvoke.NCrypt.dll</HintPath>
</Reference>
<Reference Include="PInvoke.Windows.Core, Version=0.5.0.0, Culture=neutral, PublicKeyToken=9e300f9f87f04a7a, processorArchitecture=MSIL">
<HintPath>..\packages\PInvoke.Windows.Core.0.5.97\lib\net35\PInvoke.Windows.Core.dll</HintPath>
</Reference>
<Reference Include="Splat, Version=1.6.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Splat.GtkSharp.1.6.2\lib\net45\Splat.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="PCLStorage">
<HintPath>..\packages\PCLStorage.1.0.2\lib\net45\PCLStorage.dll</HintPath>
</Reference>
<Reference Include="PCLStorage.Abstractions">
<HintPath>..\packages\PCLStorage.1.0.2\lib\net45\PCLStorage.Abstractions.dll</HintPath>
</Reference>
<Reference Include="Mono.Security">
<HintPath>..\packages\Mono.Security.3.2.3.0\lib\net45\Mono.Security.dll</HintPath>
</Reference>
<Reference Include="System.IO.Compression" />
<Reference Include="System.Drawing" />
<Reference Include="Validation, Version=2.4.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL">
<HintPath>..\packages\Validation.2.4.15\lib\net45\Validation.dll</HintPath>
</Reference>
</ItemGroup>
<Import Project="..\KeePass2PCL.Test.Shared\KeePass2PCL.Test.Shared.projitems" Label="Shared" Condition="Exists('..\KeePass2PCL.Test.Shared\KeePass2PCL.Test.Shared.projitems')" />
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\ModernKeePassLib\ModernKeePassLibPCL.csproj">
<Project>{2e710089-9559-4967-846c-e763dd1f3acb}</Project>
<Name>KeePass2PCL</Name>
</ProjectReference>
</ItemGroup>
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets'))" />
<Error Condition="!Exists('..\packages\NUnit3TestAdapter.3.8.0\build\net35\NUnit3TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\NUnit3TestAdapter.3.8.0\build\net35\NUnit3TestAdapter.props'))" />
</Target>
</Project>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Validation" publicKeyToken="2fc06f0d701809a7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.4.0.0" newVersion="2.4.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PInvoke.BCrypt" publicKeyToken="9e300f9f87f04a7a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-0.5.0.0" newVersion="0.5.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PInvoke.NCrypt" publicKeyToken="9e300f9f87f04a7a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-0.5.0.0" newVersion="0.5.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Castle.Core" version="4.1.1" targetFramework="net45" />
<package id="Microsoft.Bcl.Build" version="1.0.21" targetFramework="net45" />
<package id="Microsoft.Bcl.Compression" version="3.9.85" targetFramework="net45" />
<package id="Mono.Security" version="3.2.3.0" targetFramework="net45" />
<package id="Moq" version="4.7.99" targetFramework="net45" />
<package id="NUnit" version="3.7.1" targetFramework="net45" />
<package id="NUnit3TestAdapter" version="3.8.0" targetFramework="net45" />
<package id="PCLCrypto" version="2.0.147" targetFramework="net45" />
<package id="PCLStorage" version="1.0.2" targetFramework="net45" />
<package id="PInvoke.BCrypt" version="0.5.97" targetFramework="net45" />
<package id="PInvoke.Kernel32" version="0.5.97" targetFramework="net45" />
<package id="PInvoke.NCrypt" version="0.5.97" targetFramework="net45" />
<package id="PInvoke.Windows.Core" version="0.5.97" targetFramework="net45" />
<package id="Splat.GtkSharp" version="1.6.2" targetFramework="net45" />
<package id="Validation" version="2.4.15" targetFramework="net45" />
</packages>

View File

@@ -0,0 +1,65 @@
using System;
using System.IO;
#if KeePassLib
using KeePassLib.Cryptography.Cipher;
#else
using KeePass2PCL.Cryptography.Cipher;
#endif
using NUnit.Framework;
namespace KeePass2PCL.Test.Shared.Cryptography.Cipher
{
[TestFixture ()]
public class StandardAesEngineTests
{
[Test ()]
public void TestEncryptStream ()
{
// Test vector (official ECB test vector #356)
var pbIV = new byte[16];
var pbTestKey = new byte[32];
var pbTestData = new byte[16];
var pbReferenceCT = new byte[16] {
0x75, 0xD1, 0x1B, 0x0E, 0x3A, 0x68, 0xC4, 0x22,
0x3D, 0x88, 0xDB, 0xF0, 0x17, 0x97, 0x7D, 0xD7
};
pbTestData[0] = 0x04;
var outStream = new MemoryStream (new byte[16]);
var aes = new StandardAesEngine ();
var inStream = aes.EncryptStream (outStream, pbTestKey, pbIV);
new BinaryWriter (inStream).Write (pbTestData);
Assert.That (outStream.Position, Is.EqualTo (16));
outStream.Position = 0;
var outBytes = new BinaryReader (outStream).ReadBytes (16);
Assert.That(outBytes, Is.EqualTo (pbReferenceCT));
}
[Test ()]
public void TestDecryptStream ()
{
// Test vector (official ECB test vector #356)
var pbIV = new byte[16];
var pbTestKey = new byte[32];
var pbTestData = new byte[16];
var pbReferenceCT = new byte[16] {
0x75, 0xD1, 0x1B, 0x0E, 0x3A, 0x68, 0xC4, 0x22,
0x3D, 0x88, 0xDB, 0xF0, 0x17, 0x97, 0x7D, 0xD7
};
pbTestData[0] = 0x04;
// Possible Mono Bug? This only works with size >= 48
var inStream = new MemoryStream (new byte[48]);
inStream.Write (pbReferenceCT, 0, pbReferenceCT.Length);
inStream.Position = 0;
var aes = new StandardAesEngine ();
var outStream = aes.DecryptStream (inStream, pbTestKey, pbIV);
var outBytes = new BinaryReader (outStream).ReadBytes (16);
Assert.That(outBytes, Is.EqualTo (pbTestData));
}
}
}

View File

@@ -0,0 +1,60 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Cryptography;
#else
using ModernKeePassLibPCL.Cryptography;
#endif
namespace KeePass2PCL.Test.Shared.Cryptography
{
[TestFixture ()]
public class CryptoRandomStreamTests
{
void TestGetRandomBytes(CryptoRandomStream stream)
{
const uint length = 16;
var bytes1 = stream.GetRandomBytes (length);
Assert.That (bytes1.Length, Is.EqualTo (length));
var bytes2 = stream.GetRandomBytes (length);
Assert.That (bytes2, Is.Not.EqualTo (bytes1));
}
[Test ()]
public void TestGetRandomBytesCrsAlgorithmSalsa20 ()
{
var stream = new CryptoRandomStream (CrsAlgorithm.Salsa20, new byte[16]);
TestGetRandomBytes (stream);
}
[Test ()]
public void TestGetRandomBytesCrsAlgorithmArcFourVariant ()
{
var stream = new CryptoRandomStream (CrsAlgorithm.ArcFourVariant, new byte[16]);
TestGetRandomBytes (stream);
}
void TestGetRandomInt64 (CryptoRandomStream stream)
{
var value1 = stream.GetRandomUInt64 ();
var value2 = stream.GetRandomUInt64 ();
Assert.That (value2, Is.Not.EqualTo (value1));
}
[Test ()]
public void TestGetRandomInt64AlgorithmSalsa20 ()
{
var stream = new CryptoRandomStream (CrsAlgorithm.Salsa20, new byte[16]);
TestGetRandomInt64 (stream);
}
[Test ()]
public void TestGetRandomInt64AlgorithmArcFourVariant ()
{
var stream = new CryptoRandomStream (CrsAlgorithm.ArcFourVariant, new byte[16]);
TestGetRandomInt64 (stream);
}
}
}

View File

@@ -0,0 +1,44 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Cryptography;
#else
using KeePass2PCL.Cryptography;
#endif
namespace KeePass2PCL.Test.Shared.Cryptography
{
[TestFixture ()]
public class CryptoRandomTests
{
[Test ()]
public void TestAddEntropy ()
{
// just making sure it does not throw an exception
CryptoRandom.Instance.AddEntropy (new byte[1]);
}
[Test ()]
public void TestGetRandomBytes ()
{
const int length = 32;
var bytes1 = CryptoRandom.Instance.GetRandomBytes (length);
Assert.That (bytes1.Length, Is.EqualTo (length));
var bytes2 = CryptoRandom.Instance.GetRandomBytes (length);
Assert.That (bytes2, Is.Not.EqualTo (bytes1));
}
[Test ()]
public void TestGeneratedBytesCount ()
{
const int length = 1;
CryptoRandom.Instance.GetRandomBytes (length);
var count1 = CryptoRandom.Instance.GeneratedBytesCount;
CryptoRandom.Instance.GetRandomBytes (length);
var count2 = CryptoRandom.Instance.GeneratedBytesCount;
Assert.That (count2, Is.GreaterThan (count1));
}
}
}

View File

@@ -0,0 +1,77 @@
using NUnit.Framework;
using System;
using System.IO;
using System.Text;
#if KeePassLib
using KeePassLib.Cryptography;
#else
using KeePass2PCL.Cryptography;
#endif
namespace KeePass2PCL.Test.Shared.Cryptography
{
[TestFixture ()]
public class HashingStreamExTests
{
const string data = "test";
// The expected hash includes the \n added by WriteLine
static readonly byte[] sha256HashOfData = {
0xf2, 0xca, 0x1b, 0xb6, 0xc7, 0xe9, 0x07, 0xd0,
0x6d, 0xaf, 0xe4, 0x68, 0x7e, 0x57, 0x9f, 0xce,
0x76, 0xb3, 0x7e, 0x4e, 0x93, 0xb7, 0x60, 0x50,
0x22, 0xda, 0x52, 0xe6, 0xcc, 0xc2, 0x6f, 0xd2
};
[Test ()]
public void TestRead ()
{
// if we use larger size, StreamReader will read past newline and cause bad hash
var bytes = new byte[data.Length + 1];
using (var ms = new MemoryStream (bytes)) {
using (var sw = new StreamWriter (ms)) {
// set NewLine to ensure we don't run into cross-platform issues on Windows
sw.NewLine = "\n";
sw.WriteLine (data);
}
}
using (var ms = new MemoryStream (bytes)) {
using (var hs = new HashingStreamEx (ms, false, null)) {
using (var sr = new StreamReader (hs)) {
var read = sr.ReadLine ();
Assert.That (read, Is.EqualTo (data));
}
// When the StreamReader is disposed, it calls Dispose on the
//HasingStreamEx, which computes the hash.
Assert.That (hs.Hash, Is.EqualTo (sha256HashOfData));
}
}
}
[Test ()]
public void TestWrite ()
{
var bytes = new byte[16];
using (var ms = new MemoryStream (bytes)) {
using (var hs = new HashingStreamEx (ms, true, null)) {
using (var sw = new StreamWriter (hs)) {
// set NewLine to ensure we don't run into cross-platform issues on Windows
sw.NewLine = "\n";
sw.WriteLine (data);
}
// When the StreamWriter is disposed, it calls Dispose on the
//HasingStreamEx, which computes the hash.
Assert.That (hs.Hash, Is.EqualTo (sha256HashOfData));
}
}
using (var ms = new MemoryStream (bytes)) {
using (var sr = new StreamReader (ms)) {
var read = sr.ReadLine ();
Assert.That (read, Is.EqualTo (data));
}
}
}
}
}

View File

@@ -0,0 +1,36 @@
using NUnit.Framework;
using System;
using System.Text;
#if KeePassLib
using KeePassLib.Cryptography;
#else
using KeePass2PCL.Cryptography;
#endif
namespace KeePass2PCL.Test.Shared.Cryptography
{
[TestFixture ()]
public class HmacOtpTests
{
// Using the test case from Appendix D of RFC 4226
const string secret = "12345678901234567890";
static readonly string[] expectedHOTP = new string[] {
"755224", "287082", "359152", "969429", "338314",
"254676", "287922", "162583", "399871", "520489"
};
[Test ()]
public void TestGenerate ()
{
var secretBytes = Encoding.UTF8.GetBytes (secret);
for (ulong i = 0; i < 10; i++) {
var hotp = HmacOtp.Generate (secretBytes, i, 6, false, -1);
Assert.That (hotp, Is.EqualTo (expectedHOTP[i]));
}
}
}
}

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<SharedGUID>{17F1C1A7-AE14-47AD-AE9A-ECFB9C45A559}</SharedGUID>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<Import_RootNamespace>KeePass2PCL.Test.Shared</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Cryptography\Cipher\StandardAesEngineTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Cryptography\CryptoRandomTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Cryptography\CryptoRandomStreamTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Cryptography\HashingStreamExTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Cryptography\HmacOtpTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Keys\CompositeKeyTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Keys\KcpKeyFileTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Keys\KcpCustomKeyTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Keys\KcpPasswordTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Serialization\HashedBlockStreamTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Serialization\KdbxFileTests.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Utility\GfxUtilTests.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="$(MSBuildThisFileDirectory)Keys\" />
<Folder Include="$(MSBuildThisFileDirectory)Serialization\" />
<Folder Include="$(MSBuildThisFileDirectory)Utility\" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ProjectGuid>{17F1C1A7-AE14-47AD-AE9A-ECFB9C45A559}</ProjectGuid>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<Import Project="KeePass2PCL.Test.Shared.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project>

View File

@@ -0,0 +1,34 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Keys;
#else
using KeePass2PCL.Keys;
#endif
namespace KeePass2PCL.Test.Shared.Keys
{
[TestFixture ()]
public class CompositeKeyTests
{
[Test ()]
public void TestGenerateKey32 ()
{
var originalKey = new byte[32];
var expectedKey = new byte[32] {
0xF0, 0xED, 0x57, 0xD5, 0xF0, 0xDA, 0xF3, 0x47,
0x90, 0xD0, 0xDB, 0x43, 0x25, 0xC6, 0x81, 0x2C,
0x81, 0x6A, 0x0D, 0x94, 0x96, 0xA9, 0x03, 0xE1,
0x20, 0xD4, 0x3A, 0x3E, 0x45, 0xAD, 0x02, 0x65
};
const ulong rounds = 1;
var composite = new CompositeKey ();
var key = composite.GenerateKey32 (originalKey, rounds);
Assert.That (key, Is.Not.Null);
var keyData = key.ReadData ();
Assert.That (keyData, Is.EqualTo (expectedKey));
}
}
}

View File

@@ -0,0 +1,39 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Keys;
#else
using KeePass2PCL.Keys;
#endif
namespace KeePass2PCL.Test.Shared.Keys
{
[TestFixture ()]
public class KcpCustomKeyTests
{
static readonly byte[] testData = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
[Test ()]
public void TestConstruct ()
{
var expectedHash = new byte[32] {
0xAF, 0x55, 0x70, 0xF5, 0xA1, 0x81, 0x0B, 0x7A,
0xF7, 0x8C, 0xAF, 0x4B, 0xC7, 0x0A, 0x66, 0x0F,
0x0D, 0xF5, 0x1E, 0x42, 0xBA, 0xF9, 0x1D, 0x4D,
0xE5, 0xB2, 0x32, 0x8D, 0xE0, 0xE8, 0x3D, 0xFC
};
var key = new KcpCustomKey ("test1", testData, false);
var keyData = key.KeyData.ReadData ();
Assert.That (keyData, Is.EqualTo (testData));
key = new KcpCustomKey ("test2", testData, true);
keyData = key.KeyData.ReadData ();
Assert.That (keyData, Is.EqualTo (expectedHash));
}
}
}

View File

@@ -0,0 +1,76 @@
using NUnit.Framework;
using System;
using System.IO;
#if KeePassLib
using KeePassLib.Keys;
#else
using KeePass2PCL.Keys;
#endif
namespace KeePass2PCL.Test.Shared.Keys
{
[TestFixture ()]
public class KcpKeyFileTests
{
const string testCreateFile = "TestCreate.xml";
const string testKey = "0123456789";
const string expectedFileStart =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
"<KeyFile>\r\n" +
"\t<Meta>\r\n" +
"\t\t<Version>1.00</Version>\r\n" +
"\t</Meta>\r\n" +
"\t<Key>\r\n" +
"\t\t<Data>";
const string expectedFileEnd = "\t</Key>\r\n" +
"</KeyFile>\r\n";
[Test ()]
public void TestConstruct ()
{
var expectedKeyData = new byte[32] {
0xC1, 0xB1, 0x12, 0x77, 0x23, 0xB8, 0x99, 0xB8,
0xB9, 0x3B, 0x1B, 0xFF, 0x6C, 0xBE, 0xA1, 0x5B,
0x8B, 0x99, 0xAC, 0xBD, 0x99, 0x51, 0x85, 0x95,
0x31, 0xAA, 0x14, 0x3D, 0x95, 0xBF, 0x63, 0xFF
};
var fullPath = Path.Combine(Path.GetTempPath(), testCreateFile);
using (var fs = new FileStream(fullPath, FileMode.Create)) {
using (var sw = new StreamWriter(fs)) {
sw.Write (expectedFileStart);
sw.Write (testKey);
sw.Write (expectedFileEnd);
}
}
try {
var keyFile = new KcpKeyFile (fullPath);
var keyData = keyFile.KeyData.ReadData ();
Assert.That (keyData, Is.EqualTo (expectedKeyData));
} finally {
File.Delete (fullPath);
}
}
[Test ()]
public void TestCreate ()
{
var fullPath = Path.Combine(Path.GetTempPath(), testCreateFile);
File.Create(fullPath).Close();
KcpKeyFile.Create (fullPath, null);
try {
var fileContents = File.ReadAllText (fullPath);
Assert.That (fileContents.Length, Is.EqualTo (187));
Assert.That (fileContents, Does.StartWith (expectedFileStart));
Assert.That (fileContents, Does.EndWith (expectedFileEnd));
} finally {
File.Delete (fullPath);
}
}
}
}

View File

@@ -0,0 +1,33 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Keys;
#else
using KeePass2PCL.Keys;
#endif
namespace KeePass2PCL.Test.Shared.Keys
{
[TestFixture ()]
public class KcpPasswordTests
{
const string testPassword = "password";
[Test ()]
public void TestConstruct ()
{
var expectedHash = new byte[32] {
0x5E, 0x88, 0x48, 0x98, 0xDA, 0x28, 0x04, 0x71,
0x51, 0xD0, 0xE5, 0x6F, 0x8D, 0xC6, 0x29, 0x27,
0x73, 0x60, 0x3D, 0x0D, 0x6A, 0xAB, 0xBD, 0xD6,
0x2A, 0x11, 0xEF, 0x72, 0x1D, 0x15, 0x42, 0xD8
};
var key = new KcpPassword (testPassword);
var keyData = key.KeyData.ReadData ();
Assert.That (keyData, Is.EqualTo (expectedHash));
}
}
}

View File

@@ -0,0 +1,12 @@
using System;
namespace KeePass2PCL.Test.Shared
{
public class MyClass
{
public MyClass ()
{
}
}
}

View File

@@ -0,0 +1,71 @@
using NUnit.Framework;
using System;
using System.IO;
#if KeePassLib
using KeePassLib.Serialization;
#else
using KeePass2PCL.Serialization;
#endif
namespace KeePass2PCL.Test.Shared.Serialization
{
[TestFixture ()]
public class HashedBlockStreamTests
{
static readonly byte[] data = new byte[16];
static readonly byte[] hashStreamData = new byte[] {
// The first 4 bytes are an integer indicating the block index
0x00, 0x00, 0x00, 0x00,
// Then the SHA-256 hash of the data
0x37, 0x47, 0x08, 0xFF, 0xF7, 0x71, 0x9D, 0xD5,
0x97, 0x9E, 0xC8, 0x75, 0xD5, 0x6C, 0xD2, 0x28,
0x6F, 0x6D, 0x3C, 0xF7, 0xEC, 0x31, 0x7A, 0x3B,
0x25, 0x63, 0x2A, 0xAB, 0x28, 0xEC, 0x37, 0xBB,
// then an integer that is the length of the data
0x10, 0x00, 0x00, 0x00,
// and finally the data itself
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Next, a terminating block
0x01, 0x00, 0x00, 0x00,
// terminating block is indicated by a hash of all 0s...
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// ...and by a size of 0
0x00, 0x00, 0x00, 0x00
};
[Test ()]
public void TestRead ()
{
using (var ms = new MemoryStream (hashStreamData)) {
using (var hbs = new HashedBlockStream (ms, false)) {
using (var br = new BinaryReader(hbs)) {
var bytes = br.ReadBytes (data.Length);
Assert.That (bytes, Is.EqualTo (data));
Assert.That (() => br.ReadByte (), Throws.InstanceOf<EndOfStreamException> ());
}
}
}
}
[Test ()]
public void TestWrite ()
{
var buffer = new byte[hashStreamData.Length];
using (var ms = new MemoryStream (buffer)) {
using (var hbs = new HashedBlockStream (ms, true)) {
using (var bw = new BinaryWriter(hbs)) {
bw.Write (data);
}
}
Assert.That (buffer, Is.EqualTo (hashStreamData));
}
}
}
}

View File

@@ -0,0 +1,181 @@
using NUnit.Framework;
using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
#if KeePassLib
using KeePassLib;
using KeePassLib.Keys;
using KeePassLib.Security;
using KeePassLib.Serialization;
using KeePassLib.Collections;
#else
using KeePass2PCL.Keys;
using KeePass2PCL.Security;
using KeePass2PCL.Serialization;
using KeePass2PCL.Collections;
#endif
namespace KeePass2PCL.Test.Shared.Serialization
{
[TestFixture()]
public class KdbxFileTests
{
const string testLocalizedAppName = "My Localized App Name";
const string testDatabaseName = "My Database Name";
const string testDatabaseDescription = "My Database Description";
const string testDefaultUserName = "My Default User Name";
const string testColor = "#FF0000"; // Red
const string testRootGroupName = "My Root Group Name";
const string testRootGroupNotes = "My Root Group Notes";
const string testRootGroupDefaultAutoTypeSequence = "My Root Group Default Auto Type Sequence";
const string testDatabase = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n" +
"<KeePassFile>\r\n" +
"\t<Meta>\r\n" +
"\t\t<Generator>" + testLocalizedAppName + "</Generator>\r\n" +
"\t\t<DatabaseName>" + testDatabaseName + "</DatabaseName>\r\n" +
"\t\t<DatabaseNameChanged>2015-03-14T03:15:26Z</DatabaseNameChanged>\r\n" +
"\t\t<DatabaseDescription>" + testDatabaseDescription + "</DatabaseDescription>\r\n" +
"\t\t<DatabaseDescriptionChanged>2015-03-14T03:15:26Z</DatabaseDescriptionChanged>\r\n" +
"\t\t<DefaultUserName>" + testDefaultUserName + "</DefaultUserName>\r\n" +
"\t\t<DefaultUserNameChanged>2015-03-14T03:15:26Z</DefaultUserNameChanged>\r\n" +
"\t\t<MaintenanceHistoryDays>365</MaintenanceHistoryDays>\r\n" +
"\t\t<Color>" + testColor + "</Color>\r\n" +
"\t\t<MasterKeyChanged>2015-03-14T03:15:26Z</MasterKeyChanged>\r\n" +
"\t\t<MasterKeyChangeRec>-1</MasterKeyChangeRec>\r\n" +
"\t\t<MasterKeyChangeForce>-1</MasterKeyChangeForce>\r\n" +
"\t\t<MemoryProtection>\r\n" +
"\t\t\t<ProtectTitle>False</ProtectTitle>\r\n" +
"\t\t\t<ProtectUserName>False</ProtectUserName>\r\n" +
"\t\t\t<ProtectPassword>True</ProtectPassword>\r\n" +
"\t\t\t<ProtectURL>False</ProtectURL>\r\n" +
"\t\t\t<ProtectNotes>False</ProtectNotes>\r\n" +
"\t\t</MemoryProtection>\r\n" +
"\t\t<RecycleBinEnabled>True</RecycleBinEnabled>\r\n" +
"\t\t<RecycleBinUUID>AAAAAAAAAAAAAAAAAAAAAA==</RecycleBinUUID>\r\n" +
"\t\t<RecycleBinChanged>2015-03-14T03:15:26Z</RecycleBinChanged>\r\n" +
"\t\t<EntryTemplatesGroup>AAAAAAAAAAAAAAAAAAAAAA==</EntryTemplatesGroup>\r\n" +
"\t\t<EntryTemplatesGroupChanged>2015-03-14T03:15:26Z</EntryTemplatesGroupChanged>\r\n" +
"\t\t<HistoryMaxItems>10</HistoryMaxItems>\r\n" +
"\t\t<HistoryMaxSize>6291456</HistoryMaxSize>\r\n" +
"\t\t<LastSelectedGroup>AAAAAAAAAAAAAAAAAAAAAA==</LastSelectedGroup>\r\n" +
"\t\t<LastTopVisibleGroup>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleGroup>\r\n" +
"\t\t<Binaries />\r\n" +
"\t\t<CustomData />\r\n" +
"\t</Meta>\r\n" +
"\t<Root>\r\n" +
"\t\t<Group>\r\n" +
"\t\t\t<UUID>AAAAAAAAAAAAAAAAAAAAAA==</UUID>\r\n" +
"\t\t\t<Name>" + testRootGroupName + "</Name>\r\n" +
"\t\t\t<Notes>" + testRootGroupNotes + "</Notes>\r\n" +
"\t\t\t<IconID>49</IconID>\r\n" +
"\t\t\t<Times>\r\n" +
"\t\t\t\t<CreationTime>2015-03-14T03:15:26Z</CreationTime>\r\n" +
"\t\t\t\t<LastModificationTime>2015-03-14T03:15:26Z</LastModificationTime>\r\n" +
"\t\t\t\t<LastAccessTime>2015-03-14T03:15:26Z</LastAccessTime>\r\n" +
"\t\t\t\t<ExpiryTime>2015-03-14T03:15:26Z</ExpiryTime>\r\n" +
"\t\t\t\t<Expires>False</Expires>\r\n" +
"\t\t\t\t<UsageCount>0</UsageCount>\r\n" +
"\t\t\t\t<LocationChanged>2015-03-14T03:15:26Z</LocationChanged>\r\n" +
"\t\t\t</Times>\r\n" +
"\t\t\t<IsExpanded>True</IsExpanded>\r\n" +
"\t\t\t<DefaultAutoTypeSequence>" + testRootGroupDefaultAutoTypeSequence + "</DefaultAutoTypeSequence>\r\n" +
"\t\t\t<EnableAutoType>null</EnableAutoType>\r\n" +
"\t\t\t<EnableSearching>null</EnableSearching>\r\n" +
"\t\t\t<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>\r\n" +
"\t\t</Group>\r\n" +
"\t\t<DeletedObjects />\r\n" +
"\t</Root>\r\n" +
"</KeePassFile>";
const string testDate = "2015-03-14T03:15:26Z";
[Test()]
public void TestLoad()
{
var database = new PwDatabase();
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(testDatabase)))
{
var file = new KdbxFile(database);
file.Load(ms, KdbxFormat.PlainXml, null);
}
Assert.That(database.Color.ToArgb(), Is.EqualTo(Color.Red.ToArgb()));
Assert.That(database.Compression, Is.EqualTo(PwCompressionAlgorithm.GZip));
//Assert.That (database.CustomData, Is.EqualTo ());
Assert.That(database.CustomIcons, Is.Empty);
}
[Test()]
public void TestSave()
{
var buffer = new byte[4096];
using (var ms = new MemoryStream(buffer))
{
var database = new PwDatabase();
database.New(new IOConnectionInfo(), new CompositeKey());
var date = DateTime.Parse(testDate);
PwDatabase.LocalizedAppName = testLocalizedAppName;
database.Name = testDatabaseName;
database.NameChanged = date;
database.Description = testDatabaseDescription;
database.DescriptionChanged = date;
database.DefaultUserName = testDefaultUserName;
database.DefaultUserNameChanged = date;
database.Color = Color.Red;
database.MasterKeyChanged = date;
database.RecycleBinChanged = date;
database.EntryTemplatesGroupChanged = date;
database.RootGroup.Uuid = PwUuid.Zero;
database.RootGroup.Name = testRootGroupName;
database.RootGroup.Notes = testRootGroupNotes;
database.RootGroup.DefaultAutoTypeSequence = testRootGroupDefaultAutoTypeSequence;
database.RootGroup.CreationTime = date;
database.RootGroup.LastModificationTime = date;
database.RootGroup.LastAccessTime = date;
database.RootGroup.ExpiryTime = date;
database.RootGroup.LocationChanged = date;
var file = new KdbxFile(database);
file.Save(ms, null, KdbxFormat.PlainXml, null);
}
var fileContents = Encoding.UTF8.GetString(buffer).Replace("\0", "");
if (typeof(KdbxFile).Namespace.StartsWith("KeePassLib.")
&& Environment.OSVersion.Platform != PlatformID.Win32NT)
{
// Upstream KeePassLib does not specify line endings for XmlTextWriter,
// so it uses native line endings.
fileContents = fileContents.Replace("\n", "\r\n");
}
Assert.That(fileContents, Is.EqualTo(testDatabase));
}
[Test]
public void TestSearch()
{
var database = new PwDatabase();
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(testDatabase)))
{
var file = new KdbxFile(database);
file.Load(ms, KdbxFormat.PlainXml, null);
}
var sp = new SearchParameters()
{
SearchString = "sfsoiwsefsi"
};
var listStorage = new PwObjectList<PwEntry>();
database.RootGroup.SearchEntries(sp, listStorage);
Assert.AreEqual(0U, listStorage.UCount);
var entry = new PwEntry(true, true);
entry.Strings.Set("Title", new ProtectedString(false, "NaMe"));
database.RootGroup.AddEntry(entry, true);
sp.SearchString = "name";
database.RootGroup.SearchEntries(sp, listStorage);
Assert.AreEqual(1U, listStorage.UCount);
}
}
}

View File

@@ -0,0 +1,32 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Utility;
#else
using Splat;
using KeePass2PCL.Utility;
#endif
namespace KeePass2PCL.Test.Shared.Utility
{
[TestFixture ()]
public class GfxUtilTests
{
// 16x16 all white PNG file, base64 encoded
const string testImageData =
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAsTAAA" +
"LEwEAmpwYAAAAB3RJTUUH3wMOFgIgmTCUMQAAABl0RVh0Q29tbWVudABDcmVhdG" +
"VkIHdpdGggR0lNUFeBDhcAAAAaSURBVCjPY/z//z8DKYCJgUQwqmFUw9DRAABVb" +
"QMdny4VogAAAABJRU5ErkJggg==";
[Test ()]
public void TestLoadImage ()
{
var testData = Convert.FromBase64String (testImageData);
var image = GfxUtil.LoadImage (testData);
Assert.That (image.Width, Is.EqualTo (16));
Assert.That (image.Height, Is.EqualTo (16));
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

@@ -0,0 +1,172 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{4E21AE3C-13FF-4773-824C-D51542AD1A7B}</ProjectGuid>
<OutputType>AppContainerExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>KeePass2PCL.Test.UWP</RootNamespace>
<AssemblyName>KeePass2PCL.Test.UWP</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.15063.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.10240.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<PackageCertificateKeyFile>KeePass2PCL.Test.UWP_TemporaryKey.pfx</PackageCertificateKeyFile>
<UnitTestPlatformVersion Condition="'$(UnitTestPlatformVersion)' == ''">$(VisualStudioVersion)</UnitTestPlatformVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
<OutputPath>bin\ARM\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup>
<RestoreProjectStyle>PackageReference</RestoreProjectStyle>
</PropertyGroup>
<ItemGroup>
<SDKReference Include="TestPlatform.Universal, Version=$(UnitTestPlatformVersion)" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="PwDatabaseTests.cs" />
<Compile Include="UnitTestApp.xaml.cs">
<DependentUpon>UnitTestApp.xaml</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="UnitTestApp.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
<None Include="KeePass2PCL.Test.UWP_TemporaryKey.pfx" />
<EmbeddedResource Include="TestData\1.kdbx" />
<EmbeddedResource Include="TestData\1.key" />
<EmbeddedResource Include="TestData\1key.kdbx" />
</ItemGroup>
<ItemGroup>
<Content Include="Properties\UnitTestApp.rd.xml" />
<Content Include="Assets\LockScreenLogo.scale-200.png" />
<Content Include="Assets\SplashScreen.scale-200.png" />
<Content Include="Assets\Square150x150Logo.scale-200.png" />
<Content Include="Assets\Square44x44Logo.scale-200.png" />
<Content Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png" />
<Content Include="Assets\StoreLogo.png" />
<Content Include="Assets\Wide310x150Logo.scale-200.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>5.4.0</Version>
</PackageReference>
<PackageReference Include="MSTest.TestAdapter">
<Version>1.1.18</Version>
</PackageReference>
<PackageReference Include="MSTest.TestFramework">
<Version>1.1.18</Version>
</PackageReference>
<PackageReference Include="PCLCrypto">
<Version>2.0.147</Version>
</PackageReference>
<PackageReference Include="PCLSpecialFolder">
<Version>1.1.0</Version>
</PackageReference>
<PackageReference Include="PCLStorage">
<Version>1.0.2</Version>
</PackageReference>
<PackageReference Include="Splat">
<Version>2.0.0</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\KeePass2PCL\KeePass2PCL.csproj">
<Project>{2e710089-9559-4967-846c-e763dd1f3acb}</Project>
<Name>KeePass2PCL</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' &lt; '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="utf-8"?>
<Package
xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
IgnorableNamespaces="uap mp">
<Identity Name="04c08526-0134-4915-a3bc-fa1d4ed1ea42"
Publisher="CN=anpan"
Version="1.0.0.0" />
<mp:PhoneIdentity PhoneProductId="04c08526-0134-4915-a3bc-fa1d4ed1ea42" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
<Properties>
<DisplayName>KeePass2PCL.Test.UWP</DisplayName>
<PublisherDisplayName>anpan</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>
<Dependencies>
<TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
</Dependencies>
<Resources>
<Resource Language="x-generate" />
</Resources>
<Applications>
<Application Id="vstest.executionengine.universal.App"
Executable="$targetnametoken$.exe"
EntryPoint="KeePass2PCL.Test.UWP.App">
<uap:VisualElements
DisplayName="KeePass2PCL.Test.UWP"
Square150x150Logo="Assets\Square150x150Logo.png"
Square44x44Logo="Assets\Square44x44Logo.png"
Description="KeePass2PCL.Test.UWP"
BackgroundColor="transparent">
<uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
<uap:SplashScreen Image="Assets\SplashScreen.png" />
</uap:VisualElements>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClientServer" />
</Capabilities>
</Package>

View File

@@ -0,0 +1,18 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("KeePass2PCL.Test.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("KeePass2PCL.Test.UWP")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyMetadata("TargetPlatform","UAP")]
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)]

View File

@@ -0,0 +1,29 @@
<!--
This file contains Runtime Directives used by .NET Native. The defaults here are suitable for most
developers. However, you can modify these parameters to modify the behavior of the .NET Native
optimizer.
Runtime Directives are documented at http://go.microsoft.com/fwlink/?LinkID=391919
To fully enable reflection for App1.MyClass and all of its public/private members
<Type Name="App1.MyClass" Dynamic="Required All"/>
To enable dynamic creation of the specific instantiation of AppClass<T> over System.Int32
<TypeInstantiation Name="App1.AppClass" Arguments="System.Int32" Activate="Required Public" />
Using the Namespace directive to apply reflection policy to all the types in a particular namespace
<Namespace Name="DataClasses.ViewModels" Seralize="All" />
-->
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
<Application>
<!--
An Assembly element with Name="*Application*" applies to all assemblies in
the application package. The asterisks are not wildcards.
-->
<Assembly Name="*Application*" Dynamic="Required All" />
<!-- Add your application specific runtime directives here. -->
</Application>
</Directives>

View File

@@ -0,0 +1,117 @@
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PCLStorage;
using System.IO;
using KeePass2PCL.Serialization;
using KeePass2PCL.Keys;
namespace KeePass2PCL.Test.UWP
{
[TestClass]
public class PwDatabaseTests
{
[TestMethod]
public void Open_With_Wrong_Password_Test()
{
IFolder folder = SpecialFolder.Current.Local;
IFolder testData = folder.CreateFolderAsync("TestData",
CreationCollisionOption.OpenIfExists).Result;
IFile file = testData.CreateFileAsync("1.kdbx",
CreationCollisionOption.ReplaceExisting).Result;
var fileStream = file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result;
var assembly = typeof(PwDatabaseTests).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream(
"KeePass2PCL.Test.UWP.TestData.1.kdbx");
using (var reader = new BinaryReader(stream))
using (var fileWriter = new BinaryWriter(fileStream))
{
fileWriter.Write(reader.ReadBytes((int)stream.Length));
}
var ci = new IOConnectionInfo();
ci.Path = file.Path;
var key = new CompositeKey();
key.AddUserKey(new KcpPassword("0"));
var db = new PwDatabase();
bool wasException = false;
try
{
db.Open(ci, key, null);
}
catch (InvalidCompositeKeyException)
{
wasException = true;
}
Assert.IsTrue(wasException);
file.DeleteAsync().Wait();
testData.DeleteAsync().Wait();
}
[TestMethod]
public void Open_With_KeyFile_Test()
{
IFolder folder = SpecialFolder.Current.Local;
IFolder testData = folder.CreateFolderAsync("TestData",
CreationCollisionOption.OpenIfExists).Result;
IFile keyFile = testData.CreateFileAsync("1.key",
CreationCollisionOption.ReplaceExisting).Result;
var fileStream = keyFile.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result;
var assembly = typeof(PwDatabaseTests).GetTypeInfo().Assembly;
var stream = assembly.GetManifestResourceStream(
"KeePass2PCL.Test.UWP.TestData.1.key");
using (var reader = new BinaryReader(stream))
using (var fileWriter = new BinaryWriter(fileStream))
{
fileWriter.Write(reader.ReadBytes((int)stream.Length));
}
IFile file = testData.CreateFileAsync("1key.kdbx",
CreationCollisionOption.ReplaceExisting).Result;
fileStream = file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite).Result;
assembly = typeof(PwDatabaseTests).GetTypeInfo().Assembly;
stream = assembly.GetManifestResourceStream(
"KeePass2PCL.Test.UWP.TestData.1key.kdbx");
using (var reader = new BinaryReader(stream))
using (var fileWriter = new BinaryWriter(fileStream))
{
fileWriter.Write(reader.ReadBytes((int)stream.Length));
}
var ci = new IOConnectionInfo();
ci.Path = file.Path;
var key = new CompositeKey();
key.AddUserKey(new KcpKeyFile(keyFile.Path));
var db = new PwDatabase();
db.Open(ci, key, null);
keyFile.DeleteAsync().Wait();
file.DeleteAsync().Wait();
testData.DeleteAsync().Wait();
}
[TestMethod]
public void New_Test()
{
IFolder folder = SpecialFolder.Current.Local;
IFolder testData = folder.CreateFolderAsync("TestData",
CreationCollisionOption.OpenIfExists).Result;
IFile file = testData.CreateFileAsync("1.kdbx",
CreationCollisionOption.ReplaceExisting).Result;
var ci = new IOConnectionInfo();
ci.Path = file.Path;
var key = new CompositeKey();
key.AddUserKey(new KcpPassword("0"));
var db = new PwDatabase();
db.New(ci, key);
var initialEnitiesCount = db.RootGroup.GetEntriesCount(true);
Assert.AreNotEqual(0, initialEnitiesCount);
db.Save(null);
db.Close();
Assert.IsNull(db.RootGroup);
db = new PwDatabase();
db.Open(ci, key, null);
Assert.AreEqual(initialEnitiesCount,
db.RootGroup.GetEntriesCount(true));
}
}
}

Binary file not shown.

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<KeyFile>
<Meta>
<Version>1.00</Version>
</Meta>
<Key>
<Data>M+5k7gXYzjN8Vwp5akdSwaPeUhBq0bC0q5qnSYlJmAw=</Data>
</Key>
</KeyFile>

Binary file not shown.

View File

@@ -0,0 +1,8 @@
<Application
x:Class="KeePass2PCL.Test.UWP.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:KeePass2PCL.Test.UWP"
RequestedTheme="Light">
</Application>

View File

@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace KeePass2PCL.Test.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.CreateDefaultUI();
// Ensure the current window is active
Window.Current.Activate();
Microsoft.VisualStudio.TestPlatform.TestExecutor.UnitTestClient.Run(e.Arguments);
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}

View File

@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\NUnit3TestAdapter.3.8.0\build\net35\NUnit3TestAdapter.props" Condition="Exists('..\packages\NUnit3TestAdapter.3.8.0\build\net35\NUnit3TestAdapter.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{2637FAA9-838C-43AB-81F3-BB231E0E1DCA}</ProjectGuid>
<OutputType>Library</OutputType>
<RootNamespace>KeePass2PCL.Test.KeePassLib</RootNamespace>
<AssemblyName>KeePass2PCL.Test.KeePassLib</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug</OutputPath>
<DefineConstants>DEBUG;KeePassLib</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<Optimize>true</Optimize>
<OutputPath>bin\Release</OutputPath>
<DefineConstants>KeePassLib;</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<ConsolePause>false</ConsolePause>
</PropertyGroup>
<ItemGroup>
<Reference Include="Castle.Core, Version=4.1.1.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>..\packages\Castle.Core.4.1.1\lib\net45\Castle.Core.dll</HintPath>
</Reference>
<Reference Include="KeePassLib, Version=2.35.0.20021, Culture=neutral, PublicKeyToken=a47af649847d8ce7, processorArchitecture=MSIL">
<HintPath>..\packages\pt.KeePassLib.2.35.2\lib\net20\KeePassLib.dll</HintPath>
</Reference>
<Reference Include="Moq, Version=4.7.99.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\packages\Moq.4.7.99\lib\net45\Moq.dll</HintPath>
</Reference>
<Reference Include="nunit.framework, Version=3.7.1.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.7.1\lib\net45\nunit.framework.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Drawing" />
</ItemGroup>
<Import Project="..\KeePass2PCL.Test.Shared\KeePass2PCL.Test.Shared.projitems" Label="Shared" Condition="Exists('..\KeePass2PCL.Test.Shared\KeePass2PCL.Test.Shared.projitems')" />
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\NUnit3TestAdapter.3.8.0\build\net35\NUnit3TestAdapter.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\NUnit3TestAdapter.3.8.0\build\net35\NUnit3TestAdapter.props'))" />
</Target>
</Project>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Validation" publicKeyToken="2fc06f0d701809a7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.4.0.0" newVersion="2.4.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Castle.Core" version="4.1.1" targetFramework="net45" />
<package id="Moq" version="4.7.99" targetFramework="net45" />
<package id="NUnit" version="3.7.1" targetFramework="net45" />
<package id="NUnit3TestAdapter" version="3.8.0" targetFramework="net45" />
<package id="pt.KeePassLib" version="2.35.2" targetFramework="net45" />
</packages>

View File

@@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModernKeePass", "ModernKeeP
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModernKeePassLibPCL", "ModernKeePassLib\ModernKeePassLibPCL.csproj", "{2E710089-9559-4967-846C-E763DD1F3ACB}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModernKeePassLibPCL", "ModernKeePassLib\ModernKeePassLibPCL.csproj", "{2E710089-9559-4967-846C-E763DD1F3ACB}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModernKeePassLib.Test", "ModernKeePassLib.Test\ModernKeePassLib.Test.csproj", "{067456C0-086C-46A8-B37F-1405717B7BFC}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -59,6 +61,22 @@ Global
{2E710089-9559-4967-846C-E763DD1F3ACB}.Release|x64.Build.0 = Release|Any CPU {2E710089-9559-4967-846C-E763DD1F3ACB}.Release|x64.Build.0 = Release|Any CPU
{2E710089-9559-4967-846C-E763DD1F3ACB}.Release|x86.ActiveCfg = Release|Any CPU {2E710089-9559-4967-846C-E763DD1F3ACB}.Release|x86.ActiveCfg = Release|Any CPU
{2E710089-9559-4967-846C-E763DD1F3ACB}.Release|x86.Build.0 = Release|Any CPU {2E710089-9559-4967-846C-E763DD1F3ACB}.Release|x86.Build.0 = Release|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Debug|ARM.ActiveCfg = Debug|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Debug|ARM.Build.0 = Debug|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Debug|x64.ActiveCfg = Debug|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Debug|x64.Build.0 = Debug|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Debug|x86.ActiveCfg = Debug|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Debug|x86.Build.0 = Debug|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Release|Any CPU.Build.0 = Release|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Release|ARM.ActiveCfg = Release|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Release|ARM.Build.0 = Release|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Release|x64.ActiveCfg = Release|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Release|x64.Build.0 = Release|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Release|x86.ActiveCfg = Release|Any CPU
{067456C0-086C-46A8-B37F-1405717B7BFC}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -31,8 +31,11 @@ namespace ModernKeePass.Common
_pwDatabase.Open(IOConnectionInfo.FromFile(databaseFile), key, new NullStatusLogger()); _pwDatabase.Open(IOConnectionInfo.FromFile(databaseFile), key, new NullStatusLogger());
//_pwDatabase.Open(IOConnectionInfo.FromPath(databaseFile.Path), key, new NullStatusLogger()); //_pwDatabase.Open(IOConnectionInfo.FromPath(databaseFile.Path), key, new NullStatusLogger());
IsOpen = _pwDatabase.IsOpen; IsOpen = _pwDatabase.IsOpen;
Name = databaseFile.DisplayName; if (IsOpen)
RootGroup = new GroupVm(_pwDatabase.RootGroup); {
Name = databaseFile.DisplayName;
RootGroup = new GroupVm(_pwDatabase.RootGroup);
}
} }
catch (ArgumentNullException) catch (ArgumentNullException)
{ {

View File

@@ -20,7 +20,7 @@
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<ListView Grid.Column="0" SelectionChanged="ListView_SelectionChanged"> <ListView Grid.Column="0" SelectionChanged="ListView_SelectionChanged">
<ListView.Header> <ListView.Header>
<TextBlock Text="Open database from..." FontWeight="Bold" FontSize="36" /> <TextBlock Text="ModernKeePass" FontWeight="Bold" FontSize="36" />
</ListView.Header> </ListView.Header>
<ListView.ItemTemplate > <ListView.ItemTemplate >
<DataTemplate> <DataTemplate>
@@ -37,6 +37,7 @@
<ListViewItem Name="NewItem">New</ListViewItem> <ListViewItem Name="NewItem">New</ListViewItem>
<ListViewItem Name="SelectItem">File</ListViewItem> <ListViewItem Name="SelectItem">File</ListViewItem>
<ListViewItem Name="RecentItem">Recent files - Coming soon</ListViewItem> <ListViewItem Name="RecentItem">Recent files - Coming soon</ListViewItem>
<ListViewItem Name="UrlItem">Url files - Coming soon</ListViewItem>
</ListView.Items> </ListView.Items>
</ListView> </ListView>
<Grid Name="SelectGrid" Grid.Column="2" HorizontalAlignment="Left" Height="auto" VerticalAlignment="Top" Width="auto" Margin="0,30,0,0" Visibility="Collapsed" > <Grid Name="SelectGrid" Grid.Column="2" HorizontalAlignment="Left" Height="auto" VerticalAlignment="Top" Width="auto" Margin="0,30,0,0" Visibility="Collapsed" >
@@ -56,6 +57,6 @@
<TextBlock Grid.Column="1" Grid.Row="2" Text="{Binding ErrorMessage}" Foreground="#FF9E1B1B" /> <TextBlock Grid.Column="1" Grid.Row="2" Text="{Binding ErrorMessage}" Foreground="#FF9E1B1B" />
<Button Grid.Column="1" Grid.Row="3" x:Name="OpenButton" Content="OK" HorizontalAlignment="Right" VerticalAlignment="Top" Visibility="{Binding Visibility}" Click="openBbutton_Click" Margin="0,0,7,0" Width="auto"/> <Button Grid.Column="1" Grid.Row="3" x:Name="OpenButton" Content="OK" HorizontalAlignment="Right" VerticalAlignment="Top" Visibility="{Binding Visibility}" Click="openBbutton_Click" Margin="0,0,7,0" Width="auto"/>
</Grid> </Grid>
<HyperlinkButton Grid.Column="2" Name="SaveButton" Content="Save file" Click="saveBbutton_Click" VerticalAlignment="Top" Margin="0,30,0,0" Visibility="Collapsed" /> <HyperlinkButton Grid.Column="2" Name="SaveButton" Content="Save file" Click="saveBbutton_Click" VerticalAlignment="Top" Margin="0,30,0,0" Visibility="Collapsed" IsEnabled="{Binding IsOpen}" />
</Grid> </Grid>
</Page> </Page>

View File

@@ -1,7 +1,7 @@
using System; using System;
using Windows.UI.Xaml; using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using ModernKeePass.Pages; using ModernKeePass.Pages;
using ModernKeePass.ViewModels; using ModernKeePass.ViewModels;
@@ -48,7 +48,8 @@ namespace ModernKeePass
var homeVm = DataContext as HomeVm; var homeVm = DataContext as HomeVm;
var app = ((App)Application.Current); var app = ((App)Application.Current);
homeVm.ErrorMessage = app.Database.Open(homeVm.Password); homeVm.ErrorMessage = app.Database.Open(homeVm.Password);
if (!app.Database.IsOpen) homeVm.NotifyPropertyChanged("ErrorMessage");
if (!string.IsNullOrEmpty(homeVm.ErrorMessage)) homeVm.NotifyPropertyChanged("ErrorMessage");
else Frame.Navigate(typeof(GroupDetailPage), app.Database.RootGroup); else Frame.Navigate(typeof(GroupDetailPage), app.Database.RootGroup);
} }
@@ -71,5 +72,15 @@ namespace ModernKeePass
SelectGrid.Visibility = Visibility.Collapsed; SelectGrid.Visibility = Visibility.Collapsed;
} }
} }
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var app = (App)Application.Current;
if (app.Database == null) return;
var homeVm = DataContext as HomeVm;
homeVm.IsOpen = app.Database.IsOpen;
homeVm.NotifyPropertyChanged("IsOpen");
}
} }
} }

View File

@@ -163,8 +163,8 @@
<HintPath>..\packages\Portable.BouncyCastle.1.8.1.1\lib\netstandard1.0\crypto.dll</HintPath> <HintPath>..\packages\Portable.BouncyCastle.1.8.1.1\lib\netstandard1.0\crypto.dll</HintPath>
<Private>True</Private> <Private>True</Private>
</Reference> </Reference>
<Reference Include="ModernKeePassLibPCL, Version=2.28.1.22258, Culture=neutral, processorArchitecture=MSIL"> <Reference Include="ModernKeePassLibPCL, Version=2.28.1.31251, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\ModernKeePassLibPCL.2.28.1.22258\lib\netstandard1.2\ModernKeePassLibPCL.dll</HintPath> <HintPath>..\packages\ModernKeePassLibPCL.2.28.1.31251\lib\netstandard1.2\ModernKeePassLibPCL.dll</HintPath>
<Private>True</Private> <Private>True</Private>
</Reference> </Reference>
<Reference Include="PCLCrypto, Version=2.0.0.0, Culture=neutral, PublicKeyToken=d4421c8a4786956c, processorArchitecture=MSIL"> <Reference Include="PCLCrypto, Version=2.0.0.0, Culture=neutral, PublicKeyToken=d4421c8a4786956c, processorArchitecture=MSIL">

View File

@@ -65,7 +65,7 @@
</GridView.ItemTemplate> </GridView.ItemTemplate>
<GridView.Header> <GridView.Header>
<StackPanel Width="480" Margin="0,4,14,0"> <StackPanel Width="480" Margin="0,4,14,0">
<ListView x:Name="entriesListView" Height="100" ItemsSource="{Binding Source={StaticResource entriesViewSource}}" Margin="10,0,0,0" SelectionChanged="entriesListView_SelectionChanged"> <ListView x:Name="entriesListView" Height="auto" ItemsSource="{Binding Source={StaticResource entriesViewSource}}" Margin="10,0,0,0" SelectionChanged="entriesListView_SelectionChanged">
<ListView.ItemTemplate> <ListView.ItemTemplate>
<DataTemplate> <DataTemplate>
<Grid> <Grid>
@@ -77,8 +77,6 @@
</DataTemplate> </DataTemplate>
</ListView.ItemTemplate> </ListView.ItemTemplate>
</ListView> </ListView>
<Button x:Name="addGroupButton" VerticalAlignment="Bottom" HorizontalAlignment="Right" Click="addGroupButton_Click" Content="Add Group" />
</StackPanel> </StackPanel>
</GridView.Header> </GridView.Header>
<GridView.ItemContainerStyle> <GridView.ItemContainerStyle>

View File

@@ -89,11 +89,5 @@ namespace ModernKeePass.Pages
var listView = sender as ListView; var listView = sender as ListView;
Frame.Navigate(typeof(EntryDetailPage), listView.SelectedItem as EntryVm); Frame.Navigate(typeof(EntryDetailPage), listView.SelectedItem as EntryVm);
} }
private void addGroupButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
var group = DataContext as GroupVm;
group.AddGroup("New group");
}
} }
} }

View File

@@ -5,7 +5,7 @@ namespace ModernKeePass.ViewModels
{ {
public class EntryVm : INotifyPropertyChanged public class EntryVm : INotifyPropertyChanged
{ {
public string Title { get; private set; } public string Title { get; set; }
public string UserName { get; private set; } public string UserName { get; private set; }
public string Password { get; private set; } public string Password { get; private set; }
public string URL { get; private set; } public string URL { get; private set; }

View File

@@ -32,27 +32,34 @@ namespace ModernKeePass.ViewModels
Name = "GroupName"; Name = "GroupName";
Entries = new ObservableCollection<EntryVm>(); Entries = new ObservableCollection<EntryVm>();
Groups = new ObservableCollection<GroupVm>(); Groups = new ObservableCollection<GroupVm>();
} }
public GroupVm(PwGroup group) public GroupVm(PwGroup pwGroup)
{ {
_pwGroup = group; _pwGroup = pwGroup;
Name = group.Name; Name = pwGroup.Name;
Entries = new ObservableCollection<EntryVm>(group.Entries.Select(e => new EntryVm(e))); Entries = new ObservableCollection<EntryVm>(pwGroup.Entries.Select(e => new EntryVm(e)));
Groups = new ObservableCollection<GroupVm>(group.Groups.Select(g => new GroupVm(g))); //Entries.Insert(0, new EntryVm { Title = " + New entry" });
Groups = new ObservableCollection<GroupVm>(pwGroup.Groups.Select(g => new GroupVm(g)));
//Groups.Insert(0, new GroupVm { Name = " + New group" });
} }
public void AddGroup(string title) public void CreateNewGroup(string title)
{ {
var pwGroup = new PwGroup var pwGroup = new PwGroup(true, true, title, PwIcon.Folder);
{ _pwGroup.AddGroup(pwGroup, true);
Name = title
};
Groups.Add(new GroupVm(pwGroup)); Groups.Add(new GroupVm(pwGroup));
NotifyPropertyChanged("Groups"); NotifyPropertyChanged("Groups");
this._pwGroup.Groups.Add(pwGroup);
} }
public void CreateNewEntry(string title)
{
var pwEntry = new PwEntry(true, true);
_pwGroup.AddEntry(pwEntry, true);
Entries.Add(new EntryVm(pwEntry));
NotifyPropertyChanged("Entries");
}
public event PropertyChangedEventHandler PropertyChanged; public event PropertyChangedEventHandler PropertyChanged;

View File

@@ -8,6 +8,7 @@ namespace ModernKeePass.ViewModels
public string Password { get; set; } public string Password { get; set; }
public Visibility Visibility { get; set; } public Visibility Visibility { get; set; }
public string ErrorMessage { get; set; } public string ErrorMessage { get; set; }
public bool IsOpen { get; set; }
public HomeVm() public HomeVm()
{ {

View File

@@ -4,7 +4,7 @@
<package id="Microsoft.Bcl.Compression" version="3.9.85" targetFramework="win81" /> <package id="Microsoft.Bcl.Compression" version="3.9.85" targetFramework="win81" />
<package id="Microsoft.NETCore.Platforms" version="2.0.0" targetFramework="win81" /> <package id="Microsoft.NETCore.Platforms" version="2.0.0" targetFramework="win81" />
<package id="Microsoft.NETCore.Portable.Compatibility" version="1.0.2" targetFramework="win81" /> <package id="Microsoft.NETCore.Portable.Compatibility" version="1.0.2" targetFramework="win81" />
<package id="ModernKeePassLibPCL" version="2.28.1.22258" targetFramework="win81" /> <package id="ModernKeePassLibPCL" version="2.28.1.31251" targetFramework="win81" />
<package id="NETStandard.Library" version="2.0.0" targetFramework="win81" /> <package id="NETStandard.Library" version="2.0.0" targetFramework="win81" />
<package id="PCLCrypto" version="2.0.147" targetFramework="win81" /> <package id="PCLCrypto" version="2.0.147" targetFramework="win81" />
<package id="PCLStorage" version="1.0.2" targetFramework="win81" /> <package id="PCLStorage" version="1.0.2" targetFramework="win81" />

View File

@@ -0,0 +1,65 @@
using System;
using System.IO;
#if KeePassLib
using KeePassLib.Cryptography.Cipher;
#else
using ModernKeePassLibPCL.Cryptography.Cipher;
#endif
using NUnit.Framework;
namespace ModernKeePassLib.Test.Shared.Cryptography.Cipher
{
[TestFixture ()]
public class StandardAesEngineTests
{
[Test ()]
public void TestEncryptStream ()
{
// Test vector (official ECB test vector #356)
var pbIV = new byte[16];
var pbTestKey = new byte[32];
var pbTestData = new byte[16];
var pbReferenceCT = new byte[16] {
0x75, 0xD1, 0x1B, 0x0E, 0x3A, 0x68, 0xC4, 0x22,
0x3D, 0x88, 0xDB, 0xF0, 0x17, 0x97, 0x7D, 0xD7
};
pbTestData[0] = 0x04;
var outStream = new MemoryStream (new byte[16]);
var aes = new StandardAesEngine ();
var inStream = aes.EncryptStream (outStream, pbTestKey, pbIV);
new BinaryWriter (inStream).Write (pbTestData);
Assert.That (outStream.Position, Is.EqualTo (16));
outStream.Position = 0;
var outBytes = new BinaryReader (outStream).ReadBytes (16);
Assert.That(outBytes, Is.EqualTo (pbReferenceCT));
}
[Test ()]
public void TestDecryptStream ()
{
// Test vector (official ECB test vector #356)
var pbIV = new byte[16];
var pbTestKey = new byte[32];
var pbTestData = new byte[16];
var pbReferenceCT = new byte[16] {
0x75, 0xD1, 0x1B, 0x0E, 0x3A, 0x68, 0xC4, 0x22,
0x3D, 0x88, 0xDB, 0xF0, 0x17, 0x97, 0x7D, 0xD7
};
pbTestData[0] = 0x04;
// Possible Mono Bug? This only works with size >= 48
var inStream = new MemoryStream (new byte[48]);
inStream.Write (pbReferenceCT, 0, pbReferenceCT.Length);
inStream.Position = 0;
var aes = new StandardAesEngine ();
var outStream = aes.DecryptStream (inStream, pbTestKey, pbIV);
var outBytes = new BinaryReader (outStream).ReadBytes (16);
Assert.That(outBytes, Is.EqualTo (pbTestData));
}
}
}

View File

@@ -0,0 +1,60 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Cryptography;
#else
using ModernKeePassLibPCL.Cryptography;
#endif
namespace ModernKeePassLib.Test.Shared.Cryptography
{
[TestFixture ()]
public class CryptoRandomStreamTests
{
void TestGetRandomBytes(CryptoRandomStream stream)
{
const uint length = 16;
var bytes1 = stream.GetRandomBytes (length);
Assert.That (bytes1.Length, Is.EqualTo (length));
var bytes2 = stream.GetRandomBytes (length);
Assert.That (bytes2, Is.Not.EqualTo (bytes1));
}
[Test ()]
public void TestGetRandomBytesCrsAlgorithmSalsa20 ()
{
var stream = new CryptoRandomStream (CrsAlgorithm.Salsa20, new byte[16]);
TestGetRandomBytes (stream);
}
[Test ()]
public void TestGetRandomBytesCrsAlgorithmArcFourVariant ()
{
var stream = new CryptoRandomStream (CrsAlgorithm.ArcFourVariant, new byte[16]);
TestGetRandomBytes (stream);
}
void TestGetRandomInt64 (CryptoRandomStream stream)
{
var value1 = stream.GetRandomUInt64 ();
var value2 = stream.GetRandomUInt64 ();
Assert.That (value2, Is.Not.EqualTo (value1));
}
[Test ()]
public void TestGetRandomInt64AlgorithmSalsa20 ()
{
var stream = new CryptoRandomStream (CrsAlgorithm.Salsa20, new byte[16]);
TestGetRandomInt64 (stream);
}
[Test ()]
public void TestGetRandomInt64AlgorithmArcFourVariant ()
{
var stream = new CryptoRandomStream (CrsAlgorithm.ArcFourVariant, new byte[16]);
TestGetRandomInt64 (stream);
}
}
}

View File

@@ -0,0 +1,44 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Cryptography;
#else
using ModernKeePassLibPCL.Cryptography;
#endif
namespace ModernKeePassLib.Test.Shared.Cryptography
{
[TestFixture ()]
public class CryptoRandomTests
{
[Test ()]
public void TestAddEntropy ()
{
// just making sure it does not throw an exception
CryptoRandom.Instance.AddEntropy (new byte[1]);
}
[Test ()]
public void TestGetRandomBytes ()
{
const int length = 32;
var bytes1 = CryptoRandom.Instance.GetRandomBytes (length);
Assert.That (bytes1.Length, Is.EqualTo (length));
var bytes2 = CryptoRandom.Instance.GetRandomBytes (length);
Assert.That (bytes2, Is.Not.EqualTo (bytes1));
}
[Test ()]
public void TestGeneratedBytesCount ()
{
const int length = 1;
CryptoRandom.Instance.GetRandomBytes (length);
var count1 = CryptoRandom.Instance.GeneratedBytesCount;
CryptoRandom.Instance.GetRandomBytes (length);
var count2 = CryptoRandom.Instance.GeneratedBytesCount;
Assert.That (count2, Is.GreaterThan (count1));
}
}
}

View File

@@ -0,0 +1,77 @@
using NUnit.Framework;
using System;
using System.IO;
using System.Text;
#if KeePassLib
using KeePassLib.Cryptography;
#else
using ModernKeePassLibPCL.Cryptography;
#endif
namespace ModernKeePassLib.Test.Shared.Cryptography
{
[TestFixture ()]
public class HashingStreamExTests
{
const string data = "test";
// The expected hash includes the \n added by WriteLine
static readonly byte[] sha256HashOfData = {
0xf2, 0xca, 0x1b, 0xb6, 0xc7, 0xe9, 0x07, 0xd0,
0x6d, 0xaf, 0xe4, 0x68, 0x7e, 0x57, 0x9f, 0xce,
0x76, 0xb3, 0x7e, 0x4e, 0x93, 0xb7, 0x60, 0x50,
0x22, 0xda, 0x52, 0xe6, 0xcc, 0xc2, 0x6f, 0xd2
};
[Test ()]
public void TestRead ()
{
// if we use larger size, StreamReader will read past newline and cause bad hash
var bytes = new byte[data.Length + 1];
using (var ms = new MemoryStream (bytes)) {
using (var sw = new StreamWriter (ms)) {
// set NewLine to ensure we don't run into cross-platform issues on Windows
sw.NewLine = "\n";
sw.WriteLine (data);
}
}
using (var ms = new MemoryStream (bytes)) {
using (var hs = new HashingStreamEx (ms, false, null)) {
using (var sr = new StreamReader (hs)) {
var read = sr.ReadLine ();
Assert.That (read, Is.EqualTo (data));
}
// When the StreamReader is disposed, it calls Dispose on the
//HasingStreamEx, which computes the hash.
Assert.That (hs.Hash, Is.EqualTo (sha256HashOfData));
}
}
}
[Test ()]
public void TestWrite ()
{
var bytes = new byte[16];
using (var ms = new MemoryStream (bytes)) {
using (var hs = new HashingStreamEx (ms, true, null)) {
using (var sw = new StreamWriter (hs)) {
// set NewLine to ensure we don't run into cross-platform issues on Windows
sw.NewLine = "\n";
sw.WriteLine (data);
}
// When the StreamWriter is disposed, it calls Dispose on the
//HasingStreamEx, which computes the hash.
Assert.That (hs.Hash, Is.EqualTo (sha256HashOfData));
}
}
using (var ms = new MemoryStream (bytes)) {
using (var sr = new StreamReader (ms)) {
var read = sr.ReadLine ();
Assert.That (read, Is.EqualTo (data));
}
}
}
}
}

View File

@@ -0,0 +1,36 @@
using NUnit.Framework;
using System;
using System.Text;
#if KeePassLib
using KeePassLib.Cryptography;
#else
using ModernKeePassLibPCL.Cryptography;
#endif
namespace ModernKeePassLib.Test.Shared.Cryptography
{
[TestFixture ()]
public class HmacOtpTests
{
// Using the test case from Appendix D of RFC 4226
const string secret = "12345678901234567890";
static readonly string[] expectedHOTP = new string[] {
"755224", "287082", "359152", "969429", "338314",
"254676", "287922", "162583", "399871", "520489"
};
[Test ()]
public void TestGenerate ()
{
var secretBytes = Encoding.UTF8.GetBytes (secret);
for (ulong i = 0; i < 10; i++) {
var hotp = HmacOtp.Generate (secretBytes, i, 6, false, -1);
Assert.That (hotp, Is.EqualTo (expectedHOTP[i]));
}
}
}
}

View File

@@ -0,0 +1,34 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Keys;
#else
using ModernKeePassLibPCL.Keys;
#endif
namespace ModernKeePassLib.Test.Shared.Keys
{
[TestFixture ()]
public class CompositeKeyTests
{
[Test ()]
public void TestGenerateKey32 ()
{
var originalKey = new byte[32];
var expectedKey = new byte[32] {
0xF0, 0xED, 0x57, 0xD5, 0xF0, 0xDA, 0xF3, 0x47,
0x90, 0xD0, 0xDB, 0x43, 0x25, 0xC6, 0x81, 0x2C,
0x81, 0x6A, 0x0D, 0x94, 0x96, 0xA9, 0x03, 0xE1,
0x20, 0xD4, 0x3A, 0x3E, 0x45, 0xAD, 0x02, 0x65
};
const ulong rounds = 1;
var composite = new CompositeKey ();
var key = composite.GenerateKey32 (originalKey, rounds);
Assert.That (key, Is.Not.Null);
var keyData = key.ReadData ();
Assert.That (keyData, Is.EqualTo (expectedKey));
}
}
}

View File

@@ -0,0 +1,39 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Keys;
#else
using ModernKeePassLibPCL.Keys;
#endif
namespace ModernKeePassLib.Test.Shared.Keys
{
[TestFixture ()]
public class KcpCustomKeyTests
{
static readonly byte[] testData = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
[Test ()]
public void TestConstruct ()
{
var expectedHash = new byte[32] {
0xAF, 0x55, 0x70, 0xF5, 0xA1, 0x81, 0x0B, 0x7A,
0xF7, 0x8C, 0xAF, 0x4B, 0xC7, 0x0A, 0x66, 0x0F,
0x0D, 0xF5, 0x1E, 0x42, 0xBA, 0xF9, 0x1D, 0x4D,
0xE5, 0xB2, 0x32, 0x8D, 0xE0, 0xE8, 0x3D, 0xFC
};
var key = new KcpCustomKey ("test1", testData, false);
var keyData = key.KeyData.ReadData ();
Assert.That (keyData, Is.EqualTo (testData));
key = new KcpCustomKey ("test2", testData, true);
keyData = key.KeyData.ReadData ();
Assert.That (keyData, Is.EqualTo (expectedHash));
}
}
}

View File

@@ -0,0 +1,76 @@
using NUnit.Framework;
using System;
using System.IO;
#if KeePassLib
using KeePassLib.Keys;
#else
using ModernKeePassLibPCL.Keys;
#endif
namespace ModernKeePassLib.Test.Shared.Keys
{
[TestFixture ()]
public class KcpKeyFileTests
{
const string testCreateFile = "TestCreate.xml";
const string testKey = "0123456789";
const string expectedFileStart =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
"<KeyFile>\r\n" +
"\t<Meta>\r\n" +
"\t\t<Version>1.00</Version>\r\n" +
"\t</Meta>\r\n" +
"\t<Key>\r\n" +
"\t\t<Data>";
const string expectedFileEnd = "\t</Key>\r\n" +
"</KeyFile>\r\n";
[Test ()]
public void TestConstruct ()
{
var expectedKeyData = new byte[32] {
0xC1, 0xB1, 0x12, 0x77, 0x23, 0xB8, 0x99, 0xB8,
0xB9, 0x3B, 0x1B, 0xFF, 0x6C, 0xBE, 0xA1, 0x5B,
0x8B, 0x99, 0xAC, 0xBD, 0x99, 0x51, 0x85, 0x95,
0x31, 0xAA, 0x14, 0x3D, 0x95, 0xBF, 0x63, 0xFF
};
var fullPath = Path.Combine(Path.GetTempPath(), testCreateFile);
using (var fs = new FileStream(fullPath, FileMode.Create)) {
using (var sw = new StreamWriter(fs)) {
sw.Write (expectedFileStart);
sw.Write (testKey);
sw.Write (expectedFileEnd);
}
}
try {
var keyFile = new KcpKeyFile (fullPath);
var keyData = keyFile.KeyData.ReadData ();
Assert.That (keyData, Is.EqualTo (expectedKeyData));
} finally {
File.Delete (fullPath);
}
}
[Test ()]
public void TestCreate ()
{
var fullPath = Path.Combine(Path.GetTempPath(), testCreateFile);
File.Create(fullPath).Close();
KcpKeyFile.Create (fullPath, null);
try {
var fileContents = File.ReadAllText (fullPath);
Assert.That (fileContents.Length, Is.EqualTo (187));
Assert.That (fileContents, Does.StartWith (expectedFileStart));
Assert.That (fileContents, Does.EndWith (expectedFileEnd));
} finally {
File.Delete (fullPath);
}
}
}
}

View File

@@ -0,0 +1,33 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Keys;
#else
using ModernKeePassLibPCL.Keys;
#endif
namespace ModernKeePassLib.Test.Shared.Keys
{
[TestFixture ()]
public class KcpPasswordTests
{
const string testPassword = "password";
[Test ()]
public void TestConstruct ()
{
var expectedHash = new byte[32] {
0x5E, 0x88, 0x48, 0x98, 0xDA, 0x28, 0x04, 0x71,
0x51, 0xD0, 0xE5, 0x6F, 0x8D, 0xC6, 0x29, 0x27,
0x73, 0x60, 0x3D, 0x0D, 0x6A, 0xAB, 0xBD, 0xD6,
0x2A, 0x11, 0xEF, 0x72, 0x1D, 0x15, 0x42, 0xD8
};
var key = new KcpPassword (testPassword);
var keyData = key.KeyData.ReadData ();
Assert.That (keyData, Is.EqualTo (expectedHash));
}
}
}

View File

@@ -0,0 +1,124 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{067456C0-086C-46A8-B37F-1405717B7BFC}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>ModernKeePassLib.Test</RootNamespace>
<AssemblyName>ModernKeePassLib.Test</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="ModernKeePassLibPCL, Version=2.28.1.32947, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\ModernKeePassLibPCL.2.28.1.32947\lib\portable46-net451+win81+wpa81\ModernKeePassLibPCL.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="nunit.framework, Version=3.8.1.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.3.8.1\lib\net45\nunit.framework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="PCLCrypto, Version=2.0.0.0, Culture=neutral, PublicKeyToken=d4421c8a4786956c, processorArchitecture=MSIL">
<HintPath>..\packages\PCLCrypto.2.0.147\lib\net45\PCLCrypto.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="PCLStorage, Version=1.0.2.0, Culture=neutral, PublicKeyToken=286fe515a2c35b64, processorArchitecture=MSIL">
<HintPath>..\packages\PCLStorage.1.0.2\lib\net45\PCLStorage.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="PCLStorage.Abstractions, Version=1.0.2.0, Culture=neutral, PublicKeyToken=286fe515a2c35b64, processorArchitecture=MSIL">
<HintPath>..\packages\PCLStorage.1.0.2\lib\net45\PCLStorage.Abstractions.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="PInvoke.BCrypt, Version=0.5.0.0, Culture=neutral, PublicKeyToken=9e300f9f87f04a7a, processorArchitecture=MSIL">
<HintPath>..\packages\PInvoke.BCrypt.0.5.97\lib\net45\PInvoke.BCrypt.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="PInvoke.Kernel32, Version=0.5.0.0, Culture=neutral, PublicKeyToken=9e300f9f87f04a7a, processorArchitecture=MSIL">
<HintPath>..\packages\PInvoke.Kernel32.0.5.97\lib\net45\PInvoke.Kernel32.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="PInvoke.NCrypt, Version=0.5.0.0, Culture=neutral, PublicKeyToken=9e300f9f87f04a7a, processorArchitecture=MSIL">
<HintPath>..\packages\PInvoke.NCrypt.0.5.97\lib\net45\PInvoke.NCrypt.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="PInvoke.Windows.Core, Version=0.5.0.0, Culture=neutral, PublicKeyToken=9e300f9f87f04a7a, processorArchitecture=MSIL">
<HintPath>..\packages\PInvoke.Windows.Core.0.5.97\lib\net35\PInvoke.Windows.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Splat, Version=2.0.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Splat.2.0.0\lib\Net45\Splat.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5.1\System.Runtime.WindowsRuntime.dll</HintPath>
</Reference>
<Reference Include="Validation, Version=2.4.0.0, Culture=neutral, PublicKeyToken=2fc06f0d701809a7, processorArchitecture=MSIL">
<HintPath>..\packages\Validation.2.4.15\lib\net45\Validation.dll</HintPath>
<Private>True</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Cryptography\Cipher\StandardAesEngineTests.cs" />
<Compile Include="Cryptography\CryptoRandomStreamTests.cs" />
<Compile Include="Cryptography\CryptoRandomTests.cs" />
<Compile Include="Cryptography\HashingStreamExTests.cs" />
<Compile Include="Cryptography\HmacOtpTests.cs" />
<Compile Include="Keys\CompositeKeyTests.cs" />
<Compile Include="Keys\KcpCustomKeyTests.cs" />
<Compile Include="Keys\KcpKeyFileTests.cs" />
<Compile Include="Keys\KcpPasswordTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Serialization\HashedBlockStreamTests.cs" />
<Compile Include="Serialization\KdbxFileTests.cs" />
<Compile Include="Utility\GfxUtilTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets" Condition="Exists('..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ModernKeePassLib.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ModernKeePassLib.Test")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("067456c0-086c-46a8-b37f-1405717b7bfc")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,71 @@
using NUnit.Framework;
using System;
using System.IO;
#if KeePassLib
using KeePassLib.Serialization;
#else
using ModernKeePassLibPCL.Serialization;
#endif
namespace ModernKeePassLib.Test.Shared.Serialization
{
[TestFixture ()]
public class HashedBlockStreamTests
{
static readonly byte[] data = new byte[16];
static readonly byte[] hashStreamData = new byte[] {
// The first 4 bytes are an integer indicating the block index
0x00, 0x00, 0x00, 0x00,
// Then the SHA-256 hash of the data
0x37, 0x47, 0x08, 0xFF, 0xF7, 0x71, 0x9D, 0xD5,
0x97, 0x9E, 0xC8, 0x75, 0xD5, 0x6C, 0xD2, 0x28,
0x6F, 0x6D, 0x3C, 0xF7, 0xEC, 0x31, 0x7A, 0x3B,
0x25, 0x63, 0x2A, 0xAB, 0x28, 0xEC, 0x37, 0xBB,
// then an integer that is the length of the data
0x10, 0x00, 0x00, 0x00,
// and finally the data itself
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// Next, a terminating block
0x01, 0x00, 0x00, 0x00,
// terminating block is indicated by a hash of all 0s...
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// ...and by a size of 0
0x00, 0x00, 0x00, 0x00
};
[Test ()]
public void TestRead ()
{
using (var ms = new MemoryStream (hashStreamData)) {
using (var hbs = new HashedBlockStream (ms, false)) {
using (var br = new BinaryReader(hbs)) {
var bytes = br.ReadBytes (data.Length);
Assert.That (bytes, Is.EqualTo (data));
Assert.That (() => br.ReadByte (), Throws.InstanceOf<EndOfStreamException> ());
}
}
}
}
[Test ()]
public void TestWrite ()
{
var buffer = new byte[hashStreamData.Length];
using (var ms = new MemoryStream (buffer)) {
using (var hbs = new HashedBlockStream (ms, true)) {
using (var bw = new BinaryWriter(hbs)) {
bw.Write (data);
}
}
Assert.That (buffer, Is.EqualTo (hashStreamData));
}
}
}
}

View File

@@ -0,0 +1,182 @@
using NUnit.Framework;
using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Windows.UI;
#if KeePassLib
using KeePassLib;
using KeePassLib.Keys;
using KeePassLib.Security;
using KeePassLib.Serialization;
using KeePassLib.Collections;
#else
using ModernKeePassLibPCL;
using ModernKeePassLibPCL.Keys;
using ModernKeePassLibPCL.Security;
using ModernKeePassLibPCL.Serialization;
using ModernKeePassLibPCL.Collections;
#endif
namespace ModernKeePassLib.Test.Shared.Serialization
{
[TestFixture()]
public class KdbxFileTests
{
const string testLocalizedAppName = "My Localized App Name";
const string testDatabaseName = "My Database Name";
const string testDatabaseDescription = "My Database Description";
const string testDefaultUserName = "My Default User Name";
const string testColor = "#FF0000"; // Red
const string testRootGroupName = "My Root Group Name";
const string testRootGroupNotes = "My Root Group Notes";
const string testRootGroupDefaultAutoTypeSequence = "My Root Group Default Auto Type Sequence";
const string testDatabase = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n" +
"<KeePassFile>\r\n" +
"\t<Meta>\r\n" +
"\t\t<Generator>" + testLocalizedAppName + "</Generator>\r\n" +
"\t\t<DatabaseName>" + testDatabaseName + "</DatabaseName>\r\n" +
"\t\t<DatabaseNameChanged>2015-03-14T03:15:26Z</DatabaseNameChanged>\r\n" +
"\t\t<DatabaseDescription>" + testDatabaseDescription + "</DatabaseDescription>\r\n" +
"\t\t<DatabaseDescriptionChanged>2015-03-14T03:15:26Z</DatabaseDescriptionChanged>\r\n" +
"\t\t<DefaultUserName>" + testDefaultUserName + "</DefaultUserName>\r\n" +
"\t\t<DefaultUserNameChanged>2015-03-14T03:15:26Z</DefaultUserNameChanged>\r\n" +
"\t\t<MaintenanceHistoryDays>365</MaintenanceHistoryDays>\r\n" +
//"\t\t<Color>" + testColor + "</Color>\r\n" +
"\t\t<Color></Color>\r\n" +
"\t\t<MasterKeyChanged>2015-03-14T03:15:26Z</MasterKeyChanged>\r\n" +
"\t\t<MasterKeyChangeRec>-1</MasterKeyChangeRec>\r\n" +
"\t\t<MasterKeyChangeForce>-1</MasterKeyChangeForce>\r\n" +
"\t\t<MemoryProtection>\r\n" +
"\t\t\t<ProtectTitle>False</ProtectTitle>\r\n" +
"\t\t\t<ProtectUserName>False</ProtectUserName>\r\n" +
"\t\t\t<ProtectPassword>True</ProtectPassword>\r\n" +
"\t\t\t<ProtectURL>False</ProtectURL>\r\n" +
"\t\t\t<ProtectNotes>False</ProtectNotes>\r\n" +
"\t\t</MemoryProtection>\r\n" +
"\t\t<RecycleBinEnabled>True</RecycleBinEnabled>\r\n" +
"\t\t<RecycleBinUUID>AAAAAAAAAAAAAAAAAAAAAA==</RecycleBinUUID>\r\n" +
"\t\t<RecycleBinChanged>2015-03-14T03:15:26Z</RecycleBinChanged>\r\n" +
"\t\t<EntryTemplatesGroup>AAAAAAAAAAAAAAAAAAAAAA==</EntryTemplatesGroup>\r\n" +
"\t\t<EntryTemplatesGroupChanged>2015-03-14T03:15:26Z</EntryTemplatesGroupChanged>\r\n" +
"\t\t<HistoryMaxItems>10</HistoryMaxItems>\r\n" +
"\t\t<HistoryMaxSize>6291456</HistoryMaxSize>\r\n" +
"\t\t<LastSelectedGroup>AAAAAAAAAAAAAAAAAAAAAA==</LastSelectedGroup>\r\n" +
"\t\t<LastTopVisibleGroup>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleGroup>\r\n" +
"\t\t<Binaries />\r\n" +
"\t\t<CustomData />\r\n" +
"\t</Meta>\r\n" +
"\t<Root>\r\n" +
"\t\t<Group>\r\n" +
"\t\t\t<UUID>AAAAAAAAAAAAAAAAAAAAAA==</UUID>\r\n" +
"\t\t\t<Name>" + testRootGroupName + "</Name>\r\n" +
"\t\t\t<Notes>" + testRootGroupNotes + "</Notes>\r\n" +
"\t\t\t<IconID>49</IconID>\r\n" +
"\t\t\t<Times>\r\n" +
"\t\t\t\t<CreationTime>2015-03-14T03:15:26Z</CreationTime>\r\n" +
"\t\t\t\t<LastModificationTime>2015-03-14T03:15:26Z</LastModificationTime>\r\n" +
"\t\t\t\t<LastAccessTime>2015-03-14T03:15:26Z</LastAccessTime>\r\n" +
"\t\t\t\t<ExpiryTime>2015-03-14T03:15:26Z</ExpiryTime>\r\n" +
"\t\t\t\t<Expires>False</Expires>\r\n" +
"\t\t\t\t<UsageCount>0</UsageCount>\r\n" +
"\t\t\t\t<LocationChanged>2015-03-14T03:15:26Z</LocationChanged>\r\n" +
"\t\t\t</Times>\r\n" +
"\t\t\t<IsExpanded>True</IsExpanded>\r\n" +
"\t\t\t<DefaultAutoTypeSequence>" + testRootGroupDefaultAutoTypeSequence + "</DefaultAutoTypeSequence>\r\n" +
"\t\t\t<EnableAutoType>null</EnableAutoType>\r\n" +
"\t\t\t<EnableSearching>null</EnableSearching>\r\n" +
"\t\t\t<LastTopVisibleEntry>AAAAAAAAAAAAAAAAAAAAAA==</LastTopVisibleEntry>\r\n" +
"\t\t</Group>\r\n" +
"\t\t<DeletedObjects />\r\n" +
"\t</Root>\r\n" +
"</KeePassFile>";
const string testDate = "2015-03-14T03:15:26Z";
[Test()]
public void TestLoad()
{
var database = new PwDatabase();
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(testDatabase)))
{
var file = new KdbxFile(database);
file.Load(ms, KdbxFormat.PlainXml, null);
}
//Assert.That(database.Color.ToArgb(), Is.EqualTo(Color.Red.ToArgb()));
Assert.That(database.Compression, Is.EqualTo(PwCompressionAlgorithm.GZip));
//Assert.That (database.CustomData, Is.EqualTo ());
Assert.That(database.CustomIcons, Is.Empty);
}
[Test()]
public void TestSave()
{
var buffer = new byte[4096];
using (var ms = new MemoryStream(buffer))
{
var database = new PwDatabase();
database.New(new IOConnectionInfo(), new CompositeKey());
var date = DateTime.Parse(testDate);
PwDatabase.LocalizedAppName = testLocalizedAppName;
database.Name = testDatabaseName;
database.NameChanged = date;
database.Description = testDatabaseDescription;
database.DescriptionChanged = date;
database.DefaultUserName = testDefaultUserName;
database.DefaultUserNameChanged = date;
//database.Color = Color.Red;
database.MasterKeyChanged = date;
database.RecycleBinChanged = date;
database.EntryTemplatesGroupChanged = date;
database.RootGroup.Uuid = PwUuid.Zero;
database.RootGroup.Name = testRootGroupName;
database.RootGroup.Notes = testRootGroupNotes;
database.RootGroup.DefaultAutoTypeSequence = testRootGroupDefaultAutoTypeSequence;
database.RootGroup.CreationTime = date;
database.RootGroup.LastModificationTime = date;
database.RootGroup.LastAccessTime = date;
database.RootGroup.ExpiryTime = date;
database.RootGroup.LocationChanged = date;
var file = new KdbxFile(database);
file.Save(ms, null, KdbxFormat.PlainXml, null);
}
var fileContents = Encoding.UTF8.GetString(buffer).Replace("\0", "");
if (typeof(KdbxFile).Namespace.StartsWith("KeePassLib.")
&& Environment.OSVersion.Platform != PlatformID.Win32NT)
{
// Upstream KeePassLib does not specify line endings for XmlTextWriter,
// so it uses native line endings.
fileContents = fileContents.Replace("\n", "\r\n");
}
Assert.That(fileContents, Is.EqualTo(testDatabase));
}
[Test]
public void TestSearch()
{
var database = new PwDatabase();
using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(testDatabase)))
{
var file = new KdbxFile(database);
file.Load(ms, KdbxFormat.PlainXml, null);
}
var sp = new SearchParameters()
{
SearchString = "sfsoiwsefsi"
};
var listStorage = new PwObjectList<PwEntry>();
database.RootGroup.SearchEntries(sp, listStorage);
Assert.AreEqual(0U, listStorage.UCount);
var entry = new PwEntry(true, true);
entry.Strings.Set("Title", new ProtectedString(false, "NaMe"));
database.RootGroup.AddEntry(entry, true);
sp.SearchString = "name";
database.RootGroup.SearchEntries(sp, listStorage);
Assert.AreEqual(1U, listStorage.UCount);
}
}
}

View File

@@ -0,0 +1,32 @@
using NUnit.Framework;
using System;
#if KeePassLib
using KeePassLib.Utility;
#else
using Splat;
using ModernKeePassLibPCL.Utility;
#endif
namespace ModernKeePassLib.Test.Shared.Utility
{
[TestFixture ()]
public class GfxUtilTests
{
// 16x16 all white PNG file, base64 encoded
const string testImageData =
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAACXBIWXMAAAsTAAA" +
"LEwEAmpwYAAAAB3RJTUUH3wMOFgIgmTCUMQAAABl0RVh0Q29tbWVudABDcmVhdG" +
"VkIHdpdGggR0lNUFeBDhcAAAAaSURBVCjPY/z//z8DKYCJgUQwqmFUw9DRAABVb" +
"QMdny4VogAAAABJRU5ErkJggg==";
[Test ()]
public void TestLoadImage ()
{
var testData = Convert.FromBase64String (testImageData);
var image = GfxUtil.LoadImage (testData);
Assert.That (image.Width, Is.EqualTo (16));
Assert.That (image.Height, Is.EqualTo (16));
}
}
}

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="PInvoke.BCrypt" publicKeyToken="9e300f9f87f04a7a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-0.5.0.0" newVersion="0.5.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PInvoke.NCrypt" publicKeyToken="9e300f9f87f04a7a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-0.5.0.0" newVersion="0.5.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Validation" publicKeyToken="2fc06f0d701809a7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.4.0.0" newVersion="2.4.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Bcl.Build" version="1.0.21" targetFramework="net462" />
<package id="Microsoft.Bcl.Compression" version="3.9.85" targetFramework="net462" />
<package id="ModernKeePassLibPCL" version="2.28.1.32947" targetFramework="net462" />
<package id="NUnit" version="3.8.1" targetFramework="net452" />
<package id="PCLCrypto" version="2.0.147" targetFramework="net462" />
<package id="PCLStorage" version="1.0.2" targetFramework="net462" />
<package id="PInvoke.BCrypt" version="0.5.97" targetFramework="net462" />
<package id="PInvoke.Kernel32" version="0.5.97" targetFramework="net462" />
<package id="PInvoke.NCrypt" version="0.5.97" targetFramework="net462" />
<package id="PInvoke.Windows.Core" version="0.5.97" targetFramework="net462" />
<package id="Splat" version="2.0.0" targetFramework="net462" />
<package id="Validation" version="2.4.15" targetFramework="net462" />
</packages>

View File

@@ -87,9 +87,9 @@ namespace ModernKeePassLibPCL.Keys
Construct(iocKeyFile, bThrowIfDbFile); Construct(iocKeyFile, bThrowIfDbFile);
} }
private async void Construct(IOConnectionInfo iocFile, bool bThrowIfDbFile) private void Construct(IOConnectionInfo iocFile, bool bThrowIfDbFile)
{ {
byte[] pbFileData = await IOConnection.ReadFile(iocFile); byte[] pbFileData = IOConnection.ReadFile(iocFile);
if(pbFileData == null) throw new FileNotFoundException(); if(pbFileData == null) throw new FileNotFoundException();
if(bThrowIfDbFile && (pbFileData.Length >= 8)) if(bThrowIfDbFile && (pbFileData.Length >= 8))
@@ -310,7 +310,7 @@ namespace ModernKeePassLibPCL.Keys
return pbKeyData; return pbKeyData;
} }
private static async void CreateXmlKeyFile(string strFile, byte[] pbKeyData) private static void CreateXmlKeyFile(string strFile, byte[] pbKeyData)
{ {
Debug.Assert(strFile != null); Debug.Assert(strFile != null);
if(strFile == null) throw new ArgumentNullException("strFile"); if(strFile == null) throw new ArgumentNullException("strFile");
@@ -318,7 +318,7 @@ namespace ModernKeePassLibPCL.Keys
if(pbKeyData == null) throw new ArgumentNullException("pbKeyData"); if(pbKeyData == null) throw new ArgumentNullException("pbKeyData");
IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile); IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFile);
var sOut = await IOConnection.OpenWrite(ioc); var sOut = IOConnection.OpenWrite(ioc);
#if ModernKeePassLibPCL #if ModernKeePassLibPCL
var settings = new XmlWriterSettings() { Encoding = StrUtil.Utf8 }; var settings = new XmlWriterSettings() { Encoding = StrUtil.Utf8 };

View File

@@ -566,7 +566,7 @@ namespace ModernKeePassLibPCL
/// <param name="ioSource">IO connection to load the database from.</param> /// <param name="ioSource">IO connection to load the database from.</param>
/// <param name="pwKey">Key used to open the specified database.</param> /// <param name="pwKey">Key used to open the specified database.</param>
/// <param name="slLogger">Logger, which gets all status messages.</param> /// <param name="slLogger">Logger, which gets all status messages.</param>
public async void Open(IOConnectionInfo ioSource, CompositeKey pwKey, public void Open(IOConnectionInfo ioSource, CompositeKey pwKey,
IStatusLogger slLogger) IStatusLogger slLogger)
{ {
Debug.Assert(ioSource != null); Debug.Assert(ioSource != null);
@@ -589,7 +589,7 @@ namespace ModernKeePassLibPCL
KdbxFile kdbx = new KdbxFile(this); KdbxFile kdbx = new KdbxFile(this);
kdbx.DetachBinaries = m_strDetachBins; kdbx.DetachBinaries = m_strDetachBins;
var s = await IOConnection.OpenRead(ioSource); var s = IOConnection.OpenRead(ioSource);
kdbx.Load(s, KdbxFormat.Default, slLogger); kdbx.Load(s, KdbxFormat.Default, slLogger);
s.Dispose(); s.Dispose();
@@ -612,7 +612,7 @@ namespace ModernKeePassLibPCL
/// it has been opened from. /// it has been opened from.
/// </summary> /// </summary>
/// <param name="slLogger">Logger that recieves status information.</param> /// <param name="slLogger">Logger that recieves status information.</param>
public async void Save(IStatusLogger slLogger) public void Save(IStatusLogger slLogger)
{ {
Debug.Assert(ValidateUuidUniqueness()); Debug.Assert(ValidateUuidUniqueness());
@@ -622,7 +622,7 @@ namespace ModernKeePassLibPCL
{ {
FileTransactionEx ft = new FileTransactionEx(m_ioSource, FileTransactionEx ft = new FileTransactionEx(m_ioSource,
m_bUseFileTransactions); m_bUseFileTransactions);
var s = await ft.OpenWrite(); var s = ft.OpenWrite();
KdbxFile kdb = new KdbxFile(this); KdbxFile kdb = new KdbxFile(this);
kdb.Save(s, null, KdbxFormat.Default, slLogger); kdb.Save(s, null, KdbxFormat.Default, slLogger);

View File

@@ -123,9 +123,9 @@ namespace ModernKeePassLibPCL.Serialization
return sb.ToString(); return sb.ToString();
} }
public static async Task<LockFileInfo> Load(IOConnectionInfo iocLockFile) public static LockFileInfo Load(IOConnectionInfo iocLockFile)
{ {
using (var s = await IOConnection.OpenRead(iocLockFile)) using (var s = IOConnection.OpenRead(iocLockFile))
try try
{ {
if(s == null) return null; if(s == null) return null;
@@ -158,7 +158,7 @@ namespace ModernKeePassLibPCL.Serialization
} }
// Throws on error // Throws on error
public static async Task<LockFileInfo> Create(IOConnectionInfo iocLockFile) public static LockFileInfo Create(IOConnectionInfo iocLockFile)
{ {
byte[] pbID = CryptoRandom.Instance.GetRandomBytes(16); byte[] pbID = CryptoRandom.Instance.GetRandomBytes(16);
string strTime = TimeUtil.SerializeUtc(DateTime.Now); string strTime = TimeUtil.SerializeUtc(DateTime.Now);
@@ -175,11 +175,11 @@ namespace ModernKeePassLibPCL.Serialization
sb.AppendLine(lfi.Machine); sb.AppendLine(lfi.Machine);
sb.AppendLine(lfi.Domain); sb.AppendLine(lfi.Domain);
using (var s = await IOConnection.OpenWrite(iocLockFile)) using (var s = IOConnection.OpenWrite(iocLockFile))
{ {
byte[] pbFile = StrUtil.Utf8.GetBytes(sb.ToString()); byte[] pbFile = StrUtil.Utf8.GetBytes(sb.ToString());
if (s == null) throw new IOException(iocLockFile.GetDisplayName()); if (s == null) throw new IOException(iocLockFile.GetDisplayName());
await s.WriteAsync(pbFile.AsBuffer()); s.WriteAsync(pbFile.AsBuffer()).GetAwaiter().GetResult();
} }
return lfi; return lfi;
@@ -193,7 +193,7 @@ namespace ModernKeePassLibPCL.Serialization
m_iocLockFile = iocBaseFile.CloneDeep(); m_iocLockFile = iocBaseFile.CloneDeep();
m_iocLockFile.Path += LockFileExt; m_iocLockFile.Path += LockFileExt;
LockFileInfo lfiEx = LockFileInfo.Load(m_iocLockFile).Result; LockFileInfo lfiEx = LockFileInfo.Load(m_iocLockFile);
if(lfiEx != null) if(lfiEx != null)
{ {
m_iocLockFile = null; // Otherwise Dispose deletes the existing one m_iocLockFile = null; // Otherwise Dispose deletes the existing one

View File

@@ -79,7 +79,7 @@ namespace ModernKeePassLibPCL.Serialization
else m_iocTemp = m_iocBase; else m_iocTemp = m_iocBase;
} }
public async Task<IRandomAccessStream> OpenWrite() public IRandomAccessStream OpenWrite()
{ {
if(!m_bTransacted) m_bMadeUnhidden = UrlUtil.UnhideFile(m_iocTemp.Path); if(!m_bTransacted) m_bMadeUnhidden = UrlUtil.UnhideFile(m_iocTemp.Path);
else // m_bTransacted else // m_bTransacted
@@ -88,7 +88,7 @@ namespace ModernKeePassLibPCL.Serialization
catch(Exception) { } catch(Exception) { }
} }
return await IOConnection.OpenWrite(m_iocTemp); return IOConnection.OpenWrite(m_iocTemp);
} }
public void CommitWrite() public void CommitWrite()

View File

@@ -422,17 +422,17 @@ namespace ModernKeePassLibPCL.Serialization
new Uri(ioc.Path))); new Uri(ioc.Path)));
} }
#else #else
public static async Task<IRandomAccessStream> OpenRead(IOConnectionInfo ioc) public static IRandomAccessStream OpenRead(IOConnectionInfo ioc)
{ {
RaiseIOAccessPreEvent(ioc, IOAccessType.Read); RaiseIOAccessPreEvent(ioc, IOAccessType.Read);
return await OpenReadLocal(ioc); return OpenReadLocal(ioc);
} }
#endif #endif
private static async Task<IRandomAccessStream> OpenReadLocal(IOConnectionInfo ioc) private static IRandomAccessStream OpenReadLocal(IOConnectionInfo ioc)
{ {
return await ioc.StorageFile.OpenAsync(FileAccessMode.Read); return ioc.StorageFile.OpenAsync(FileAccessMode.Read).GetAwaiter().GetResult();
} }
#if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT) #if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT)
@@ -458,17 +458,17 @@ namespace ModernKeePassLibPCL.Serialization
return IocStream.WrapIfRequired(s); return IocStream.WrapIfRequired(s);
} }
#else #else
public static async Task<IRandomAccessStream> OpenWrite(IOConnectionInfo ioc) public static IRandomAccessStream OpenWrite(IOConnectionInfo ioc)
{ {
RaiseIOAccessPreEvent(ioc, IOAccessType.Write); RaiseIOAccessPreEvent(ioc, IOAccessType.Write);
return await OpenWriteLocal(ioc); return OpenWriteLocal(ioc);
} }
#endif #endif
private static async Task<IRandomAccessStream> OpenWriteLocal(IOConnectionInfo ioc) private static IRandomAccessStream OpenWriteLocal(IOConnectionInfo ioc)
{ {
return await ioc.StorageFile.OpenAsync(FileAccessMode.ReadWrite); return ioc.StorageFile.OpenAsync(FileAccessMode.ReadWrite).GetAwaiter().GetResult();
} }
public static bool FileExists(IOConnectionInfo ioc) public static bool FileExists(IOConnectionInfo ioc)
@@ -486,12 +486,12 @@ namespace ModernKeePassLibPCL.Serialization
return ioc.StorageFile.IsAvailable; return ioc.StorageFile.IsAvailable;
} }
public static async void DeleteFile(IOConnectionInfo ioc) public static void DeleteFile(IOConnectionInfo ioc)
{ {
RaiseIOAccessPreEvent(ioc, IOAccessType.Delete); RaiseIOAccessPreEvent(ioc, IOAccessType.Delete);
if (!ioc.IsLocalFile()) return; if (!ioc.IsLocalFile()) return;
await ioc.StorageFile?.DeleteAsync(); ioc.StorageFile?.DeleteAsync().GetAwaiter().GetResult();
} }
/// <summary> /// <summary>
@@ -503,12 +503,12 @@ namespace ModernKeePassLibPCL.Serialization
/// </summary> /// </summary>
/// <param name="iocFrom">Source file path.</param> /// <param name="iocFrom">Source file path.</param>
/// <param name="iocTo">Target file path.</param> /// <param name="iocTo">Target file path.</param>
public static async void RenameFile(IOConnectionInfo iocFrom, IOConnectionInfo iocTo) public static void RenameFile(IOConnectionInfo iocFrom, IOConnectionInfo iocTo)
{ {
RaiseIOAccessPreEvent(iocFrom, iocTo, IOAccessType.Move); RaiseIOAccessPreEvent(iocFrom, iocTo, IOAccessType.Move);
if (!iocFrom.IsLocalFile()) return; if (!iocFrom.IsLocalFile()) return;
await iocFrom.StorageFile?.RenameAsync(iocTo.Path); iocFrom.StorageFile?.RenameAsync(iocTo.Path).GetAwaiter().GetResult();
} }
#if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT) #if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT)
@@ -544,13 +544,13 @@ namespace ModernKeePassLibPCL.Serialization
catch(Exception) { Debug.Assert(false); } catch(Exception) { Debug.Assert(false); }
} }
#endif #endif
public static async Task<byte[]> ReadFile(IOConnectionInfo ioc) public static byte[] ReadFile(IOConnectionInfo ioc)
{ {
IRandomAccessStream sIn = null; IRandomAccessStream sIn = null;
MemoryStream ms = null; MemoryStream ms = null;
try try
{ {
sIn = await OpenRead(ioc); sIn = OpenRead(ioc);
if(sIn == null) return null; if(sIn == null) return null;
ms = new MemoryStream(); ms = new MemoryStream();

View File

@@ -58,10 +58,10 @@ namespace ModernKeePassLibPCL.Serialization
/// <param name="strFilePath">File to load.</param> /// <param name="strFilePath">File to load.</param>
/// <param name="kdbFormat">Format specifier.</param> /// <param name="kdbFormat">Format specifier.</param>
/// <param name="slLogger">Status logger (optional).</param> /// <param name="slLogger">Status logger (optional).</param>
public async void Load(string strFilePath, KdbxFormat kdbFormat, IStatusLogger slLogger) public void Load(string strFilePath, KdbxFormat kdbFormat, IStatusLogger slLogger)
{ {
IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFilePath); IOConnectionInfo ioc = IOConnectionInfo.FromPath(strFilePath);
Load(await IOConnection.OpenRead(ioc), kdbFormat, slLogger); Load(IOConnection.OpenRead(ioc), kdbFormat, slLogger);
} }
/// <summary> /// <summary>