Пример #1
0
        public override void Write(byte[] pbBuffer, int nOffset, int nCount)
        {
            if (!m_bWriting)
            {
                throw new InvalidOperationException();
            }

#if DEBUG
            byte[] pbOrg = new byte[pbBuffer.Length];
            Array.Copy(pbBuffer, pbOrg, pbBuffer.Length);
#endif

            if ((m_hash != null) && (nCount > 0))
#if !KeePassUAP
            { m_hash.TransformBlock(pbBuffer, nOffset, nCount, pbBuffer, nOffset); }
#else
            { m_hash.AppendData(pbBuffer, nOffset, nCount); }
#endif

#if DEBUG
            Debug.Assert(MemUtil.ArraysEqual(pbBuffer, pbOrg));
#endif

            m_sBaseStream.Write(pbBuffer, nOffset, nCount);
        }
Пример #2
0
        public void TestGenerateKey32()
        {
            var originalKey = new byte[32];
            var expectedKey = new byte[]
            {
                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();
            AesKdf        kdf       = new AesKdf();
            KdfParameters p         = kdf.GetDefaultParameters();

            p.SetUInt64(AesKdf.ParamRounds, rounds);
            p.SetByteArray(AesKdf.ParamSeed, originalKey);
            var key = composite.GenerateKey32(p);

            Assert.NotNull(key);
            var keyData = key.ReadData();

            Assert.True(MemUtil.ArraysEqual(keyData, expectedKey));
        }
Пример #3
0
        public bool Equals(ProtectedBinary other)
        {
            if (other == null)
            {
                return(false);                          // No assert
            }
            if (m_bProtected != other.m_bProtected)
            {
                return(false);
            }
            if (m_uDataLen != other.m_uDataLen)
            {
                return(false);
            }

            byte[] pbL = ReadData();
            byte[] pbR = other.ReadData();
            bool   bEq = MemUtil.ArraysEqual(pbL, pbR);

            MemUtil.ZeroByteArray(pbL);
            MemUtil.ZeroByteArray(pbR);

#if DEBUG
            if (bEq)
            {
                Debug.Assert(GetHashCode() == other.GetHashCode());
            }
#endif

            return(bEq);
        }
Пример #4
0
        private static void TestSalsa20()
        {
            // Test values from official set 6, vector 3
            byte[] pbKey = new byte[32]
            {
                0x0F, 0x62, 0xB5, 0x08, 0x5B, 0xAE, 0x01, 0x54,
                0xA7, 0xFA, 0x4D, 0xA0, 0xF3, 0x46, 0x99, 0xEC,
                0x3F, 0x92, 0xE5, 0x38, 0x8B, 0xDE, 0x31, 0x84,
                0xD7, 0x2A, 0x7D, 0xD0, 0x23, 0x76, 0xC9, 0x1C
            };
            byte[] pbIV = new byte[8]
            {
                0x28, 0x8F, 0xF6, 0x5D,
                0xC4, 0x2B, 0x92, 0xF9
            };
            byte[] pbExpected = new byte[16]
            {
                0x5E, 0x5E, 0x71, 0xF9, 0x01, 0x99, 0x34, 0x03,
                0x04, 0xAB, 0xB2, 0x2A, 0x37, 0xB6, 0x62, 0x5B
            };

            byte[]        pb = new byte[16];
            Salsa20Cipher c  = new Salsa20Cipher(pbKey, pbIV);

            c.Encrypt(pb, pb.Length, false);
            if (!MemUtil.ArraysEqual(pb, pbExpected))
            {
                throw new SecurityException("Salsa20.");
            }

#if DEBUG
            // Extended test in debug mode
            byte[] pbExpected2 = new byte[16]
            {
                0xAB, 0xF3, 0x9A, 0x21, 0x0E, 0xEE, 0x89, 0x59,
                0x8B, 0x71, 0x33, 0x37, 0x70, 0x56, 0xC2, 0xFE
            };
            byte[] pbExpected3 = new byte[16]
            {
                0x1B, 0xA8, 0x9D, 0xBD, 0x3F, 0x98, 0x83, 0x97,
                0x28, 0xF5, 0x67, 0x91, 0xD5, 0xB7, 0xCE, 0x23
            };

            Random r    = new Random();
            int    nPos = Salsa20ToPos(c, r, pb.Length, 65536);
            c.Encrypt(pb, pb.Length, false);
            if (!MemUtil.ArraysEqual(pb, pbExpected2))
            {
                throw new SecurityException("Salsa20-2.");
            }

            nPos = Salsa20ToPos(c, r, nPos + pb.Length, 131008);
            Array.Clear(pb, 0, pb.Length);
            c.Encrypt(pb, pb.Length, true);
            if (!MemUtil.ArraysEqual(pb, pbExpected3))
            {
                throw new SecurityException("Salsa20-3.");
            }
#endif
        }
Пример #5
0
        private static byte[] CreateUserKey()
        {
#if KeePassLibSD
            return(null);
#else
            string strFilePath = GetUserKeyFilePath(true);

            byte[] pbRandomKey = CryptoRandom.Instance.GetRandomBytes(64);
#if NETSTANDARD2_0
            byte[] pbProtectedKey = CryptoUtil.DecryptStringAES(
                m_pbEntropy, CryptoUtil.SharedSecret);
#else
            byte[] pbProtectedKey = ProtectedData.Protect(pbRandomKey,
                                                          m_pbEntropy, DataProtectionScope.CurrentUser);
#endif

            File.WriteAllBytes(strFilePath, pbProtectedKey);

            byte[] pbKey = LoadUserKey(true);
            Debug.Assert(MemUtil.ArraysEqual(pbKey, pbRandomKey));

            MemUtil.ZeroByteArray(pbRandomKey);
            return(pbKey);
#endif
        }
Пример #6
0
        public static void ClearIfOwner()
        {
            // Handle-based detection doesn't work well, because a control
            // or dialog that stored the data may not exist anymore and
            // thus GetClipboardOwner returns null

            /* bool bOwnHandle = false;
             * try
             * {
             *      if(!NativeLib.IsUnix())
             *      {
             *              IntPtr h = NativeMethods.GetClipboardOwner();
             *              bOwnHandle = GlobalWindowManager.HasWindowMW(h);
             *      }
             * }
             * catch(Exception) { Debug.Assert(false); } */

            if (g_pbDataHash == null)
            {
                return;
            }

            byte[] pbCur = ComputeHash();
            if ((pbCur == null) || !MemUtil.ArraysEqual(pbCur, g_pbDataHash))
            {
                return;
            }

            Clear();
        }
Пример #7
0
        public void TestBase32()
        {
            var pbRes = MemUtil.ParseBase32("MY======");
            var pbExp = Encoding.UTF8.GetBytes("f");

            Assert.That(MemUtil.ArraysEqual(pbRes, pbExp), Is.True);

            pbRes = MemUtil.ParseBase32("MZXQ====");
            pbExp = Encoding.UTF8.GetBytes("fo");
            Assert.That(MemUtil.ArraysEqual(pbRes, pbExp), Is.True);

            pbRes = MemUtil.ParseBase32("MZXW6===");
            pbExp = Encoding.UTF8.GetBytes("foo");
            Assert.That(MemUtil.ArraysEqual(pbRes, pbExp), Is.True);

            pbRes = MemUtil.ParseBase32("MZXW6YQ=");
            pbExp = Encoding.UTF8.GetBytes("foob");
            Assert.That(MemUtil.ArraysEqual(pbRes, pbExp), Is.True);

            pbRes = MemUtil.ParseBase32("MZXW6YTB");
            pbExp = Encoding.UTF8.GetBytes("fooba");
            Assert.That(MemUtil.ArraysEqual(pbRes, pbExp), Is.True);

            pbRes = MemUtil.ParseBase32("MZXW6YTBOI======");
            pbExp = Encoding.UTF8.GetBytes("foobar");
            Assert.That(MemUtil.ArraysEqual(pbRes, pbExp), Is.True);

            pbRes = MemUtil.ParseBase32("JNSXSIDQOJXXM2LEMVZCAYTBONSWIIDPNYQG63TFFV2GS3LFEBYGC43TO5XXEZDTFY======");
            pbExp = Encoding.UTF8.GetBytes("Key provider based on one-time passwords.");
            Assert.That(MemUtil.ArraysEqual(pbRes, pbExp), Is.True);
        }
Пример #8
0
        public void TestEncryptStream()
        {
            /*using (var outStream = new MemoryStream(new byte[16]))
             * {
             *  var aes = new StandardAesEngine();
             *  using (var inStream = aes.EncryptStream(outStream, _pbTestKey, _pbIv))
             *  {
             *      new BinaryWriter(inStream).Write(_pbTestData);
             *      Assert.Equal(16, outStream.Position);
             *      outStream.Position = 0;
             *      var outBytes = new BinaryReaderEx(outStream, Encoding.UTF8, string.Empty).ReadBytes(16);
             *      Assert.True(MemUtil.ArraysEqual(outBytes, _pbReferenceCt));
             *  }
             * }*/
            SymmetricAlgorithm a = CryptoUtil.CreateAes();

            if (a.BlockSize != 128) // AES block size
            {
                //Debug.Assert(false);
                a.BlockSize = 128;
            }

            a.IV      = _pbIv;
            a.KeySize = 256;
            a.Key     = _pbTestKey;
            a.Mode    = CipherMode.ECB;
            ICryptoTransform iCrypt = a.CreateEncryptor();

            iCrypt.TransformBlock(_pbTestData, 0, 16, _pbTestData, 0);

            Assert.True(MemUtil.ArraysEqual(_pbTestData, _pbReferenceCt));
        }
Пример #9
0
        private static void AddFile(BinaryWriter writer,
                                    KeyValuePair <string, byte[]> file)
        {
            var stream       = new MemoryStream();
            var streamWriter = new BinaryWriter(stream);

            WriteObject(streamWriter, PlgxfPath, StrUtil.Utf8.GetBytes(file.Key));

            if (file.Value.LongLength >= (long)(int.MaxValue / 2)) // Max 1 GB
            {
                throw new OutOfMemoryException();
            }

            byte[] compressedData = MemUtil.Compress(file.Value);
            WriteObject(streamWriter, PlgxfData, compressedData);

            WriteObject(streamWriter, PlgxfEOF, null);

            WriteObject(writer, PlgxFile, stream.ToArray());
            streamWriter.Close();
            stream.Close();

            if (!MemUtil.ArraysEqual(MemUtil.Decompress(compressedData), file.Value))
            {
                throw new InvalidOperationException();
            }
        }
Пример #10
0
        internal static bool RecalcRequired(this PwEntry pe)
        {
            if (pe.History.UCount < 1)
            {
                return(false);                // no history exists, this is a new entry and not a password change: nothing to do
            }
            byte[] pw_now  = pe.Strings.GetSafe(PwDefs.PasswordField).ReadUtf8();
            byte[] pw_prev = pe.History.GetAt(pe.History.UCount - 1).Strings.GetSafe(PwDefs.PasswordField).ReadUtf8();

            string days_string      = ReadPEDCString(pe);
            string days_string_prev = ReadPEDCString(pe.History.GetAt(pe.History.UCount - 1));

            DateTime expiry_now  = pe.ExpiryTime;
            DateTime expiry_prev = pe.History.GetAt(pe.History.UCount - 1).ExpiryTime;

            //check whether recalculation is required
            bool bNoRecalc = ((expiry_now != expiry_prev) ||         //expiry time has been changed manually
                              ((days_string == days_string_prev) &&  //	PEDCalc password lifetime value is the same as before
                               MemUtil.ArraysEqual(pw_now, pw_prev)));     //	Passwords are the same

            if (bNoRecalc)
            {
                PluginDebug.AddInfo("Recalc expiry date", pe.Uuid.ToString(), "Recalc not required");
            }
            else
            {
                PluginDebug.AddInfo("Recalc expiry date", pe.Uuid.ToString(), "Recalc required");
            }
            return(!bNoRecalc);
        }
Пример #11
0
        public bool Equals(ProtectedBinary other)
        {
            if (other == null)
            {
                return(false);
            }

            if (isProtected != other.isProtected)
            {
                return(false);
            }

            if (dataLength != other.dataLength)
            {
                return(false);
            }

            var pbL = ReadData();
            var pbR = other.ReadData();
            var bEq = MemUtil.ArraysEqual(pbL, pbR);

            MemUtil.ZeroByteArray(pbL);
            MemUtil.ZeroByteArray(pbR);

            return(bEq);
        }
Пример #12
0
        public void TestSha256()
        {
            var r      = CryptoRandom.NewWeakRandom();
            var pbData = new byte[517];

            r.NextBytes(pbData);

            byte[] pbH1;
            using (var h1 = new SHA256Managed())
            {
                var i = 0;
                while (i != pbData.Length)
                {
                    var cb = r.Next(pbData.Length - i) + 1;
                    h1.TransformBlock(pbData, i, cb, pbData, i);
                    i += cb;
                }
                h1.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);
                pbH1 = h1.Hash;
            }

            byte[] pbH2;
            using (var h2 = new SHA256Managed())
            {
                pbH2 = h2.ComputeHash(pbData);
            }

            Assert.That(MemUtil.ArraysEqual(pbH1, pbH2), Is.True);
        }
