Example #1
0
        public string Decrypt(string metaStr)
        {
            #region metaStr_buffer
            var metaStr_buffer = CryptographicBuffer.DecodeFromHexString(metaStr);
            #endregion

            #region _Key
            var _SymmetricKeyAlgorithmProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);
            var _Key = _SymmetricKeyAlgorithmProvider.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(this._key));
            #endregion

            #region IV_buffer
            var IV_buffer = CryptographicBuffer.CreateFromByteArray(_iv);
            #endregion

            IBuffer _result_buffer = CryptographicEngine.Decrypt(_Key, metaStr_buffer, IV_buffer);
            byte[]  dat            = new byte[256];
            CryptographicBuffer.CopyToByteArray(_result_buffer, out dat);

            #region rebuild string
            List <byte> list_byte = new List <byte>();
            for (int i = 0; i < dat.Count(); i++)
            {
                if (dat[i] != 0)
                {
                    list_byte.Add(dat[i]);
                }
            }
            #endregion
            return(Encoding.UTF8.GetString(list_byte.ToArray()));
        }
Example #2
0
        public async Task Decrypt_should_decrypt_content()
        {
            using (var input = TestFiles.Read("IO.Demo7Pass.kdbx"))
            {
                input.Seek(222);

                var masterSeed = CryptographicBuffer.DecodeFromHexString(
                    "2b4656399a5bdf9fdfe9e8705a34b6f484f9b1b940c3d7cfb7ffece3b634e0ae");
                var masterKey = CryptographicBuffer.DecodeFromHexString(
                    "87730050341ff55c46421f2f2a5f4e1e018d0443d19cacc8682f128f1874d0a4");
                var encryptionIV = CryptographicBuffer.DecodeFromHexString(
                    "f360c29e1a603a6548cfbb28da6fff50");

                using (var decrypted = await FileFormat.Decrypt(input,
                                                                masterKey, masterSeed, encryptionIV))
                {
                    var buffer = WindowsRuntimeBuffer.Create(32);
                    buffer = await decrypted.ReadAsync(buffer, 32);

                    Assert.Equal(
                        "54347fe32f3edbccae1fc60f72c11dafd0a72487b315f9b174ed1073ed67a6e0",
                        CryptographicBuffer.EncodeToHexString(buffer));
                }
            }
        }
        public IAsyncOperation <IInputStream> UriToStreamAsync(System.Uri uri)
        {
            string path = uri.AbsolutePath;

            if (path.StartsWith("/ajax", StringComparison.OrdinalIgnoreCase))
            {
                return(GetObject(new
                {
                    a = 1,
                    b = "b"
                }).AsAsyncOperation());
            }

            string  host             = uri.Host;
            int     delimiter        = host.LastIndexOf('_');
            string  encodedContentId = host.Substring(delimiter + 1);
            IBuffer buffer           = CryptographicBuffer.DecodeFromHexString(encodedContentId);

            string contentIdentifier = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffer);
            string relativePath      = uri.PathAndQuery;

            // For this sample, we will return a stream for a file under the local app data
            // folder, under the subfolder named after the contentIdentifier and having the
            // given relativePath.  Real apps can have more complex behavior, such as handling
            // contentIdentifiers in a custom manner (not necessarily as paths), and generating
            // arbitrary streams that are not read directly from a file.
            System.Uri appDataUri = new Uri("ms-appx:///app" + relativePath);

            return(GetFileStreamFromApplicationUriAsync(appDataUri).AsAsyncOperation());
        }
