Пример #1
0
        private static bool IsBuildType(string str)
        {
            try
            {
                string strFile = UrlUtil.GetFileDirectory(WinUtil.GetExecutable(),
                                                          true, false) + "Application.ini";
                if (!File.Exists(strFile))
                {
                    return(false);
                }

                IniFile f       = IniFile.Read(strFile, StrUtil.Utf8);
                string  strType = f.Get("Application", "Type");
                if (string.IsNullOrEmpty(strType))
                {
                    return(false);
                }

                byte[] pb = CryptoUtil.HashSha256(StrUtil.Utf8.GetBytes(strType.Trim()));
                return(string.Equals(MemUtil.ByteArrayToHexString(pb),
                                     str, StrUtil.CaseIgnoreCmp));
            }
            catch (Exception) { Debug.Assert(false); }

            return(false);
        }
Пример #2
0
        private static string FormatKeyHex(byte[] pb, int cTabs)
        {
            StringBuilder sb  = new StringBuilder();
            string        str = MemUtil.ByteArrayToHexString(pb);

            for (int i = 0; i < str.Length; ++i)
            {
                if ((i & 0x1F) == 0)
                {
                    sb.AppendLine();
                    sb.Append('\t', cTabs);
                }
                else if ((i & 0x07) == 0)
                {
                    sb.Append(' ');
                }

                sb.Append(str[i]);
            }

            sb.AppendLine();
            if (cTabs > 0)
            {
                sb.Append('\t', cTabs - 1);
            }
            return(sb.ToString());
        }
Пример #3
0
        private string CachedFilePath(IOConnectionInfo ioc)
        {
            SHA256Managed sha256         = new SHA256Managed();
            string        iocAsHexString = MemUtil.ByteArrayToHexString(sha256.ComputeHash(Encoding.Unicode.GetBytes(ioc.Path.ToCharArray()))) + ".cache";

            return(_streamCacheDir + iocAsHexString);
        }
Пример #4
0
        public void PopulateGroups(PwGroup groups)
        {
            _groupUuid = new LinkedList <String>();

                        #if INCLUDE_DEBUG_MOVE_GROUPNAME
            groupNameList = new LinkedList <String> {
            };
                        #endif

            FullGroupName = "";
            PwGroup readGroup = groups;
            while (readGroup != null)
            {
                if ((readGroup.ParentGroup != null) ||
                    (readGroup.ParentGroup == null) && (readGroup == groups))
                {
                    FullGroupName = readGroup.Name + "." + FullGroupName;
                }

                _groupUuid.AddFirst(MemUtil.ByteArrayToHexString(readGroup.Uuid.UuidBytes));

                                #if INCLUDE_DEBUG_MOVE_GROUPNAME
                groupNameList.AddFirst(readGroup.Name);
                                #endif

                readGroup = readGroup.ParentGroup;
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.icon_picker);

            GridView currIconGridView = (GridView)FindViewById(Resource.Id.IconGridView);

            currIconGridView.Adapter = new ImageAdapter(this, App.Kp2a.GetDb().KpDatabase);

            currIconGridView.ItemClick += (sender, e) =>
            {
                Intent intent = new Intent();

                if (((ImageAdapter)currIconGridView.Adapter).IsCustomIcon(e.Position))
                {
                    intent.PutExtra(KeyCustomIconId,
                                    MemUtil.ByteArrayToHexString(((ImageAdapter)currIconGridView.Adapter).GetCustomIcon(e.Position).Uuid.UuidBytes));
                }
                else
                {
                    intent.PutExtra(KeyIconId, e.Position);
                }
                SetResult((Result)EntryEditActivity.ResultOkIconPicker, intent);

                Finish();
            };
        }
Пример #6
0
 public string GetPlainSecret()
 {
     if (this.Key.ReadData().Length > 0)
     {
         if (this.Encoding == OtpSecretEncoding.Base32)
         {
             return(Base32Encoding.ToString(this.Key.ReadData()));
         }
         else if (this.Encoding == OtpSecretEncoding.Base64)
         {
             return(Convert.ToBase64String(this.Key.ReadData()));
         }
         else if (this.Encoding == OtpSecretEncoding.Hex)
         {
             return(MemUtil.ByteArrayToHexString(this.Key.ReadData()));
         }
         else if (this.Encoding == OtpSecretEncoding.UTF8)
         {
             return(StrUtil.Utf8.GetString(this.Key.ReadData()));
         }
         else
         {
             return(null);
         }
     }
     return(null);
 }
        private static string IocAsHexString(IOConnectionInfo ioc)
        {
            SHA256Managed sha256         = new SHA256Managed();
            string        iocAsHexString =
                MemUtil.ByteArrayToHexString(sha256.ComputeHash(Encoding.Unicode.GetBytes(ioc.Path.ToCharArray())));

            return(iocAsHexString);
        }