Пример #13
0
        private static void HmacEval(byte[] pbKey, byte[] pbMsg,
                                     byte[] pbExpc, string strID)
        {
            using (HMACSHA256 h = new HMACSHA256(pbKey))
            {
                h.TransformBlock(pbMsg, 0, pbMsg.Length, pbMsg, 0);
                h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

                byte[] pbHash = h.Hash;
                if (!MemUtil.ArraysEqual(pbHash, pbExpc))
                {
                    throw new SecurityException("HMAC-SHA-256-" + strID);
                }

                // Reuse the object
                h.Initialize();
                h.TransformBlock(pbMsg, 0, pbMsg.Length, pbMsg, 0);
                h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

                pbHash = h.Hash;
                if (!MemUtil.ArraysEqual(pbHash, pbExpc))
                {
                    throw new SecurityException("HMAC-SHA-256-" + strID + "-R");
                }
            }
        }
Пример #14
0
        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.True(MemUtil.ArraysEqual(hs.Hash, sha256HashOfData));
                }
            }
            using (var ms = new MemoryStream(bytes))
            {
                using (var sr = new StreamReader(ms))
                {
                    var read = sr.ReadLine();
                    Assert.Equal(read, data);
                }
            }
        }
Пример #15
0
        internal static byte[] GetHmacKey64(byte[] pbKey, ulong uBlockIndex)
        {
            if (pbKey == null)
            {
                throw new ArgumentNullException("pbKey");
            }
            Debug.Assert(pbKey.Length == 64);

            // We are computing the HMAC using SHA-256, whose internal
            // block size is 512 bits; thus create a key that is 512
            // bits long (using SHA-512)

            byte[] pbBlockKey;
            using (SHA512Managed h = new SHA512Managed())
            {
                byte[] pbIndex = MemUtil.UInt64ToBytes(uBlockIndex);

                h.TransformBlock(pbIndex, 0, pbIndex.Length, pbIndex, 0);
                h.TransformBlock(pbKey, 0, pbKey.Length, pbKey, 0);
                h.TransformFinalBlock(MemUtil.EmptyByteArray, 0, 0);

                pbBlockKey = h.Hash;
            }

#if DEBUG
            byte[] pbZero = new byte[64];
            Debug.Assert((pbBlockKey.Length == 64) && !MemUtil.ArraysEqual(
                             pbBlockKey, pbZero));    // Ensure we own pbBlockKey
#endif
            return(pbBlockKey);
        }