Example #4
0
        public string getDPK(string username, string password)
        {
            string dpk = "";

            try
            {
                PasswordCredential credential = vault.Retrieve(vaultID, username);

                if (credential != null)
                {
                    credential.RetrievePassword();
                    JObject jsonEntries = JObject.Parse(credential.Password);

                    string saltString = jsonEntries.GetValue(JSONStoreConstants.JSON_STORE_KEY_SALT).ToString();
                    string ivString   = jsonEntries.GetValue(JSONStoreConstants.JSON_STORE_KEY_IV).ToString();

                    IBuffer salt  = CryptographicBuffer.DecodeFromHexString(saltString);
                    IBuffer iv    = CryptographicBuffer.DecodeFromHexString(ivString);
                    IBuffer pwKey = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
                    IBuffer cpk   = passwordToKey(pwKey, salt);

                    // decrypt the dpk
                    dpk = decryptWithKey(cpk, jsonEntries.GetValue(JSONStoreConstants.JSON_STORE_KEY_DPK).ToString(), iv);
                }
            }
            catch (Exception)
            {
                //log error message
            }

            return(dpk);
        }
Example #5
0
        /// <summary>
        /// 将 HexString 转换为 Byte 数组数据
        /// </summary>
        /// <param name="hexString">需要转换的 HexString </param>
        /// <returns>转换完成的 Byte 数组</returns>
        public static Byte[] DecodeFromHexString(String hexString)
        {
            var buff = CryptographicBuffer.DecodeFromHexString(hexString);

            Byte[] data = new Byte[buff.Length];
            CryptographicBuffer.CopyToByteArray(buff, out data);
            return(data);
        }
Example #6
0
        private void ReceiveEncryptionKey(Windows.Networking.Proximity.ProximityDevice sender, Windows.Networking.Proximity.ProximityMessage message)
        {
            string keyString = message.DataAsString;

            this.keyBuff = CryptographicBuffer.DecodeFromHexString(keyString);
            lastSelected.encryptionKey = AppServices.encryptionAlgorithim.CreateSymmetricKey(this.keyBuff);
            this.PrintMessageAsync("Secure connection established! You may now separate your devices.");
        }
Example #7
0
        public static string DESDecrypt(string pwd, string str)
        {
            IBuffer          buffKey       = CryptographicBuffer.ConvertStringToBinary(MD5Encrypt(pwd, MD5MD5EncryptType.Key), BinaryStringEncoding.Utf8);
            IBuffer          cryptBuffer   = CryptographicBuffer.DecodeFromHexString(str);
            CryptographicKey myKey         = Syprvd.CreateSymmetricKey(buffKey);
            IBuffer          decryptBuffer = CryptographicEngine.Decrypt(myKey, cryptBuffer, BuffIni);

            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptBuffer));
        }
Example #8
0
        /// <summary>
        /// This is the click handler for the 'RunSample' button.  It is responsible for executing the sample code.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RunSample_Click(object sender, RoutedEventArgs e)
        {
            String  algName    = AlgorithmNames.SelectionBoxItem.ToString();
            IBuffer Secret     = CryptographicBuffer.ConvertStringToBinary("Master key to derive from", BinaryStringEncoding.Utf8);
            UInt32  TargetSize = UInt32.Parse(KeySizes.SelectionBoxItem.ToString());

            KeyDerivationText.Text = "";
            KeyDerivationParameters Params;

            if (algName.Contains("PBKDF2"))
            {
                // Password based key derivation function (PBKDF2).
                Params = KeyDerivationParameters.BuildForPbkdf2(
                    CryptographicBuffer.GenerateRandom(16), // Salt
                    10000                                   // PBKDF2 Iteration Count
                    );
            }
            else if (algName.Contains("SP800_108"))
            {
                // SP800_108_CTR_HMAC key derivation function.
                Params = KeyDerivationParameters.BuildForSP800108(
                    CryptographicBuffer.ConvertStringToBinary("Label", BinaryStringEncoding.Utf8),               // Label
                    CryptographicBuffer.DecodeFromHexString("303132333435363738")                                // Context
                    );
            }
            else if (algName.Contains("SP800_56A"))
            {
                Params = KeyDerivationParameters.BuildForSP80056a(
                    CryptographicBuffer.ConvertStringToBinary("AlgorithmId", BinaryStringEncoding.Utf8),
                    CryptographicBuffer.ConvertStringToBinary("VParty", BinaryStringEncoding.Utf8),
                    CryptographicBuffer.ConvertStringToBinary("UParty", BinaryStringEncoding.Utf8),
                    CryptographicBuffer.ConvertStringToBinary("SubPubInfo", BinaryStringEncoding.Utf8),
                    CryptographicBuffer.ConvertStringToBinary("SubPrivInfo", BinaryStringEncoding.Utf8)
                    );
            }
            else
            {
                KeyDerivationText.Text += "    An invalid algorithm was specified.\n";
                return;
            }

            // Create a KeyDerivationAlgorithmProvider object for the algorithm specified on input.
            KeyDerivationAlgorithmProvider Algorithm = KeyDerivationAlgorithmProvider.OpenAlgorithm(algName);

            KeyDerivationText.Text += "*** Sample Kdf Algorithm: " + Algorithm.AlgorithmName + "\n";
            KeyDerivationText.Text += "    Secrect Size: " + Secret.Length + "\n";
            KeyDerivationText.Text += "    Target Size: " + TargetSize + "\n";

            // Create a key.
            CryptographicKey key = Algorithm.CreateKey(Secret);

            // Derive a key from the created key.
            IBuffer derived = CryptographicEngine.DeriveKeyMaterial(key, Params, TargetSize);

            KeyDerivationText.Text += "    Derived  " + derived.Length + " bytes\n";
            KeyDerivationText.Text += "    Derived: " + CryptographicBuffer.EncodeToHexString(derived) + "\n";
        }