Пример #8
0
        public void TestMemUtil2()
        {
            var i     = 0 - 0x10203040;
            var pbRes = MemUtil.Int32ToBytes(i);

            Assert.That(MemUtil.ByteArrayToHexString(pbRes), Is.EqualTo("C0CFDFEF"));
            Assert.That(MemUtil.BytesToUInt32(pbRes), Is.EqualTo((uint)i));
            Assert.That(MemUtil.BytesToInt32(pbRes), Is.EqualTo(i));
        }
Пример #9
0
        private static string CreateSha1Hash(byte[] data)
        {
            using (var sha1 = new SHA1Managed())
            {
                var hash = sha1.ComputeHash(data);

                return(MemUtil.ByteArrayToHexString(hash));
            }
        }
Пример #10
0
        public void TestSalsa20Cipher()
        {
            var r = CryptoRandom.NewWeakRandom();

            // Test values from official set 6, vector 3
            var pbKey = new byte[] {
                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
            };
            var pbIv = new byte[] { 0x28, 0x8F, 0xF6, 0x5D,
                                    0xC4, 0x2B, 0x92, 0xF9 };
            var pbExpected = new byte[] {
                0x5E, 0x5E, 0x71, 0xF9, 0x01, 0x99, 0x34, 0x03,
                0x04, 0xAB, 0xB2, 0x2A, 0x37, 0xB6, 0x62, 0x5B
            };

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

            c.Encrypt(pb, 0, pb.Length);
            Assert.That(MemUtil.ArraysEqual(pb, pbExpected), Is.True);

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

            var nPos = Salsa20ToPos(c, r, pb.Length, 65536);

            Array.Clear(pb, 0, pb.Length);
            c.Encrypt(pb, 0, pb.Length);
            Assert.That(MemUtil.ArraysEqual(pb, pbExpected2), Is.True);

            Salsa20ToPos(c, r, nPos + pb.Length, 131008);
            Array.Clear(pb, 0, pb.Length);
            c.Encrypt(pb, 0, pb.Length);
            Assert.That(MemUtil.ArraysEqual(pb, pbExpected3), Is.True);

            var       d       = new Dictionary <string, bool>();
            const int nRounds = 100;

            for (var i = 0; i < nRounds; ++i)
            {
                var z = new byte[32];
                c = new Salsa20Cipher(z, MemUtil.Int64ToBytes(i));
                c.Encrypt(z, 0, z.Length);
                d[MemUtil.ByteArrayToHexString(z)] = true;
            }
            Assert.That(d.Count, Is.EqualTo(nRounds));
        }
Пример #11
0
        public static KfxFile Create(ulong uVersion, byte[] pbKey, byte[] pbHash)
        {
            if (pbKey == null)
            {
                throw new ArgumentNullException("pbKey");
            }
            if (pbKey.Length == 0)
            {
                throw new ArgumentOutOfRangeException("pbKey");
            }

            if (uVersion == 0)
            {
                uVersion = 0x0002000000000000;
            }

            // Null hash: generate one, empty hash: store no hash
            if (pbHash == null)
            {
                pbHash = HashData(pbKey);
            }
            VerifyHash(pbKey, pbHash);

            KfxFile kf = new KfxFile();

            if (uVersion == 0x0001000000000000)
            {
                kf.Meta.Version = "1.00";                 // KeePass <= 2.46 used two zeros
            }
            else
            {
                kf.Meta.Version = StrUtil.VersionToString(uVersion, 2);
            }

            if (uVersion == 0x0001000000000000)
            {
                kf.Key.Data.Value = Convert.ToBase64String(pbKey);
            }
            else if (uVersion == 0x0002000000000000)
            {
                kf.Key.Data.Value = FormatKeyHex(pbKey, 3);

                if (pbHash.Length != 0)
                {
                    kf.Key.Data.Hash = MemUtil.ByteArrayToHexString(pbHash);
                }
            }
            else
            {
                throw new NotSupportedException(KLRes.FileVersionUnsupported);
            }

            return(kf);
        }