Пример #16
0
        public async Task TestConstruct()
        {
            var expectedKeyData = new byte[]
            {
                0x95, 0x94, 0xdc, 0xb9, 0x91, 0xc6, 0x65, 0xa0,
                0x81, 0xf6, 0x6f, 0xca, 0x07, 0x1a, 0x30, 0xd1,
                0x1d, 0x65, 0xcf, 0x8d, 0x9c, 0x60, 0xfb, 0xe6,
                0x45, 0xfc, 0xc8, 0x92, 0xbd, 0xeb, 0xaf, 0xc3
            };

            await using (var fs = await _file.OpenStreamForWriteAsync())
            {
                await using var sw = new StreamWriter(fs);
                sw.Write(ExpectedFileStart);
                sw.Write(TestKey);
                sw.Write(ExpectedFileEnd);
            }

            var fileBytes = (await FileIO.ReadBufferAsync(_file)).ToArray();

            var keyFile = new KcpKeyFile(fileBytes);
            var keyData = keyFile.KeyData.ReadData();

            Assert.That(MemUtil.ArraysEqual(keyData, expectedKeyData), Is.True);
        }
Пример #17
0
        public static DateTime GetLastPasswordModTime(PwEntry pe)
        {
            if (pe == null)
            {
                Debug.Assert(false); return(TimeUtil.ToUtc(DateTime.Today, false));
            }

            List <PwEntry> l = new List <PwEntry>(pe.History);

            l.Sort(EntryUtil.CompareLastMod);

            DateTime dt = pe.LastModificationTime;

            byte[] pbC = pe.Strings.GetSafe(PwDefs.PasswordField).ReadUtf8();

            for (int i = l.Count - 1; i >= 0; --i)
            {
                PwEntry peH = l[i];

                byte[] pbH   = peH.Strings.GetSafe(PwDefs.PasswordField).ReadUtf8();
                bool   bSame = MemUtil.ArraysEqual(pbH, pbC);
                MemUtil.ZeroByteArray(pbH);

                if (!bSame)
                {
                    break;
                }
                dt = peH.LastModificationTime;
            }

            MemUtil.ZeroByteArray(pbC);
            return(dt);
        }