Example #9
0
        // Decrypt data using the AES_ECB_PKCS7 Algorithim and the given key and return the raw data as a UTF8 encoded string.
        //	the data passed in should be encrypted HEX encoded string that was encrypted using the passed in encryptionKey
        public static string DecryptString(string data, CryptographicKey encryptionKey)
        {
            // Create the algorithim, the key, and a buffer to store the string that we want to encrypt
            IBuffer dataBuff = CryptographicBuffer.DecodeFromHexString(data);

            // Decrypt the data and return it as a string
            IBuffer decryptedBuff = CryptographicEngine.Decrypt(encryptionKey, dataBuff, null);

            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, decryptedBuff));
        }
Example #10
0
        public void Enscrypt_should_compute_the_correct_hash(string password, string saltText, int iterations, string expected)
        {
            var hasher = new PasswordHasher(password);
            var salt   = saltText == "" ? new byte[0] : CryptographicBuffer.DecodeFromHexString(saltText).ToArray();

            var key    = hasher.Enscrypt(salt, iterations);
            var keyHex = CryptographicBuffer.EncodeToHexString(CryptographicBuffer.CreateFromByteArray(key));

            Assert.AreEqual(expected, keyHex, ignoreCase: true);
        }
        public static string TripleDesDecrypt(string key, string ciphertext)
        {
            SymmetricKeyAlgorithmProvider tripleDes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.TripleDesEcb);
            IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf8);
            CryptographicKey symmetricKey = tripleDes.CreateSymmetricKey(keyMaterial);

            IBuffer cipherBuffer = CryptographicBuffer.DecodeFromHexString(ciphertext);

            IBuffer plainBuffer = CryptographicEngine.Decrypt(symmetricKey, cipherBuffer, null);
            return CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, plainBuffer);
        }