Пример #12
0
        internal static bool IsDevelopmentSnapshot()
        {
            try
            {
                Assembly asm   = Assembly.GetExecutingAssembly();
                byte[]   pk    = asm.GetName().GetPublicKeyToken();
                string   strPk = MemUtil.ByteArrayToHexString(pk);
                return(!strPk.Equals("fed2ed7716aecf5c", StrUtil.CaseIgnoreCmp));
            }
            catch (Exception) { Debug.Assert(false); }

            return(false);
        }
Пример #13
0
        internal static bool IsStableAssembly()
        {
            try
            {
                Assembly asm   = typeof(Program).Assembly;
                byte[]   pk    = asm.GetName().GetPublicKeyToken();
                string   strPk = MemUtil.ByteArrayToHexString(pk);
                Debug.Assert(string.IsNullOrEmpty(strPk) || (strPk.Length == 16));
                return(string.Equals(strPk, "fed2ed7716aecf5c", StrUtil.CaseIgnoreCmp));
            }
            catch (Exception) { Debug.Assert(false); }

            return(false);
        }
Пример #14
0
        private void CalculateHashString()
        {
            ProtectedStringDictionary stringDict = Entry.Strings;

            byte[] pw     = StrUtil.Utf8.GetBytes(stringDict.ReadSafe(KeePassLib.PwDefs.PasswordField));
            byte[] hashed = null;
            using (SHA1 sha1 = new SHA1Managed())
            {
                hashed = sha1.ComputeHash(pw);
            }
            MemUtil.ZeroByteArray(pw);
            Hash = MemUtil.ByteArrayToHexString(hashed);
            MemUtil.ZeroByteArray(hashed);
        }
Пример #15
0
        private static string HashStream(Stream sourceStream, Stream destStream)
        {
            string hash;

            using (var hashingRemoteStream = new HashingStreamEx(sourceStream, false, new SHA256Managed()))
            {
                hashingRemoteStream.CopyTo(destStream);
                hashingRemoteStream.Close();
                hash = MemUtil.ByteArrayToHexString(hashingRemoteStream.Hash);
                destStream.Position = 0;
            }

            return(hash);
        }
Пример #16
0
        private static bool Is1xPlugin(string strFile)
        {
            try
            {
                byte[] pbFile  = File.ReadAllBytes(strFile);
                byte[] pbSig   = StrUtil.Utf8.GetBytes("KpCreateInstance");
                string strData = MemUtil.ByteArrayToHexString(pbFile);
                string strSig  = MemUtil.ByteArrayToHexString(pbSig);

                return(strData.IndexOf(strSig) >= 0);
            }
            catch (Exception) { Debug.Assert(false); }

            return(false);
        }
Пример #17
0
        public List <KeePassEntry> GetEntries()
        {
            var kpdata = from entry in _db.RootGroup.GetEntries(true)
                         select new KeePassEntry
            {
                Group    = entry.ParentGroup.Name,
                Title    = entry.Strings.ReadSafe("Title"),
                Username = entry.Strings.ReadSafe("UserName"),
                Password = entry.Strings.ReadSafe("Password"),
                URL      = entry.Strings.ReadSafe("URL"),
                Notes    = entry.Strings.ReadSafe("Notes"),
                ID       = MemUtil.ByteArrayToHexString(entry.Uuid.UuidBytes)
            };

            return(kpdata.ToList());
        }
Пример #18
0
        public static string SerializeToString(GoogleColor c)
        {
            if (c == null)
            {
                return(null);
            }

            IFormatter formatter = new BinaryFormatter()
            {
                Binder = new GoogleColor.Binder(),
            };
            MemoryStream ms = new MemoryStream();

            using (ms)
            {
                formatter.Serialize(ms, c);
                return(MemUtil.ByteArrayToHexString(ms.ToArray()));
            }
        }
Пример #19
0
        public MemoryStream GetRemoteDataAndHash(IOConnectionInfo ioc, out string hash)
        {
            MemoryStream remoteData = new MemoryStream();

            using (var remoteStream = _cachedStorage.OpenFileForRead(ioc))
            {
                //note: directly copying to remoteData and hashing causes NullReferenceExceptions in FTP and with Digest auth
                // -> use the temp data approach:
                MemoryStream tempData = new MemoryStream();
                remoteStream.CopyTo(tempData);
                tempData.Position = 0;
                HashingStreamEx hashingRemoteStream = new HashingStreamEx(tempData, false, new SHA256Managed());

                hashingRemoteStream.CopyTo(remoteData);
                hashingRemoteStream.Close();
                hash = MemUtil.ByteArrayToHexString(hashingRemoteStream.Hash);
            }
            remoteData.Position = 0;
            return(remoteData);
        }