Пример #18
0
        private static byte[] DecryptSecretPriv(OtpEncryptedData d, string[] vOtps,
                                                int iOtpsOffset, int iOtpsCount)
        {
            if (d == null)
            {
                throw new ArgumentNullException("d");
            }

            byte[] pbTrfKey32 = Convert.FromBase64String(d.TransformationKey);
            byte[] pbKey32    = OtpUtil.KeyFromOtps(vOtps, iOtpsOffset, iOtpsCount,
                                                    pbTrfKey32, d.TransformationRounds);
            byte[] pbIV = Convert.FromBase64String(d.IV);

            byte[] pbSecret = OtpUtil.DecryptData(d.CipherText, pbKey32, pbIV);

            byte[] pbHashTrfKey32 = Convert.FromBase64String(d.PlainTextHashTransformationKey);
            byte[] pbHash         = HashAndTransform(pbSecret, pbHashTrfKey32,
                                                     d.PlainTextHashTransformationRounds);

            if (!MemUtil.ArraysEqual(pbHash, Convert.FromBase64String(d.PlainTextHash)))
            {
                return(null);
            }

            return(pbSecret);
        }
Пример #19
0
        public override int Read(byte[] pbBuffer, int nOffset, int nCount)
        {
            if (m_bWriting)
            {
                Debug.Assert(false); throw new InvalidOperationException();
            }

            int nRead        = m_sBaseStream.Read(pbBuffer, nOffset, nCount);
            int nPartialRead = nRead;

            while ((nRead < nCount) && (nPartialRead != 0))
            {
                nPartialRead = m_sBaseStream.Read(pbBuffer, nOffset + nRead,
                                                  nCount - nRead);
                nRead += nPartialRead;
            }

#if DEBUG
            byte[] pbOrg = new byte[pbBuffer.Length];
            Array.Copy(pbBuffer, pbOrg, pbBuffer.Length);
#endif

            if ((m_hash != null) && (nRead > 0))
            {
                m_hash.TransformBlock(pbBuffer, nOffset, nRead, pbBuffer, nOffset);
            }

#if DEBUG
            Debug.Assert(MemUtil.ArraysEqual(pbBuffer, pbOrg));
#endif

            return(nRead);
        }