Example #12
0
        public static string ComputeHash(string algorithm, string input, bool isByteArray)
        {
            byte[] a;
            if (isByteArray)
            {
                if (input.Length % 2 == 1)
                {
                    throw new Exception("\'" + input + "\' is missing a character to be a valid byte string.");
                }
                // making sure there are even number of characters.
                IBuffer inBuffer = null;
                try
                {
                    // convert from characters to values ('0' -> 0, etc.)
                    inBuffer = CryptographicBuffer.DecodeFromHexString(input);
                }
                catch (Exception e)
                {
                    throw new Exception("\'" + input + "\' is not a valid byte string.", e);
                }
                CryptographicBuffer.CopyToByteArray(inBuffer, out a);
                if (a == null)
                {
                    throw new Exception("\'" + input + "\' could not be converted into a byte stream.");
                }
            }
            else
            {
                int i = 0;
                a = new byte[input.Length];
                foreach (char c in input)
                {
                    a[i++] = (byte)c;
                }
            }

            if (a.Length == 0)
            {
                throw new Exception("Byte array generated from \'" + input + "\' is empty.");
            }

            byte[] encoded = ComputeHash(algorithm, a);
            if (encoded == null)
            {
                throw new Exception("Could not compute hash from \'" + input + "\'.");
            }

            var buffer = CryptographicBuffer.CreateFromByteArray(encoded);
            var ret    = CryptographicBuffer.EncodeToHexString(buffer);

            return(ret);
        }
Example #13
0
        internal string EncryptData(string data)
        {
            if (!SettingsManager.Instance.ContainsKey("EncryptionKey"))
            {
                GenerateEncryptionKey();
            }

            var key =
                CryptographicBuffer.DecodeFromHexString(
                    SettingsManager.Instance.GetValue <string>("EncryptionKey"));

            return(string.Empty);
        }
Example #14
0
        public async Task Headers_should_detect_1x_file_format()
        {
            using (var file = new InMemoryRandomAccessStream())
            {
                await file.WriteAsync(CryptographicBuffer
                                      .DecodeFromHexString("03D9A29A65FB4BB5"));

                file.Seek(0);
                var result = await FileFormat.Headers(file);

                Assert.Null(result.Headers);
                Assert.Equal(FileFormats.KeePass1x, result.Format);
            }
        }
Example #15
0
        public void Enscrypt_should_return_a_number_of_iterations_that_produces_hash(string password, string saltText, int seconds)
        {
            var hasher = new PasswordHasher(password);
            int iterations;
            var salt = saltText == "" ? new byte[0] : CryptographicBuffer.DecodeFromHexString(saltText).ToArray();

            var hash     = hasher.Enscrypt(salt, TimeSpan.FromSeconds(seconds), out iterations);
            var expected = hasher.Enscrypt(salt, iterations);

            var hashText     = CryptographicBuffer.EncodeToHexString(hash.AsBuffer());
            var expectedText = CryptographicBuffer.EncodeToHexString(expected.AsBuffer());

            Assert.AreEqual(expectedText, hashText);
        }
        public IAsyncOperation <IInputStream> UriToStreamAsync(Uri uri)
        {
            string  host             = uri.Host;
            int     delimiter        = host.LastIndexOf('_');
            string  encodedContentId = host.Substring(delimiter + 1);
            IBuffer buffer           = CryptographicBuffer.DecodeFromHexString(encodedContentId);

            string contentIdentifier = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffer);
            string relativePath      = uri.PathAndQuery;

            var appDataUri = new Uri("ms-appx:///" + contentIdentifier + relativePath);

            return(GetFileStreamFromApplicationUriAsync(appDataUri).AsAsyncOperation());
        }
Example #17
0
        public async Task Headers_should_detect_old_format()
        {
            using (var file = new InMemoryRandomAccessStream())
            {
                // Schema; 2.01
                await file.WriteAsync(CryptographicBuffer
                                      .DecodeFromHexString("03D9A29A67FB4BB501000200"));

                file.Seek(0);
                var result = await FileFormat.Headers(file);

                Assert.Null(result.Headers);
                Assert.Equal(FileFormats.OldVersion, result.Format);
            }
        }