Пример #20
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.Setup);
            ImageButton btnTogglePassword = (ImageButton)FindViewById(Resource.Id.toggle_password);

            btnTogglePassword.Click += (sender, e) =>
            {
                _showPassword = !_showPassword;
                MakePasswordMaskedOrVisible();
            };
            Android.Graphics.PorterDuff.Mode mMode = Android.Graphics.PorterDuff.Mode.SrcAtop;
            Android.Graphics.Color           color = new Android.Graphics.Color(224, 224, 224);
            btnTogglePassword.SetColorFilter(color, mMode);


            FindViewById(Resource.Id.button_ok).Click += delegate(object sender, EventArgs args)
            {
                string password;
                if (!TryGetPassword(out password))
                {
                    return;
                }
                string username = FindViewById <EditText>(Resource.Id.etUser).Text;
                new LoadingDialog <object, object, object>(this, GetString(Resource.String.deriving_key), false,
                                                           delegate
                {
                    return
                    (MemUtil.ByteArrayToHexString(
                         MasterPassword.MpAlgorithm.GetKeyForPassword(username, password)));
                },
                                                           delegate(Object res)
                {
                    string derivedKey = (string)res;
                    AddMasterKeeEntry(derivedKey, username);
                }
                                                           ).Execute();
            };
        }
Пример #21
0
        /// <summary>
        /// copies the file in ioc to the local cache. Updates the cache version files and returns the new file hash.
        /// </summary>
        protected string UpdateCacheFromRemote(IOConnectionInfo ioc, string cachedFilePath)
        {
            //note: we might use the file version to check if it's already in the cache and if copying is required.
            //However, this is safer.
            string fileHash;

            //open stream:
            using (Stream remoteFile = _cachedStorage.OpenFileForRead(ioc))
            {
                using (HashingStreamEx cachedFile = new HashingStreamEx(File.Create(cachedFilePath), true, new SHA256Managed()))
                {
                    remoteFile.CopyTo(cachedFile);
                    cachedFile.Close();
                    fileHash = MemUtil.ByteArrayToHexString(cachedFile.Hash);
                }
            }

            //save hash in cache files:
            File.WriteAllText(VersionFilePath(ioc), fileHash);
            File.WriteAllText(BaseVersionFilePath(ioc), fileHash);
            return(fileHash);
        }
Пример #22
0
            public void CommitWrite()
            {
                _committed = true;
                _memoryStream.Close();

                //write file to cache:
                //(note: this might overwrite local changes. It's assumed that a sync operation or check was performed before

                byte[] output = _memoryStream.ToArray();

                string hash;

                using (var hashingStream = new HashingStreamEx(File.Create(_cachingFileStorage.CachedFilePath(_ioc)), true, new SHA256Managed()))
                {
                    hashingStream.Write(output, 0, output.Length);

                    hashingStream.Close();
                    hash = MemUtil.ByteArrayToHexString(hashingStream.Hash);
                }

                File.WriteAllText(_cachingFileStorage.VersionFilePath(_ioc), hash);
                //create another memory stream which is open for reading again
                MemoryStream openMemStream = new MemoryStream(output);

                //update file on remote. This might overwrite changes there as well, see above.
                if (_cachingFileStorage.IsCached(_ioc))
                {
                    //if the file already is in the cache, it's ok if writing to remote fails.
                    _cachingFileStorage.TryUpdateRemoteFile(openMemStream, _ioc, _useFileTransaction, hash);
                }
                else
                {
                    //if not, we don't accept a failure (e.g. invalid credentials would always remain a problem)
                    _cachingFileStorage.UpdateRemoteFile(openMemStream, _ioc, _useFileTransaction, hash);
                }

                openMemStream.Dispose();
            }