Пример #20
0
        public void TestConstruct()
        {
            var expectedKeyData = new byte[]
            {
                0x95, 0x94, 0xdc, 0xb9, 0x91, 0xc6, 0x65, 0xa0,
                0x81, 0xf6, 0x6f, 0xca, 0x07, 0x1a, 0x30, 0xd1,
                0x1d, 0x65, 0xcf, 0x8d, 0x9c, 0x60, 0xfb, 0xe6,
                0x45, 0xfc, 0xc8, 0x92, 0xbd, 0xeb, 0xaf, 0xc3
            };

            var folder = StorageFolder.GetFolderFromPathAsync(Path.GetTempPath()).GetAwaiter().GetResult();
            var file   = folder.CreateFileAsync(TestCreateFile, CreationCollisionOption.ReplaceExisting).GetAwaiter().GetResult();

            using (var fs = file.OpenStreamForWriteAsync().GetAwaiter().GetResult())
            {
                using (var sw = new StreamWriter(fs))
                {
                    sw.Write(ExpectedFileStart);
                    sw.Write(TestKey);
                    sw.Write(ExpectedFileEnd);
                }
            }

            try
            {
                var keyFile = new KcpKeyFile(file);
                var keyData = keyFile.KeyData.ReadData();
                Assert.True(MemUtil.ArraysEqual(keyData, expectedKeyData));
            }
            finally
            {
                file.DeleteAsync().GetAwaiter().GetResult();
            }
        }