Example #18
0
        /// <summary>
        /// A 64-byte keyfile is read as a UTF8 string, which must represent a hex string.
        /// If the string is not hex, null is returned.
        /// Otherwise the hex string is reinterpreted as a byte array and returned.
        /// </summary>
        /// <param name="fileData"></param>
        /// <returns></returns>
        private static IBuffer LoadHexKey32(IBuffer fileData)
        {
            DebugHelper.Assert(fileData.Length == 64);
            try
            {
                string  hexString = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, fileData);
                IBuffer hexData   = CryptographicBuffer.DecodeFromHexString(hexString);

                DebugHelper.Assert(hexData.Length == 32);
                return(hexData);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Example #19
0
        public async Task Should_transform_master_key()
        {
            var data = new PasswordData
            {
                Password = "******",
            };

            var seed = CryptographicBuffer.DecodeFromHexString(
                "9525f6992beb739cbaa73ae6e050627fcaff378d3cd6f6c232d20aa92f6d0927");

            var masterKey = await data.GetMasterKey(seed, 6000);

            Assert.Equal(
                "87730050341ff55c46421f2f2a5f4e1e018d0443d19cacc8682f128f1874d0a4",
                CryptographicBuffer.EncodeToHexString(masterKey));
        }
        /// <summary>
        /// 认证用户授权
        /// </summary>
        /// <returns></returns>
        public static async Task <AuthenticatorState> VerifyUserAsync()
        {
            if (await CheckSupportAsync().ConfigureAwait(false))
            {
                if (ApplicationData.Current.LocalSettings.Values["WindowsHelloPublicKeyForUser"] is string PublicKey)
                {
                    KeyCredentialRetrievalResult RetrievalResult = await KeyCredentialManager.OpenAsync(CredentialName);

                    switch (RetrievalResult.Status)
                    {
                    case KeyCredentialStatus.Success:
                    {
                        KeyCredentialOperationResult OperationResult = await RetrievalResult.Credential.RequestSignAsync(CryptographicBuffer.ConvertStringToBinary(ChallengeText, BinaryStringEncoding.Utf8));

                        if (OperationResult.Status == KeyCredentialStatus.Success)
                        {
                            var Algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha256);
                            var Key       = Algorithm.ImportPublicKey(CryptographicBuffer.DecodeFromHexString(PublicKey));
                            return(CryptographicEngine.VerifySignature(Key, CryptographicBuffer.ConvertStringToBinary(ChallengeText, BinaryStringEncoding.Utf8), OperationResult.Result) ? AuthenticatorState.VerifyPassed : AuthenticatorState.VerifyFailed);
                        }
                        else
                        {
                            return(AuthenticatorState.UnknownError);
                        }
                    }

                    case KeyCredentialStatus.NotFound:
                    {
                        return(AuthenticatorState.CredentialNotFound);
                    }

                    default:
                    {
                        return(AuthenticatorState.UnknownError);
                    }
                    }
                }
                else
                {
                    return(AuthenticatorState.UserNotRegistered);
                }
            }
            else
            {
                return(AuthenticatorState.WindowsHelloUnsupport);
            }
        }
Example #21
0
        public void Enscrypt_should_use_a_number_of_iterations_that_takes_the_specified_duration_to_hash(string password, string saltText, int seconds)
        {
            // This test may sometimes give a false positive and report the method as failing. This is due to the inaccurate way we are measuring the duration.
            var hasher = new PasswordHasher(password);
            int iterations;
            var salt = saltText == "" ? new byte[0] : CryptographicBuffer.DecodeFromHexString(saltText).ToArray();

            var hash = hasher.Enscrypt(salt, TimeSpan.FromSeconds(seconds), out iterations);

            var expected   = DateTime.Now.AddSeconds(seconds);
            var result     = hasher.Enscrypt(salt, iterations);
            var actual     = DateTime.Now;
            var difference = expected - actual;

            Assert.IsTrue(difference < TimeSpan.FromSeconds(1), "hashing by iteration took {0}s less time than the specified duration of {1}s", difference.TotalSeconds, seconds);
            Assert.IsTrue(difference >= TimeSpan.FromSeconds(-1), "hashing by iteration took {0}s more time than the specified duration of {1}s", difference.TotalSeconds, seconds);
        }