Пример #23
0
                public override void Close()
                {
                    if (_closed)
                    {
                        return;
                    }

                    //write file to cache:
                    //(note: this might overwrite local changes. It's assumed that a sync operation or check was performed before
                    string hash;

                    using (var hashingStream = new HashingStreamEx(File.Create(_cachingFileStorage.CachedFilePath(ioc)), true, new SHA256Managed()))
                    {
                        Position = 0;
                        CopyTo(hashingStream);

                        hashingStream.Close();
                        hash = MemUtil.ByteArrayToHexString(hashingStream.Hash);
                    }

                    File.WriteAllText(_cachingFileStorage.VersionFilePath(ioc), hash);
                    //update file on remote. This might overwrite changes there as well, see above.
                    Position = 0;
                    if (_cachingFileStorage.IsCached(ioc))
                    {
                        //if the file already is in the cache, it's ok if writing to remote fails.
                        _cachingFileStorage.TryUpdateRemoteFile(this, ioc, _useFileTransaction, hash);
                    }
                    else
                    {
                        //if not, we don't accept a failure (e.g. invalid credentials would always remain a problem)
                        _cachingFileStorage.UpdateRemoteFile(this, ioc, _useFileTransaction, hash);
                    }

                    base.Close();

                    _closed = true;
                }
Пример #24
0
        void OnMenuSetRootGroup(object sender, EventArgs e)
        {
            PwGroup pg = _host.MainWindow.GetSelectedGroup();

            Debug.Assert(pg != null);
            if (pg == null || pg.Uuid == null || pg.Uuid == PwUuid.Zero)
            {
                return;
            }

            var rid = _host.Database.RecycleBinUuid;

            if (rid != null && rid != PwUuid.Zero && pg.IsOrIsContainedIn(_host.Database.RootGroup.FindGroup(rid, true)))
            {
                MessageBox.Show(@"You can not set this to be the Kee Home Group. Choose a group outside of the Recycle Bin instead.");
                return;
            }
            var conf = _host.Database.GetKPRPCConfig();

            conf.RootUUID = MemUtil.ByteArrayToHexString(pg.Uuid.UuidBytes);
            _host.Database.SetKPRPCConfig(conf);

            _host.MainWindow.UpdateUI(false, null, true, null, true, null, true);
        }
Пример #25
0
        private static void ExtractFile(byte[] pbData, string strTmpRoot,
                                        PlgxPluginInfo plgx)
        {
            MemoryStream ms = new MemoryStream(pbData, false);
            BinaryReader br = new BinaryReader(ms);

            string strPath = null;

            byte[] pbContent = null;

            while (true)
            {
                KeyValuePair <ushort, byte[]> kvp = ReadObject(br);

                if (kvp.Key == PlgxfEOF)
                {
                    break;
                }
                else if (kvp.Key == PlgxfPath)
                {
                    strPath = StrUtil.Utf8.GetString(kvp.Value);
                }
                else if (kvp.Key == PlgxfData)
                {
                    pbContent = kvp.Value;
                }
                else
                {
                    Debug.Assert(false);
                }
            }

            br.Close();
            ms.Close();

            if (!string.IsNullOrEmpty(strPath) && (pbContent != null))
            {
                string strTmpFile = UrlUtil.EnsureTerminatingSeparator(strTmpRoot,
                                                                       false) + UrlUtil.ConvertSeparators(strPath);

                string strTmpDir = UrlUtil.GetFileDirectory(strTmpFile, false, true);
                if (!Directory.Exists(strTmpDir))
                {
                    Directory.CreateDirectory(strTmpDir);
                }

                byte[] pbDecompressed = MemUtil.Decompress(pbContent);
                File.WriteAllBytes(strTmpFile, pbDecompressed);

                // Although the temporary directory will be deleted recursively
                // anyway, add the extracted file here manually, in order to
                // minimize left-over files in case the recursive deletion fails
                // due to locked / in-use files
                Program.TempFilesPool.Add(strTmpFile);

                if (plgx.LogStream != null)
                {
                    using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
                    {
                        byte[] pbMD5 = md5.ComputeHash(pbDecompressed);
                        plgx.LogStream.Write(MemUtil.ByteArrayToHexString(pbMD5));
                        plgx.LogStream.WriteLine(" " + strPath);
                    }
                }
            }
            else
            {
                Debug.Assert(false);
            }
        }