Пример #21
0
        public static void ClearIfOwner()
        {
            // If we didn't copy anything or cleared it already: do nothing
            if (m_pbDataHash32 == null)
            {
                return;
            }
            if (m_pbDataHash32.Length != 32)
            {
                Debug.Assert(false); return;
            }

            byte[] pbHash = HashClipboard();             // Hash current contents
            if (pbHash == null)
            {
                return;                            // Unknown data (i.e. no KeePass data)
            }
            if (pbHash.Length != 32)
            {
                Debug.Assert(false); return;
            }

            if (!MemUtil.ArraysEqual(m_pbDataHash32, pbHash))
            {
                return;
            }

            m_pbDataHash32 = null;
            m_strFormat    = null;

            Clear();
        }
Пример #22
0
        public void TestAesKdf()
        {
            // Up to KeePass 2.34, the OtpKeyProv plugin used the public
            // CompositeKey.TransformKeyManaged method (and a finalizing
            // SHA-256 computation), which became an internal method of
            // the AesKdf class in KeePass 2.35, thus OtpKeyProv now
            // uses the AesKdf class; here we ensure that the results
            // are the same
            var r     = CryptoRandom.NewWeakRandom();
            var pbKey = new byte[32];

            r.NextBytes(pbKey);
            var pbSeed = new byte[32];

            r.NextBytes(pbSeed);
            var uRounds = (ulong)r.Next(1, 0x7FFF);

            var pbMan = new byte[pbKey.Length];

            Array.Copy(pbKey, pbMan, pbKey.Length);
            Assert.True(AesKdf.TransformKeyManaged(pbMan, pbSeed, uRounds));
            pbMan = CryptoUtil.HashSha256(pbMan);

            var kdf = new AesKdf();
            var p   = kdf.GetDefaultParameters();

            p.SetUInt64(AesKdf.ParamRounds, uRounds);
            p.SetByteArray(AesKdf.ParamSeed, pbSeed);
            var pbKdf = kdf.Transform(pbKey, p);

            Assert.True(MemUtil.ArraysEqual(pbMan, pbKdf));
        }