Example #22
0
        private string ConvertHexToPassPhrase(NetworkAuthenticationType authType, string presharedKey)
        {
            // If this is a WPA/WPA2-PSK type network then convert the HEX STRING back to a passphrase
            // Note that a 64 character WPA/2 network key is expected as a 128 character HEX-ized that will be
            // converted back to a 64 character network key.
            if ((authType == NetworkAuthenticationType.WpaPsk) ||
                (authType == NetworkAuthenticationType.RsnaPsk))
            {
                var tempBuffer = CryptographicBuffer.DecodeFromHexString(presharedKey);
                var hexString  = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, tempBuffer);
                return(hexString);
            }

            // If this is a WEP key then it should arrive here as a 10 or 26 character hex-ized
            // string which will be passed straight through
            return(presharedKey);
        }
Example #23
0
        public async static Task <String> UnprotectAsync(string strProtected)
        {
            // Create a DataProtectionProvider object.
            DataProtectionProvider Provider = new DataProtectionProvider();

            BinaryStringEncoding encoding = BinaryStringEncoding.Utf8;
            // Decrypt the protected message specified on input.
            IBuffer buffUnprotected = await Provider.UnprotectAsync(CryptographicBuffer.DecodeFromHexString(strProtected));

            // Execution of the SampleUnprotectData method resumes here
            // after the awaited task (Provider.UnprotectAsync) completes
            // Convert the unprotected message from an IBuffer object to a string.

            String strClearText = CryptographicBuffer.ConvertBinaryToString(encoding, buffUnprotected);

            // Return the plaintext string.
            return(strClearText);
        }
Example #24
0
        public void CrcValidation()
        {
            byte[] mlvi    = CryptographicBuffer.DecodeFromHexString("a1c46b44c67a053a").ToArray();
            byte[] salt    = CryptographicBuffer.DecodeFromHexString("5555555555555555").ToArray();
            byte[] bchipid = CryptographicBuffer.DecodeFromHexString("febbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb").ToArray();
            byte[] pubkey  = new byte[BChipMemoryLayout_BCHIP.PUBKEY_MAX_DATA];
            for (int i = 0; i < BChipMemoryLayout_BCHIP.PUBKEY_MAX_DATA; i++)
            {
                pubkey[i] = 0xaa;
            }
            byte[] privkey = new byte[BChipMemoryLayout_BCHIP.PRIVATEKEY_MAX_DATA];
            for (int i = 0; i < BChipMemoryLayout_BCHIP.PRIVATEKEY_MAX_DATA; i++)
            {
                privkey[i] = 0x0;
            }

            byte[]      checksum      = CryptographicBuffer.DecodeFromHexString("6c66ba9ae44d9b").ToArray();
            List <byte> simulatedCard = new List <byte>();

            simulatedCard.AddRange(salt);
            simulatedCard.AddRange(bchipid);
            simulatedCard.AddRange(pubkey);
            simulatedCard.AddRange(privkey);
            simulatedCard.AddRange(checksum);

            BChipMemoryLayout_BCHIP bChipCardData =
                new BChipMemoryLayout_BCHIP(
                    mlvi,
                    simulatedCard.ToArray(),
                    PKStatus.NotAvailable);

            Assert.IsTrue(bChipCardData.crcData.Length == BChipMemoryLayout_BCHIP.CRC_MAX_SIZE);

            for (int i = 0; i < checksum.Length; ++i)
            {
                Assert.AreEqual(checksum[i], bChipCardData.crcData[i]);
            }

            byte[] calculatedChecksum = bChipCardData.GetCardCheckSum();
            for (int i = 0; i < checksum.Length; ++i)
            {
                Assert.AreEqual(checksum[i], calculatedChecksum[i]);
            }
        }