Пример #26
0
        private static string PerformTextTransforms(string strText, SprContext ctx,
                                                    uint uRecursionLevel)
        {
            string        str = strText;
            int           iStart;
            List <string> lParams;

            // {T-CONV:/Text/Raw/} should be the first transformation

            while (ParseAndRemovePlhWithParams(ref str, ctx, uRecursionLevel,
                                               @"{T-CONV:", out iStart, out lParams, true))
            {
                if (lParams.Count < 2)
                {
                    continue;
                }

                try
                {
                    string strNew = lParams[0];
                    string strCmd = lParams[1].ToLower();

                    if ((strCmd == "u") || (strCmd == "upper"))
                    {
                        strNew = strNew.ToUpper();
                    }
                    else if ((strCmd == "l") || (strCmd == "lower"))
                    {
                        strNew = strNew.ToLower();
                    }
                    else if (strCmd == "base64")
                    {
                        byte[] pbUtf8 = StrUtil.Utf8.GetBytes(strNew);
                        strNew = Convert.ToBase64String(pbUtf8);
                    }
                    else if (strCmd == "hex")
                    {
                        byte[] pbUtf8 = StrUtil.Utf8.GetBytes(strNew);
                        strNew = MemUtil.ByteArrayToHexString(pbUtf8);
                    }
                    else if (strCmd == "uri")
                    {
                        strNew = Uri.EscapeDataString(strNew);
                    }
                    else if (strCmd == "uri-dec")
                    {
                        strNew = Uri.UnescapeDataString(strNew);
                    }
                    // "raw": no modification

                    if (strCmd != "raw")
                    {
                        strNew = TransformContent(strNew, ctx);
                    }

                    str = str.Insert(iStart, strNew);
                }
                catch (Exception) { Debug.Assert(false); }
            }

            while (ParseAndRemovePlhWithParams(ref str, ctx, uRecursionLevel,
                                               @"{T-REPLACE-RX:", out iStart, out lParams, true))
            {
                if (lParams.Count < 2)
                {
                    continue;
                }
                if (lParams.Count == 2)
                {
                    lParams.Add(string.Empty);
                }

                try
                {
                    string strNew = Regex.Replace(lParams[0], lParams[1], lParams[2]);
                    strNew = TransformContent(strNew, ctx);
                    str    = str.Insert(iStart, strNew);
                }
                catch (Exception) { }
            }

            return(str);
        }
Пример #27
0
 /// <summary>
 /// Convert the UUID to its string representation.
 /// </summary>
 /// <returns>String containing the UUID value.</returns>
 public string ToHexString()
 {
     return(MemUtil.ByteArrayToHexString(m_pbUuid));
 }
Пример #28
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-1");
            }

#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");
            }

            Dictionary <string, bool> d = new Dictionary <string, bool>();
            const int nRounds           = 100;
            for (int i = 0; i < nRounds; ++i)
            {
                byte[] z = new byte[32];
                c = new Salsa20Cipher(z, BitConverter.GetBytes((long)i));
                c.Encrypt(z, z.Length, true);
                d[MemUtil.ByteArrayToHexString(z)] = true;
            }
            if (d.Count != nRounds)
            {
                throw new SecurityException("Salsa20-4");
            }
#endif
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _design.ApplyDialogTheme();
            SetContentView(Resource.Layout.group_edit);

            ImageButton iconButton = (ImageButton)FindViewById(Resource.Id.icon_button);

            iconButton.Click += (sender, e) =>
            {
                IconPickerActivity.Launch(this);
            };
            _selectedIconId = (int)PwIcon.FolderOpen;

            iconButton.SetImageDrawable(App.Kp2a.GetDb().DrawableFactory.GetIconDrawable(this, App.Kp2a.GetDb().KpDatabase, (PwIcon)_selectedIconId, null, true));

            Button okButton = (Button)FindViewById(Resource.Id.ok);

            okButton.Click += (sender, e) => {
                TextView nameField = (TextView)FindViewById(Resource.Id.group_name);
                String   name      = nameField.Text;

                if (name.Length > 0)
                {
                    Intent intent = new Intent();

                    intent.PutExtra(KeyName, name);
                    intent.PutExtra(KeyIconId, _selectedIconId);
                    if (_selectedCustomIconId != null)
                    {
                        intent.PutExtra(KeyCustomIconId, MemUtil.ByteArrayToHexString(_selectedCustomIconId.UuidBytes));
                    }
                    if (_groupToEdit != null)
                    {
                        intent.PutExtra(KeyGroupUuid, MemUtil.ByteArrayToHexString(_groupToEdit.Uuid.UuidBytes));
                    }

                    SetResult(Result.Ok, intent);

                    Finish();
                }
                else
                {
                    Toast.MakeText(this, Resource.String.error_no_name, ToastLength.Long).Show();
                }
            };

            if (Intent.HasExtra(KeyGroupUuid))
            {
                string groupUuid = Intent.Extras.GetString(KeyGroupUuid);
                _groupToEdit          = App.Kp2a.GetDb().Groups[new PwUuid(MemUtil.HexStringToByteArray(groupUuid))];
                _selectedIconId       = (int)_groupToEdit.IconId;
                _selectedCustomIconId = _groupToEdit.CustomIconUuid;
                TextView nameField = (TextView)FindViewById(Resource.Id.group_name);
                nameField.Text = _groupToEdit.Name;
                App.Kp2a.GetDb().DrawableFactory.AssignDrawableTo(iconButton, this, App.Kp2a.GetDb().KpDatabase, _groupToEdit.IconId, _groupToEdit.CustomIconUuid, false);
                SetTitle(Resource.String.edit_group_title);
            }
            else
            {
                SetTitle(Resource.String.add_group_title);
            }



            Button cancel = (Button)FindViewById(Resource.Id.cancel);

            cancel.Click += (sender, e) => {
                Intent intent = new Intent();
                SetResult(Result.Canceled, intent);

                Finish();
            };
        }
