Read-mode working

Write-mode does not create exceptions but still doesn't work
This commit is contained in:
2017-09-25 14:50:47 +02:00
parent 3bf8015280
commit 34996da19d
38 changed files with 341 additions and 358 deletions

View File

@@ -27,7 +27,8 @@ using System.Threading.Tasks;
using System.Threading;
#endif
using System.Diagnostics;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Storage.Streams;
using ModernKeePassLibPCL.Cryptography;
using ModernKeePassLibPCL.Resources;
using ModernKeePassLibPCL.Utility;
@@ -124,26 +125,34 @@ namespace ModernKeePassLibPCL.Serialization
public static async Task<LockFileInfo> Load(IOConnectionInfo iocLockFile)
{
Stream s = null;
using (var s = await IOConnection.OpenRead(iocLockFile))
try
{
s = await IOConnection.OpenRead(iocLockFile);
if(s == null) return null;
StreamReader sr = new StreamReader(s, StrUtil.Utf8);
string str = sr.ReadToEnd();
sr.Dispose();
if(str == null) { Debug.Assert(false); return null; }
using (var sr = new StreamReader(s.AsStream(), StrUtil.Utf8))
{
string str = sr.ReadToEnd();
if (str == null)
{
Debug.Assert(false);
}
str = StrUtil.NormalizeNewLines(str, false);
string[] v = str.Split('\n');
if((v == null) || (v.Length < 6)) { Debug.Assert(false); return null; }
str = StrUtil.NormalizeNewLines(str, false);
string[] v = str.Split('\n');
if ((v == null) || (v.Length < 6))
{
Debug.Assert(false);
}
if(!v[0].StartsWith(LockFileHeader)) { Debug.Assert(false); return null; }
return new LockFileInfo(v[1], v[2], v[3], v[4], v[5]);
if (!v[0].StartsWith(LockFileHeader))
{
Debug.Assert(false);
}
return new LockFileInfo(v[1], v[2], v[3], v[4], v[5]);
}
}
catch(FileNotFoundException) { }
catch(Exception) { Debug.Assert(false); }
finally { if(s != null) s.Dispose(); }
return null;
}
@@ -151,46 +160,27 @@ namespace ModernKeePassLibPCL.Serialization
// Throws on error
public static async Task<LockFileInfo> Create(IOConnectionInfo iocLockFile)
{
LockFileInfo lfi;
Stream s = null;
try
byte[] pbID = CryptoRandom.Instance.GetRandomBytes(16);
string strTime = TimeUtil.SerializeUtc(DateTime.Now);
var lfi = new LockFileInfo(Convert.ToBase64String(pbID), strTime,
string.Empty, string.Empty, string.Empty);
StringBuilder sb = new StringBuilder();
sb.AppendLine(LockFileHeader);
sb.AppendLine(lfi.ID);
sb.AppendLine(strTime);
sb.AppendLine(lfi.UserName);
sb.AppendLine(lfi.Machine);
sb.AppendLine(lfi.Domain);
using (var s = await IOConnection.OpenWrite(iocLockFile))
{
byte[] pbID = CryptoRandom.Instance.GetRandomBytes(16);
string strTime = TimeUtil.SerializeUtc(DateTime.Now);
#if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT)
lfi = new LockFileInfo(Convert.ToBase64String(pbID), strTime,
Environment.UserName, Environment.MachineName,
Environment.UserDomainName);
#else
lfi = new LockFileInfo(Convert.ToBase64String(pbID), strTime,
string.Empty, string.Empty, string.Empty);
#endif
StringBuilder sb = new StringBuilder();
#if !KeePassLibSD
sb.AppendLine(LockFileHeader);
sb.AppendLine(lfi.ID);
sb.AppendLine(strTime);
sb.AppendLine(lfi.UserName);
sb.AppendLine(lfi.Machine);
sb.AppendLine(lfi.Domain);
#else
sb.Append(LockFileHeader + MessageService.NewLine);
sb.Append(lfi.ID + MessageService.NewLine);
sb.Append(strTime + MessageService.NewLine);
sb.Append(lfi.UserName + MessageService.NewLine);
sb.Append(lfi.Machine + MessageService.NewLine);
sb.Append(lfi.Domain + MessageService.NewLine);
#endif
byte[] pbFile = StrUtil.Utf8.GetBytes(sb.ToString());
s = await IOConnection.OpenWrite(iocLockFile);
if(s == null) throw new IOException(iocLockFile.GetDisplayName());
s.Write(pbFile, 0, pbFile.Length);
if (s == null) throw new IOException(iocLockFile.GetDisplayName());
await s.WriteAsync(pbFile.AsBuffer());
}
finally { if(s != null) s.Dispose(); }
return lfi;
}