Пример #23
0
        private static void TestNativeKeyTransform()
        {
#if DEBUG
            byte[] pbOrgKey = CryptoRandom.Instance.GetRandomBytes(32);
            byte[] pbSeed   = CryptoRandom.Instance.GetRandomBytes(32);
            ulong  uRounds  = (ulong)((new Random()).Next(1, 0x3FFF));

            byte[] pbManaged = new byte[32];
            Array.Copy(pbOrgKey, pbManaged, 32);
            if (CompositeKey.TransformKeyManaged(pbManaged, pbSeed, uRounds) == false)
            {
                throw new SecurityException("Managed transform.");
            }

            byte[] pbNative = new byte[32];
            Array.Copy(pbOrgKey, pbNative, 32);
            if (NativeLib.TransformKey256(pbNative, pbSeed, uRounds) == false)
            {
                return; // Native library not available ("success")
            }
            if (!MemUtil.ArraysEqual(pbManaged, pbNative))
            {
                throw new SecurityException("Native transform.");
            }
#endif
        }
        public void TestAreBinaryObjectsProtected()
        {
            var pbData = _enc.GetBytes("Test Test Test Test");
            var pb     = new ProtectedBinary(true, pbData);

            Assert.That(pb.IsProtected, Is.True);

            var pbDec = pb.ReadData();

            Assert.That(MemUtil.ArraysEqual(pbData, pbDec), Is.True);
            Assert.That(pb.IsProtected, Is.True);

            var pbData2 = _enc.GetBytes("Test Test Test Test");
            var pbData3 = _enc.GetBytes("Test Test Test Test Test");
            var pb2     = new ProtectedBinary(true, pbData2);
            var pb3     = new ProtectedBinary(true, pbData3);

            Assert.That(pb.Equals(pb2), Is.True);
            Assert.That(pb.Equals(pb3), Is.False);
            Assert.That(pb2.Equals(pb3), Is.False);

            Assert.That(pb.GetHashCode(), Is.EqualTo(pb2.GetHashCode()));
            Assert.That(pb.Equals((object)pb2), Is.True);
            Assert.That(pb.Equals((object)pb3), Is.False);
            Assert.That(pb2.Equals((object)pb3), Is.False);
        }
Пример #25
0
        public static byte[] HashSha256(byte[] pbData, int iOffset, int cbCount)
        {
            if (pbData == null)
            {
                throw new ArgumentNullException("pbData");
            }

#if DEBUG
            byte[] pbCopy = new byte[pbData.Length];
            Array.Copy(pbData, pbCopy, pbData.Length);
#endif

            byte[] pbHash;
            using (SHA256Managed h = new SHA256Managed())
            {
                pbHash = h.ComputeHash(pbData, iOffset, cbCount);
            }

#if DEBUG
            // Ensure the data has not been modified
            Debug.Assert(MemUtil.ArraysEqual(pbData, pbCopy));

            Debug.Assert((pbHash != null) && (pbHash.Length == 32));
            byte[] pbZero = new byte[32];
            Debug.Assert(!MemUtil.ArraysEqual(pbHash, pbZero));
#endif

            return(pbHash);
        }