Пример #30
0
        private static void ImportRecords(JsonObject[] v, PwDatabase pd)
        {
            if (v == null)
            {
                Debug.Assert(false); return;
            }

            Dictionary <string, PwGroup> dGroups = new Dictionary <string, PwGroup>();
            string strGroupSep   = MemUtil.ByteArrayToHexString(Guid.NewGuid().ToByteArray());
            string strBackspCode = MemUtil.ByteArrayToHexString(Guid.NewGuid().ToByteArray());

            foreach (JsonObject jo in v)
            {
                if (jo == null)
                {
                    Debug.Assert(false); continue;
                }

                PwEntry pe = new PwEntry(true, true);

                ImportUtil.AppendToField(pe, PwDefs.TitleField,
                                         jo.GetValue <string>("title"), pd);
                ImportUtil.AppendToField(pe, PwDefs.UserNameField,
                                         jo.GetValue <string>("login"), pd);
                ImportUtil.AppendToField(pe, PwDefs.PasswordField,
                                         jo.GetValue <string>("password"), pd);
                ImportUtil.AppendToField(pe, PwDefs.UrlField,
                                         jo.GetValue <string>("login_url"), pd);
                ImportUtil.AppendToField(pe, PwDefs.NotesField,
                                         jo.GetValue <string>("notes"), pd);

                JsonObject joCustom = jo.GetValue <JsonObject>("custom_fields");
                if (joCustom != null)
                {
                    foreach (KeyValuePair <string, object> kvp in joCustom.Items)
                    {
                        string strValue = (kvp.Value as string);
                        if (strValue == null)
                        {
                            Debug.Assert(false); continue;
                        }

                        if (kvp.Key == "TFC:Keeper")
                        {
                            EntryUtil.ImportOtpAuth(pe, strValue, pd);
                        }
                        else
                        {
                            ImportUtil.AppendToField(pe, kvp.Key, strValue, pd);
                        }
                    }
                }

                PwGroup      pg       = null;
                JsonObject[] vFolders = jo.GetValueArray <JsonObject>("folders");
                if ((vFolders != null) && (vFolders.Length >= 1))
                {
                    JsonObject joFolder = vFolders[0];
                    if (joFolder != null)
                    {
                        string strGroup = joFolder.GetValue <string>("folder");
                        if (!string.IsNullOrEmpty(strGroup))
                        {
                            strGroup = strGroup.Replace("\\\\", strBackspCode);
                            strGroup = strGroup.Replace("\\", strGroupSep);
                            strGroup = strGroup.Replace(strBackspCode, "\\");

                            if (!dGroups.TryGetValue(strGroup, out pg))
                            {
                                pg = pd.RootGroup.FindCreateSubTree(strGroup,
                                                                    new string[] { strGroupSep }, true);
                                dGroups[strGroup] = pg;
                            }
                        }
                        else
                        {
                            Debug.Assert(false);
                        }
                    }
                    else
                    {
                        Debug.Assert(false);
                    }
                }
                if (pg == null)
                {
                    pg = pd.RootGroup;
                }

                pg.AddEntry(pe, true);
            }
        }