View File

@@ -30,6 +30,7 @@ using System.Security.AccessControl;
using ModernKeePassLibPCL.Native;
using ModernKeePassLibPCL.Utility;
using System.Threading.Tasks;
using Windows.Storage.Streams;
namespace ModernKeePassLibPCL.Serialization
{
@@ -78,7 +79,7 @@ namespace ModernKeePassLibPCL.Serialization
else m_iocTemp = m_iocBase;
}
public async Task<Stream> OpenWrite()
public async Task<IRandomAccessStream> OpenWrite()
{
if(!m_bTransacted) m_bMadeUnhidden = UrlUtil.UnhideFile(m_iocTemp.Path);
else // m_bTransacted
@@ -108,7 +109,7 @@ namespace ModernKeePassLibPCL.Serialization
bool bEfsEncrypted = false;
#endif
if(await IOConnection.FileExists(m_iocBase))
if(IOConnection.FileExists(m_iocBase))
{
#if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT)
if(m_iocBase.IsLocalFile())

View File

@@ -422,7 +422,7 @@ namespace ModernKeePassLibPCL.Serialization
new Uri(ioc.Path)));
}
#else
public static async Task<Stream> OpenRead(IOConnectionInfo ioc)
public static async Task<IRandomAccessStream> OpenRead(IOConnectionInfo ioc)
{
RaiseIOAccessPreEvent(ioc, IOAccessType.Read);
@@ -430,20 +430,9 @@ namespace ModernKeePassLibPCL.Serialization
}
#endif
private static async Task<Stream> OpenReadLocal(IOConnectionInfo ioc)
private static async Task<IRandomAccessStream> OpenReadLocal(IOConnectionInfo ioc)
{
#if ModernKeePassLibPCL
/*if (ioc.StorageFile != null)
{*/
var file = await ioc.StorageFile.OpenAsync(FileAccessMode.Read);
return file.AsStream();
/*}
var file = FileSystem.Current.GetFileFromPathAsync(ioc.Path).Result;
return file.OpenAsync(PCLStorage.FileAccess.Read).Result;*/
#else
return new FileStream(ioc.Path, FileMode.Open, FileAccess.Read,
FileShare.Read);
#endif
return await ioc.StorageFile.OpenAsync(FileAccessMode.Read);
}
#if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT)
@@ -469,7 +458,7 @@ namespace ModernKeePassLibPCL.Serialization
return IocStream.WrapIfRequired(s);
}
#else
public static async Task<Stream> OpenWrite(IOConnectionInfo ioc)
public static async Task<IRandomAccessStream> OpenWrite(IOConnectionInfo ioc)
{
RaiseIOAccessPreEvent(ioc, IOAccessType.Write);
@@ -477,102 +466,32 @@ namespace ModernKeePassLibPCL.Serialization
}
#endif
private static async Task<Stream> OpenWriteLocal(IOConnectionInfo ioc)
private static async Task<IRandomAccessStream> OpenWriteLocal(IOConnectionInfo ioc)
{
#if ModernKeePassLibPCL
/*if (ioc.StorageFile != null)
{*/
var file = await ioc.StorageFile.OpenAsync(FileAccessMode.ReadWrite);
return file.AsStream();
/*}
var file = FileSystem.Current.GetFileFromPathAsync(ioc.Path).Result;
return file.OpenAsync(FileAccess.ReadAndWrite).Result;*/
#else
return new FileStream(ioc.Path, FileMode.Create, FileAccess.Write,
FileShare.None);
#endif
return await ioc.StorageFile.OpenAsync(FileAccessMode.ReadWrite);
}
public static async Task<bool> FileExists(IOConnectionInfo ioc)
public static bool FileExists(IOConnectionInfo ioc)
{
return await FileExists(ioc, false);
return FileExists(ioc, false);
}
public static async Task<bool> FileExists(IOConnectionInfo ioc, bool bThrowErrors)
public static bool FileExists(IOConnectionInfo ioc, bool bThrowErrors)
{
if(ioc == null) { Debug.Assert(false); return false; }
if(ioc == null) { Debug.Assert(false);
}
RaiseIOAccessPreEvent(ioc, IOAccessType.Exists);
#if ModernKeePassLibPCL
/*if(ioc.IsLocalFile())
return (FileSystem.Current.GetFileFromPathAsync(ioc.Path).Result != null);*/
return ioc.StorageFile.IsAvailable;
#else
if(ioc.IsLocalFile()) return File.Exists(ioc.Path);
#endif
#if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT)
if(ioc.Path.StartsWith("ftp://", StrUtil.CaseIgnoreCmp))
{
bool b = SendCommand(ioc, WebRequestMethods.Ftp.GetDateTimestamp);
if(!b && bThrowErrors) throw new InvalidOperationException();
return b;
}
#endif
try
{
Stream s = await OpenRead(ioc);
if(s == null) throw new FileNotFoundException();
try { s.ReadByte(); }
catch(Exception) { }
// We didn't download the file completely; close may throw
// an exception -- that's okay
try { s.Dispose(); }
catch(Exception) { }
}
catch(Exception)
{
if(bThrowErrors) throw;
return false;
}
return true;
}
public static async void DeleteFile(IOConnectionInfo ioc)
{
RaiseIOAccessPreEvent(ioc, IOAccessType.Delete);
#if ModernKeePassLibPCL
if (!ioc.IsLocalFile()) return;
await ioc.StorageFile?.DeleteAsync();
/*var file = FileSystem.Current.GetFileFromPathAsync(ioc.Path).Result;
file.DeleteAsync().RunSynchronously();*/
#else
if(ioc.IsLocalFile()) { File.Delete(ioc.Path); return; }
#endif
#if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT)
WebRequest req = CreateWebRequest(ioc);
if(req != null)
{
if(req is HttpWebRequest) req.Method = "DELETE";
else if(req is FtpWebRequest)
req.Method = WebRequestMethods.Ftp.DeleteFile;
else if(req is FileWebRequest)
{
File.Delete(UrlUtil.FileUrlToPath(ioc.Path));
return;
}
else req.Method = WrmDeleteFile;
DisposeResponse(req.GetResponse(), true);
}
#endif
}
/// <summary>
@@ -587,63 +506,9 @@ namespace ModernKeePassLibPCL.Serialization
public static async void RenameFile(IOConnectionInfo iocFrom, IOConnectionInfo iocTo)
{
RaiseIOAccessPreEvent(iocFrom, iocTo, IOAccessType.Move);
#if ModernKeePassLibPCL
if (!iocFrom.IsLocalFile()) return;
await iocFrom.StorageFile?.RenameAsync(iocTo.Path);
/*var file = FileSystem.Current.GetFileFromPathAsync(iocFrom.Path).Result;
file.MoveAsync(iocTo.Path).RunSynchronously();*/
#else
if(iocFrom.IsLocalFile()) { File.Move(iocFrom.Path, iocTo.Path); return; }
#endif
#if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT)
WebRequest req = CreateWebRequest(iocFrom);
if(req != null)
{
if(req is HttpWebRequest)
{
req.Method = "MOVE";
req.Headers.Set("Destination", iocTo.Path); // Full URL supported
}
else if(req is FtpWebRequest)
{
req.Method = WebRequestMethods.Ftp.Rename;
string strTo = UrlUtil.GetFileName(iocTo.Path);
// We're affected by .NET bug 621450:
// https://connect.microsoft.com/VisualStudio/feedback/details/621450/problem-renaming-file-on-ftp-server-using-ftpwebrequest-in-net-framework-4-0-vs2010-only
// Prepending "./", "%2E/" or "Dummy/../" doesn't work.
((FtpWebRequest)req).RenameTo = strTo;
}
else if(req is FileWebRequest)
{
File.Move(UrlUtil.FileUrlToPath(iocFrom.Path),
UrlUtil.FileUrlToPath(iocTo.Path));
return;
}
else
{
req.Method = WrmMoveFile;
req.Headers.Set(WrhMoveFileTo, iocTo.Path);
}
DisposeResponse(req.GetResponse(), true);
}
#endif
// using(Stream sIn = IOConnection.OpenRead(iocFrom))
// {
// using(Stream sOut = IOConnection.OpenWrite(iocTo))
// {
// MemUtil.CopyStream(sIn, sOut);
// sOut.Close();
// }
//
// sIn.Close();
// }
// DeleteFile(iocFrom);
}
#if (!ModernKeePassLibPCL && !KeePassLibSD && !KeePassRT)
@@ -681,7 +546,7 @@ namespace ModernKeePassLibPCL.Serialization
#endif
public static async Task<byte[]> ReadFile(IOConnectionInfo ioc)
{
Stream sIn = null;
IRandomAccessStream sIn = null;
MemoryStream ms = null;
try
{
@@ -689,7 +554,8 @@ namespace ModernKeePassLibPCL.Serialization
if(sIn == null) return null;
ms = new MemoryStream();
MemUtil.CopyStream(sIn, ms);
MemUtil.CopyStream(sIn.AsStream(), ms);
return ms.ToArray();
}

View File

@@ -43,6 +43,7 @@ using ModernKeePassLibPCL.Keys;
using ModernKeePassLibPCL.Resources;
using ModernKeePassLibPCL.Utility;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
namespace ModernKeePassLibPCL.Serialization
{
@@ -70,7 +71,7 @@ namespace ModernKeePassLibPCL.Serialization
/// a KDBX stream.</param>
/// <param name="kdbFormat">Format specifier.</param>
/// <param name="slLogger">Status logger (optional).</param>
public void Load(Stream sSource, KdbxFormat kdbFormat, IStatusLogger slLogger)
public void Load(IRandomAccessStream sSource, KdbxFormat kdbFormat, IStatusLogger slLogger)
{
Debug.Assert(sSource != null);
if(sSource == null) throw new ArgumentNullException("sSource");
@@ -78,7 +79,7 @@ namespace ModernKeePassLibPCL.Serialization
m_format = kdbFormat;
m_slLogger = slLogger;
HashingStreamEx hashedStream = new HashingStreamEx(sSource, false, null);
HashingStreamEx hashedStream = new HashingStreamEx(sSource.AsStream(), false, null);
UTF8Encoding encNoBom = StrUtil.Utf8;
try
@@ -164,7 +165,7 @@ namespace ModernKeePassLibPCL.Serialization
finally { CommonCleanUpRead(sSource, hashedStream); }
}
private void CommonCleanUpRead(Stream sSource, HashingStreamEx hashedStream)
private void CommonCleanUpRead(IRandomAccessStream sSource, HashingStreamEx hashedStream)
{
hashedStream.Dispose();
m_pbHashOfFileOnDisk = hashedStream.Hash;
@@ -375,7 +376,7 @@ namespace ModernKeePassLibPCL.Serialization
}
[Obsolete]
public static List<PwEntry> ReadEntries(PwDatabase pwDatabase, Stream msData)
public static List<PwEntry> ReadEntries(PwDatabase pwDatabase, IRandomAccessStream msData)
{
return ReadEntries(msData);
}
@@ -385,7 +386,7 @@ namespace ModernKeePassLibPCL.Serialization
/// </summary>
/// <param name="msData">Input stream to read the entries from.</param>
/// <returns>Extracted entries.</returns>
public static List<PwEntry> ReadEntries(Stream msData)
public static List<PwEntry> ReadEntries(IRandomAccessStream msData)
{
/* KdbxFile f = new KdbxFile(pwDatabase);
f.m_format = KdbxFormat.PlainXml;

View File

@@ -48,6 +48,7 @@ using ModernKeePassLibPCL.Resources;
using ModernKeePassLibPCL.Security;
using ModernKeePassLibPCL.Utility;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;
namespace ModernKeePassLibPCL.Serialization
{
@@ -76,7 +77,7 @@ namespace ModernKeePassLibPCL.Serialization
/// be written.</param>
/// <param name="format">Format of the file to create.</param>
/// <param name="slLogger">Logger that recieves status information.</param>
public void Save(Stream sSaveTo, PwGroup pgDataSource, KdbxFormat format,
public void Save(IRandomAccessStream sSaveTo, PwGroup pgDataSource, KdbxFormat format,
IStatusLogger slLogger)
{
Debug.Assert(sSaveTo != null);
@@ -85,7 +86,7 @@ namespace ModernKeePassLibPCL.Serialization
m_format = format;
m_slLogger = slLogger;
HashingStreamEx hashedStream = new HashingStreamEx(sSaveTo, true, null);
HashingStreamEx hashedStream = new HashingStreamEx(sSaveTo.AsStream(), true, null);
UTF8Encoding encNoBom = StrUtil.Utf8;
CryptoRandom cr = CryptoRandom.Instance;
@@ -145,7 +146,7 @@ namespace ModernKeePassLibPCL.Serialization
finally { CommonCleanUpWrite(sSaveTo, hashedStream); }
}
private void CommonCleanUpWrite(Stream sSaveTo, HashingStreamEx hashedStream)
private void CommonCleanUpWrite(IRandomAccessStream sSaveTo, HashingStreamEx hashedStream)
{
hashedStream.Dispose();
m_pbHashOfFileOnDisk = hashedStream.Hash;
@@ -158,50 +159,53 @@ namespace ModernKeePassLibPCL.Serialization
private void WriteHeader(Stream s)
{
MemoryStream ms = new MemoryStream();
using (var ms = new MemoryStream())
{
MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileSignature1));
MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileSignature2));
MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileVersion32));
MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileSignature1));
MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileSignature2));
MemUtil.Write(ms, MemUtil.UInt32ToBytes(FileVersion32));
WriteHeaderField(ms, KdbxHeaderFieldID.CipherID,
m_pwDatabase.DataCipherUuid.UuidBytes);
WriteHeaderField(ms, KdbxHeaderFieldID.CipherID,
m_pwDatabase.DataCipherUuid.UuidBytes);
int nCprID = (int)m_pwDatabase.Compression;
WriteHeaderField(ms, KdbxHeaderFieldID.CompressionFlags,
MemUtil.UInt32ToBytes((uint)nCprID));
int nCprID = (int) m_pwDatabase.Compression;
WriteHeaderField(ms, KdbxHeaderFieldID.CompressionFlags,
MemUtil.UInt32ToBytes((uint) nCprID));
WriteHeaderField(ms, KdbxHeaderFieldID.MasterSeed, m_pbMasterSeed);
WriteHeaderField(ms, KdbxHeaderFieldID.TransformSeed, m_pbTransformSeed);
WriteHeaderField(ms, KdbxHeaderFieldID.TransformRounds,
MemUtil.UInt64ToBytes(m_pwDatabase.KeyEncryptionRounds));
WriteHeaderField(ms, KdbxHeaderFieldID.EncryptionIV, m_pbEncryptionIV);
WriteHeaderField(ms, KdbxHeaderFieldID.ProtectedStreamKey, m_pbProtectedStreamKey);
WriteHeaderField(ms, KdbxHeaderFieldID.StreamStartBytes, m_pbStreamStartBytes);
WriteHeaderField(ms, KdbxHeaderFieldID.MasterSeed, m_pbMasterSeed);
WriteHeaderField(ms, KdbxHeaderFieldID.TransformSeed, m_pbTransformSeed);
WriteHeaderField(ms, KdbxHeaderFieldID.TransformRounds,
MemUtil.UInt64ToBytes(m_pwDatabase.KeyEncryptionRounds));
WriteHeaderField(ms, KdbxHeaderFieldID.EncryptionIV, m_pbEncryptionIV);
WriteHeaderField(ms, KdbxHeaderFieldID.ProtectedStreamKey, m_pbProtectedStreamKey);
WriteHeaderField(ms, KdbxHeaderFieldID.StreamStartBytes, m_pbStreamStartBytes);
int nIrsID = (int)m_craInnerRandomStream;
WriteHeaderField(ms, KdbxHeaderFieldID.InnerRandomStreamID,
MemUtil.UInt32ToBytes((uint)nIrsID));
int nIrsID = (int) m_craInnerRandomStream;
WriteHeaderField(ms, KdbxHeaderFieldID.InnerRandomStreamID,
MemUtil.UInt32ToBytes((uint) nIrsID));
WriteHeaderField(ms, KdbxHeaderFieldID.EndOfHeader, new byte[]{
(byte)'\r', (byte)'\n', (byte)'\r', (byte)'\n' });
WriteHeaderField(ms, KdbxHeaderFieldID.EndOfHeader, new byte[]
{
(byte) '\r', (byte) '\n', (byte) '\r', (byte) '\n'
});
byte[] pbHeader = ms.ToArray();
ms.Dispose();
byte[] pbHeader = ms.ToArray();
#if ModernKeePassLibPCL
/*var sha256 = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Sha256);
m_pbHashOfHeader = sha256.HashData(pbHeader);*/
var sha256 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
var buffer = sha256.HashData(CryptographicBuffer.CreateFromByteArray(pbHeader));
CryptographicBuffer.CopyToByteArray(buffer, out m_pbHashOfHeader);
/*var sha256 = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Sha256);
m_pbHashOfHeader = sha256.HashData(pbHeader);*/
var sha256 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
var buffer = sha256.HashData(CryptographicBuffer.CreateFromByteArray(pbHeader));
CryptographicBuffer.CopyToByteArray(buffer, out m_pbHashOfHeader);
#else
SHA256Managed sha256 = new SHA256Managed();
m_pbHashOfHeader = sha256.ComputeHash(pbHeader);
#endif
s.Write(pbHeader, 0, pbHeader.Length);
s.Flush();
s.Write(pbHeader, 0, pbHeader.Length);
s.Flush();
}
}
private static void WriteHeaderField(Stream s, KdbxHeaderFieldID kdbID,
@@ -221,43 +225,42 @@ namespace ModernKeePassLibPCL.Serialization
private Stream AttachStreamEncryptor(Stream s)
{
MemoryStream ms = new MemoryStream();
using (var ms = new MemoryStream())
{
Debug.Assert(m_pbMasterSeed != null);
Debug.Assert(m_pbMasterSeed.Length == 32);
ms.Write(m_pbMasterSeed, 0, 32);
Debug.Assert(m_pbMasterSeed != null);
Debug.Assert(m_pbMasterSeed.Length == 32);
ms.Write(m_pbMasterSeed, 0, 32);
Debug.Assert(m_pwDatabase != null);
Debug.Assert(m_pwDatabase.MasterKey != null);
ProtectedBinary pbinKey = m_pwDatabase.MasterKey.GenerateKey32(
m_pbTransformSeed, m_pwDatabase.KeyEncryptionRounds);
Debug.Assert(pbinKey != null);
if(pbinKey == null)
throw new SecurityException(KLRes.InvalidCompositeKey);
byte[] pKey32 = pbinKey.ReadData();
if((pKey32 == null) || (pKey32.Length != 32))
throw new SecurityException(KLRes.InvalidCompositeKey);
ms.Write(pKey32, 0, 32);
Debug.Assert(m_pwDatabase != null);
Debug.Assert(m_pwDatabase.MasterKey != null);
ProtectedBinary pbinKey = m_pwDatabase.MasterKey.GenerateKey32(
m_pbTransformSeed, m_pwDatabase.KeyEncryptionRounds);
Debug.Assert(pbinKey != null);
if (pbinKey == null)
throw new SecurityException(KLRes.InvalidCompositeKey);
byte[] pKey32 = pbinKey.ReadData();
if ((pKey32 == null) || (pKey32.Length != 32))
throw new SecurityException(KLRes.InvalidCompositeKey);
ms.Write(pKey32, 0, 32);
#if ModernKeePassLibPCL
/*var sha256 = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Sha256);
var aesKey = sha256.HashData(ms.ToArray());*/
var sha256 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
var buffer = sha256.HashData(CryptographicBuffer.CreateFromByteArray(ms.ToArray()));
byte[] aesKey;
CryptographicBuffer.CopyToByteArray(buffer, out aesKey);
/*var sha256 = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Sha256);
var aesKey = sha256.HashData(ms.ToArray());*/
var sha256 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
var buffer = sha256.HashData(CryptographicBuffer.CreateFromByteArray(ms.ToArray()));
byte[] aesKey;
CryptographicBuffer.CopyToByteArray(buffer, out aesKey);
#else
SHA256Managed sha256 = new SHA256Managed();
byte[] aesKey = sha256.ComputeHash(ms.ToArray());
#endif
Array.Clear(pKey32, 0, 32);
ms.Dispose();
Array.Clear(pKey32, 0, 32);
Debug.Assert(CipherPool.GlobalPool != null);
ICipherEngine iEngine = CipherPool.GlobalPool.GetCipher(m_pwDatabase.DataCipherUuid);
if(iEngine == null) throw new SecurityException(KLRes.FileUnknownCipher);
return iEngine.EncryptStream(s, aesKey, m_pbEncryptionIV);
Debug.Assert(CipherPool.GlobalPool != null);
ICipherEngine iEngine = CipherPool.GlobalPool.GetCipher(m_pwDatabase.DataCipherUuid);
if (iEngine == null) throw new SecurityException(KLRes.FileUnknownCipher);
return iEngine.EncryptStream(s, aesKey, m_pbEncryptionIV);
}
}
private void WriteDocument(PwGroup pgDataSource)
@@ -833,7 +836,7 @@ namespace ModernKeePassLibPCL.Serialization
}
[Obsolete]
public static bool WriteEntries(Stream msOutput, PwDatabase pwDatabase,
public static bool WriteEntries(IRandomAccessStream msOutput, PwDatabase pwDatabase,
PwEntry[] vEntries)
{
return WriteEntries(msOutput, vEntries);
@@ -846,7 +849,7 @@ namespace ModernKeePassLibPCL.Serialization
/// <param name="vEntries">Entries to serialize.</param>
/// <returns>Returns <c>true</c>, if the entries were written successfully
/// to the stream.</returns>
public static bool WriteEntries(Stream msOutput, PwEntry[] vEntries)
public static bool WriteEntries(IRandomAccessStream msOutput, PwEntry[] vEntries)
{
/* KdbxFile f = new KdbxFile(pwDatabase);
f.m_format = KdbxFormat.PlainXml;