Пример #26
0
        public void TestEncryptStream()
        {
            /*var a = CryptoUtil.CreateAes();
             * if (a.BlockSize != 128) // AES block size
             * {
             *  //Debug.Assert(false);
             *  a.BlockSize = 128;
             * }
             *
             * a.IV = _pbIv;
             * a.KeySize = 256;
             * a.Key = _pbTestKey;
             * a.Mode = CipherMode.ECB;
             * var iCrypt = a.CreateEncryptor();
             *
             * iCrypt.TransformBlock(_pbTestData, 0, 16, _pbTestData, 0);
             *
             * Assert.That(MemUtil.ArraysEqual(_pbTestData, _pbReferenceCt), Is.True);*/

            using var outStream = new MemoryStream();
            var aes = new StandardAesEngine();

            using var inStream = aes.EncryptStream(outStream, _pbTestKey, _pbIv);
            new BinaryWriter(inStream, Encoding.UTF8).Write(_pbTestData);

            //Assert.That(outStream.Position, Is.EqualTo(16));

            //outStream.Position = 0;
            var outBytes = new BinaryReaderEx(outStream, Encoding.UTF8, string.Empty).ReadBytes(16);

            Assert.That(MemUtil.ArraysEqual(outBytes, _pbReferenceCt), Is.True);
        }
        public bool EqualsDictionary(ProtectedBinaryDictionary dict)
        {
            if (dict == null)
            {
                Debug.Assert(false); return(false);
            }

            if (m_vBinaries.Count != dict.m_vBinaries.Count)
            {
                return(false);
            }

            foreach (KeyValuePair <string, ProtectedBinary> kvp in m_vBinaries)
            {
                ProtectedBinary pb = dict.Get(kvp.Key);
                if (pb == null)
                {
                    return(false);
                }
                if (!MemUtil.ArraysEqual(pb.ReadData(), kvp.Value.ReadData()))
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #28
0
        private static byte[] CreateUserKey()
        {
#if KeePassLibSD
            return(null);
#else
            string strFilePath = GetUserKeyFilePath(true);

            byte[] pbRandomKey    = CryptoRandom.Instance.GetRandomBytes(64);
            byte[] pbProtectedKey = CryptoUtil.ProtectData(pbRandomKey,
                                                           m_pbEntropy, DataProtectionScope.CurrentUser);
#if ModernKeePassLib
            var fileStream = StorageFile.GetFileFromPathAsync(strFilePath).GetAwaiter().GetResult().OpenStreamForWriteAsync().GetAwaiter().GetResult();
            fileStream.Write(pbProtectedKey, 0, (int)fileStream.Length);
            fileStream.Dispose();
#else
            File.WriteAllBytes(strFilePath, pbProtectedKey);
#endif

            byte[] pbKey = LoadUserKey(true);
            Debug.Assert(MemUtil.ArraysEqual(pbKey, pbRandomKey));

            MemUtil.ZeroByteArray(pbRandomKey);
            return(pbKey);
#endif
        }
        public override void Write(byte[] pbBuffer, int nOffset, int nCount)
        {
            if (!m_bWriting)
            {
                throw new InvalidOperationException();
            }

#if DEBUG
            byte[] pbOrg = new byte[pbBuffer.Length];
            Array.Copy(pbBuffer, pbOrg, pbBuffer.Length);
#endif

            if ((m_digest != null) && (nCount > 0))
            {
                //TODO check
                m_digest.BlockUpdate(pbBuffer, nOffset, nCount);
            }


#if DEBUG
            Debug.Assert(MemUtil.ArraysEqual(pbBuffer, pbOrg));
#endif

            m_sBaseStream.Write(pbBuffer, nOffset, nCount);
        }
Пример #30
0
        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_bModified)
            {
                DialogResult dr = MessageService.Ask(KPRes.SaveBeforeCloseQuestion,
                                                     PwDefs.ShortProductName, MessageBoxButtons.YesNoCancel);

                if (dr == DialogResult.Yes)
                {
                    OnFileSave(sender, EventArgs.Empty);
                }
                else if (dr == DialogResult.No)
                {
                }
                else
                {
                    e.Cancel = true;
                    return;
                }
            }

            if (m_bURtfWithHighChar && (m_pbEditedData != null) &&
                !MemUtil.ArraysEqual(m_pbEditedData, m_pbData))
            {
                string strUrl = AppHelp.GetOnlineUrl(AppDefs.HelpTopics.KbFaq,
                                                     AppDefs.HelpTopics.KbFaqURtf);
                string strLink = VistaTaskDialog.CreateLink(strUrl, strUrl);
                string strMsg  = KPRes.URtfProblem + MessageService.NewParagraph +
                                 KPRes.URtfCheck + MessageService.NewParagraph +
                                 KPRes.URtfSuggestion + MessageService.NewParagraph +
                                 KPRes.MoreInfo + ":" + MessageService.NewLine;

                VistaTaskDialog dlg = new VistaTaskDialog();
                dlg.AddButton((int)DialogResult.Cancel, KPRes.Ok, null);
                dlg.CommandLinks     = false;
                dlg.Content          = strMsg + strLink;
                dlg.DefaultButtonID  = (int)DialogResult.Cancel;
                dlg.EnableHyperlinks = true;
                dlg.SetIcon(VtdIcon.Warning);
                dlg.WindowTitle = PwDefs.ShortProductName;

                if (!dlg.ShowDialog())
                {
                    MessageService.ShowWarning(strMsg + strUrl);
                }
            }

            Debug.Assert(m_uBlockEvents == 0);

            string strRect = UIUtil.GetWindowScreenRect(this);

            if (strRect != m_strInitialFormRect)            // Don't overwrite ""
            {
                Program.Config.UI.DataEditorRect = strRect;
            }

            m_ctxText.Detach();
            GlobalWindowManager.RemoveWindow(this);
        }