Example #25
0
        /// <summary>
        /// Task to call the "configure-ap" command to a Particle Device in Listening mode
        /// </summary>
        /// <param name="index">Index for this cofiguration</param>
        /// <param name="scanAP">The SoftAPScanAP to use</param>
        /// <param name="password">The unencrypted password for the WiFi connection</param>
        /// <param name="publicKey">The publi key from the device</param>
        /// <returns>Returns response code</returns>
        public static async Task <int> SetConfigureAPAsync(int index, SoftAPScanAP scanAP, string password, SoftAPPublicKey publicKey)
        {
            var configureAP = new SoftAPConfigureAP();

            configureAP.Index    = index;
            configureAP.SSID     = scanAP.SSID;
            configureAP.Security = scanAP.Security;
            configureAP.Channel  = scanAP.Channel;

            if (configureAP.Security != SecurityType.SecurityOpen)
            {
                var algorithm = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithm.RsaPkcs1);

                var publicKeyBuffer = CryptographicBuffer.DecodeFromHexString(publicKey.Data);
                var key             = algorithm.ImportPublicKey(publicKeyBuffer);

                var data = CryptographicBuffer.ConvertStringToBinary(password, System.Text.Encoding.UTF8);

                var    encryptedData     = CryptographicEngine.Encrypt(key, data, null);
                string encryptedPassword = CryptographicBuffer.EncodeToHexString(encryptedData);

                configureAP.Password = encryptedPassword;
            }

            var configureAPString = JsonConvert.SerializeObject(configureAP,
                                                                Formatting.None,
                                                                new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            string responseContent = await SendSoftAPCommandAsync(SetupCommand.ConfigureAP, configureAPString);

            if (responseContent == null)
            {
                return(-1);
            }

            var result       = JToken.Parse(responseContent);
            var responseCode = (int)result["r"];

            return(responseCode);
        }
Example #26
0
 private static byte[] ConvertStringToByteArray(string input, bool isByteArray)
 {
     byte[] byteArray = null;
     if (isByteArray)
     {
         if (input.Length % 2 == 1)
         {
             throw new Exception("\'" + input + "\' is missing a character to be a valid byte string.");
         }
         IBuffer inBuffer = null;
         try
         {
             // convert from characters to values ('0' -> 0, etc.)
             inBuffer = CryptographicBuffer.DecodeFromHexString(input);
         }
         catch (Exception e)
         {
             throw new Exception("\'" + input + "\' is not a valid byte string.", e);
         }
         CryptographicBuffer.CopyToByteArray(inBuffer, out byteArray);
         if (byteArray == null)
         {
             throw new Exception("\'" + input + "\' could not be converted into a byte stream.");
         }
     }
     else
     {
         int i = 0;
         byteArray = new byte[input.Length];
         foreach (char c in input)
         {
             byteArray[i++] = (byte)c;
         }
     }
     if (byteArray.Length == 0)
     {
         throw new Exception("Byte array generated from \'" + input + "\' is empty.");
     }
     return(byteArray);
 }
Example #27
0
        /// <summary>
        /// Loads the specified key file.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// The <paramref name="input"/> parameter cannot be <c>null</c>.
        /// </exception>
        private static async Task <IBuffer> LoadKeyFile(IRandomAccessStream input)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            var buffer = WindowsRuntimeBuffer.Create(1024);

            switch (input.Size)
            {
            case 32:     // Binary key file
                return(await input.ReadAsync(buffer, 32));

            case 64:     // Hex text key file
                buffer = await input.ReadAsync(buffer, 64);

                var hex = CryptographicBuffer.ConvertBinaryToString(
                    BinaryStringEncoding.Utf8, buffer);

                if (IsHexString(hex))
                {
                    return(CryptographicBuffer.DecodeFromHexString(hex));
                }
                break;
            }

            // XML
            input.Seek(0);
            var xml = LoadXmlKeyFile(input);

            if (xml != null)
            {
                return(xml);
            }

            // Random keyfile
            input.Seek(0);
            return(await GetFileHash(input, buffer));
        }
Example #28
0
        public async Task <ByteTuple> DecryptAsync(string publicKey)
        {
            var vault      = new PasswordVault();
            var credential = vault.Retrieve($"{_session}", publicKey);

            var split = credential.Password.Split(';');

            var saltString          = split[0];
            var dataString          = split[1];
            var localPasswordString = split[2];
            var typeString          = split[3];

            var salt          = CryptographicBuffer.DecodeFromHexString(saltString);
            var data          = CryptographicBuffer.DecodeFromHexString(dataString);
            var localPassword = CryptographicBuffer.DecodeFromHexString(localPasswordString);

            var dialog = new SettingsPasscodeConfirmView(passcode => Task.FromResult(false), true);

            var confirm = await dialog.ShowQueuedAsync();

            if (confirm != ContentDialogResult.Primary)
            {
                return(null);
            }

            var secret   = CryptographicBuffer.ConvertStringToBinary(dialog.Passcode, BinaryStringEncoding.Utf8);
            var material = PBKDF2(secret, salt);

            var objAlg = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            var key    = objAlg.CreateSymmetricKey(material);

            var decrypt = CryptographicEngine.Decrypt(key, data, null);

            CryptographicBuffer.CopyToByteArray(decrypt, out byte[] result);
            CryptographicBuffer.CopyToByteArray(localPassword, out byte[] local);


            return(new ByteTuple(result, local));
        }
Example #29
0
        public async Task <LogOnResult> LogOnAsync(string userId, string password)
        {
            using (var client = new HttpClient())
            {
                // Ask the server for a password challenge string
                var requestId         = CryptographicBuffer.EncodeToHexString(CryptographicBuffer.GenerateRandom(4));
                var challengeResponse = await client.GetAsync(new Uri(_clientBaseUrl + "GetPasswordChallenge?requestId=" + requestId));

                challengeResponse.EnsureSuccessStatusCode();
                var challengeEncoded = await challengeResponse.Content.ReadAsStringAsync();

                challengeEncoded = challengeEncoded.Replace(@"""", string.Empty);
                var challengeBuffer = CryptographicBuffer.DecodeFromHexString(challengeEncoded);

                // Use HMAC_SHA512 hash to encode the challenge string using the password being authenticated as the key.
                var provider       = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha512);
                var passwordBuffer = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
                var hmacKey        = provider.CreateKey(passwordBuffer);
                var buffHmac       = CryptographicEngine.Sign(hmacKey, challengeBuffer);
                var hmacString     = CryptographicBuffer.EncodeToHexString(buffHmac);

                // Send the encoded challenge to the server for authentication (to avoid sending the password itself)
                var response = await client.GetAsync(new Uri(_clientBaseUrl + userId + "?requestID=" + requestId + "&passwordHash=" + hmacString));

                // Raise exception if sign in failed
                response.EnsureSuccessStatusCode();

                // On success, return sign in results from the server response packet
                var responseContent = await response.Content.ReadAsStringAsync();

                var result    = JsonConvert.DeserializeObject <UserInfo>(responseContent);
                var serverUri = new Uri(Constants.ServerAddress);
                return(new LogOnResult {
                    UserInfo = result
                });
            }
        }
Example #30
0
        /// <summary>
        /// Gets the file format of the specified stream based on file signature.
        /// </summary>
        /// <param name="buffer">The signature bytes buffer.</param>
        /// <returns>The detected database file format.</returns>
        private static FileFormats CheckSignature(IBuffer buffer)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            // KeePass 1.x
            var oldSignature = CryptographicBuffer
                               .DecodeFromHexString("03D9A29A65FB4BB5");

            if (CryptographicBuffer.Compare(buffer, oldSignature))
            {
                return(FileFormats.KeePass1x);
            }

            // KeePass 2.x pre-release
            var preRelease = CryptographicBuffer
                             .DecodeFromHexString("03D9A29A66FB4BB5");

            if (CryptographicBuffer.Compare(buffer, preRelease))
            {
                return(FileFormats.OldVersion);
            }

            // KeePass 2.x
            var current = CryptographicBuffer
                          .DecodeFromHexString("03D9A29A67FB4BB5");

            if (!CryptographicBuffer.Compare(buffer, current))
            {
                return(FileFormats.NotSupported);
            }

            return(FileFormats.Supported);
        }