Exemplo n.º 1
0
        public static string AES_Decrypt(string input, string pass)
        {
            //opposite process
            string[] strInput = input.Split('!');
            //Split IV and cyphertext
            IBuffer BufferIV = CryptographicBuffer.DecodeFromBase64String(strInput[1]);
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            string decrypted = "";

            try
            {
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
                byte[] temp;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 16, 16);
                //temp->hash

                AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

                IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(strInput[0]);
                byte[]  Decrypted;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, BufferIV), out Decrypted);
                decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);
                return(decrypted);
            }
            catch (Exception ex)
            {
                return(null);
            }
            #endregion
        }
Exemplo n.º 2
0
        private CryptographicHash CreateHmacCryptographicHash()
        {
            String algName = AlgorithmNames.SelectionBoxItem.ToString();

            // Create a HashAlgorithmProvider object.
            MacAlgorithmProvider Algorithm = MacAlgorithmProvider.OpenAlgorithm(algName);
            IBuffer vector = CryptographicBuffer.DecodeFromBase64String("uiwyeroiugfyqcajkds897945234==");

            HashingText.Text += "\n*** Sample Hash Algorithm: " + Algorithm.AlgorithmName + "\n";
            HashingText.Text += "    Initial vector:  uiwyeroiugfyqcajkds897945234==\n";

            IBuffer hmacKeyMaterial = CryptographicBuffer.GenerateRandom(Algorithm.MacLength);

            // Compute the hash in one call.
            CryptographicHash hash = Algorithm.CreateHash(hmacKeyMaterial);

            hash.Append(vector);
            digest = hash.GetValueAndReset();

            HashingText.Text += "    Hash:  " + CryptographicBuffer.EncodeToHexString(digest) + "\n";

            return(Algorithm.CreateHash(hmacKeyMaterial));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Verifies the database file headers integrity.
        /// </summary>
        /// <param name="headerHash">The database file headers hash.</param>
        /// <param name="doc">The database content.</param>
        /// <returns><c>true</c> if the header is valid; otherwise, <c>false</c>.</returns>
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="headerHash"/> and <paramref name="doc"/> cannot be <c>null</c>.
        /// </exception>
        public static bool VerifyHeaders(IBuffer headerHash, XDocument doc)
        {
            string meta;

            try
            {
                meta = doc
                       .Elements("KeePassFile")
                       .Elements("Meta")
                       .Elements("HeaderHash")
                       .Select(x => x.Value)
                       .Single();
            }
            catch (InvalidOperationException)
            {
                return(false);
            }

            var expected = CryptographicBuffer
                           .DecodeFromBase64String(meta);

            return(CryptographicBuffer.Compare(expected, headerHash));
        }
Exemplo n.º 4
0
        public static byte[] Encrypt(byte[] data, string keyString)
        {
            //初始化加密算法provider,使用DES_ECB_PKCS7算法
            SymmetricKeyAlgorithmProvider symmetricProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.Rc4);

            //根据keystring生成key
            IBuffer          key    = CryptographicBuffer.DecodeFromBase64String(keyString);
            CryptographicKey cryKey = symmetricProvider.CreateSymmetricKey(key);

            //加密数据
            IBuffer buffer = CryptographicBuffer.CreateFromByteArray(data);

            try
            {
                var encrypted = CryptographicEngine.Encrypt(cryKey, buffer, null);
                buffer.AsStream().Dispose();
                return(encrypted.ToArray());
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 5
0
        public static string AES_Decrypt(string input, string pass)
        {
            if (string.IsNullOrEmpty(input))
            {
                return(null);
            }
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            string decrypted = string.Empty;

            try
            {
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(pass)));
                byte[] temp;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out temp);

                Array.Copy(temp, 0, hash, 0, 16);
                Array.Copy(temp, 0, hash, 15, 16);

                AES = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(hash));

                IBuffer Buffer = CryptographicBuffer.DecodeFromBase64String(input);
                byte[]  Decrypted;
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(AES, Buffer, null), out Decrypted);
                decrypted = System.Text.Encoding.UTF8.GetString(Decrypted, 0, Decrypted.Length);

                return(decrypted);
            }
            catch
            {
                throw new T360Exception(T360ErrorCodes.DecryptionFailed);
            }
        }
Exemplo n.º 6
0
        private CryptographicHash CreateHashCryptographicHash()
        {
            String algName = AlgorithmNames.SelectionBoxItem.ToString();

            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider Algorithm = HashAlgorithmProvider.OpenAlgorithm(algName);
            IBuffer vector = CryptographicBuffer.DecodeFromBase64String("uiwyeroiugfyqcajkds897945234==");

            HashingText.Text += "\n*** Sample Hash Algorithm: " + Algorithm.AlgorithmName + "\n";
            HashingText.Text += "    Initial vector:  uiwyeroiugfyqcajkds897945234==\n";

            // Compute the hash in one call.
            digest = Algorithm.HashData(vector);

            if (digest.Length != Algorithm.HashLength)
            {
                HashingText.Text += "HashAlgorithmProvider failed to generate a hash of proper length!\n";
                return(null);
            }

            HashingText.Text += "    Hash:  " + CryptographicBuffer.EncodeToHexString(digest) + "\n";

            return(Algorithm.CreateHash());
        }
Exemplo n.º 7
0
        public static string Decrypt(string encryptedData, string pw, string iv)
        {
            try
            {
                IBuffer pwBuffer     = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
                IBuffer ivBuffer     = CryptographicBuffer.ConvertStringToBinary(iv, BinaryStringEncoding.Utf16LE);
                IBuffer cipherBuffer = CryptographicBuffer.DecodeFromBase64String(encryptedData);

                // Derive key material for password size 32 bytes for AES256 algorithm
                KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
                // using IV and 1000 iterations
                KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(ivBuffer, 1000);

                // create a key based on original key and derivation parmaters
                CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(pwBuffer);
                IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
                CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);

                // derive buffer to be used for encryption iv from derived password key
                IBuffer ivMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

                SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
                // create symmetric key from derived password material
                CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);

                // decrypt data buffer using symmetric key and derived IV material
                IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, ivMaterial);
                string  result       = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);
                return(result);
            }
            catch (System.Exception)
            {
                System.Diagnostics.Debug.WriteLine("Failed to decrypt file. Throwing exception up the chain.");
                throw;
            }
        }
Exemplo n.º 8
0
        private async Task <Result> SignInWithWindowsHelloAsync()
        {
            string userName = AppSettings.Current.UserName;

            if (IsWindowsHelloEnabled(userName))
            {
                var retrieveResult = await KeyCredentialManager.OpenAsync(userName);

                if (retrieveResult.Status == KeyCredentialStatus.Success)
                {
                    var credential      = retrieveResult.Credential;
                    var challengeBuffer = CryptographicBuffer.DecodeFromBase64String("challenge");
                    var result          = await credential.RequestSignAsync(challengeBuffer);

                    if (result.Status == KeyCredentialStatus.Success)
                    {
                        return(Result.Ok());
                    }
                    return(Result.Error("Windows Hello", $"Cannot sign in with Windows Hello: {result.Status}"));
                }
                return(Result.Error("Windows Hello", $"Cannot sign in with Windows Hello: {retrieveResult.Status}"));
            }
            return(Result.Error("Windows Hello", "Windows Hello is not enabled for current user."));
        }
Exemplo n.º 9
0
        /// <summary>
        /// Decypts a string using a key signed by a KeyCredential.
        /// </summary>
        /// <param name="strProtected">Text to decrypt.</param>
        /// <param name="rResult">KeyCredential object used to sign a key to encrypt the text.</param>
        /// <returns>Decrypted text.</returns>
        internal static async Task <ProtectedString> Decrypt(string strProtected, KeyCredentialRetrievalResult rResult)
        {
            // The same text must be used to decrypt the data
            Assembly assembly  = Assembly.GetExecutingAssembly();
            var      attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
            var      id        = attribute.Value;
            IBuffer  buffMsg   = CryptographicBuffer.ConvertStringToBinary(id, encoding);

            // Start a background thread to ensure Windows Security prompt is opened in foreground
            var _ = Task.Factory.StartNew(() => EnsureForeground());

            // The actual Signing of the string
            KeyCredentialOperationResult opResult = await rResult.Credential.RequestSignAsync(buffMsg);

            if (opResult.Status == KeyCredentialStatus.Success)
            {
                IBuffer signedData = opResult.Result;

                // Creation of the key with the signed string
                SymmetricKeyAlgorithmProvider provider = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
                CryptographicKey myKey = provider.CreateSymmetricKey(signedData);

                // Decryption of the data using the key created (mKey)
                IBuffer buffProtected = CryptographicBuffer.DecodeFromBase64String(strProtected);
                CryptographicBuffer.CopyToByteArray(CryptographicEngine.Decrypt(myKey, buffProtected, null), out var ba);
                ProtectedString ps = new ProtectedString(true, ba);
                MemUtil.ZeroByteArray(ba);
                return(ps);
            }
            else
            {
                WinHelloUnlockExt.opened = true;
                WinHelloErrors(opResult.Status, "Error decrypting the data: ");
                return(null);
            }
        }
Exemplo n.º 10
0
    /// <summary>
    /// Дешифрования текст
    /// </summary>
    /// <param name="SourceText">Исходный (шифрованный) текст</param>
    /// <param name="InputKey">Ключ шифрования</param>
    /// <param name="AlgorytmName">Имя алгоритма дешифрования</param>
    ///
    /// <returns>Расшифрованный (открытый) текст</returns>
    public string DecrypMode(string SourceText, string InputKey, string AlgorytmName, string IV, string KeySize)
    {
        SymmetricKeyAlgorithmProvider Algorithm = SymmetricKeyAlgorithmProvider.OpenAlgorithm(AlgorytmName);
        IBuffer KeyBuffer  = CryptographicBuffer.ConvertStringToBinary(InputKey, BinaryStringEncoding.Utf16LE);
        IBuffer saltBuffer = CryptographicBuffer.ConvertStringToBinary("ll234hl@kljh5:Annc!6002mz", BinaryStringEncoding.Utf16LE);
        //CryptoKey = Algorithm.CreateSymmetricKey(keymaterial);



        KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha512);

        KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 10000);

        CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(KeyBuffer);

        IBuffer keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, Convert.ToUInt32(KeySize) / 8);

        //  string test= CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, keyMaterial);

        CryptoKey = Algorithm.CreateSymmetricKey(keyMaterial);



        if (AlgorytmName.Contains("CBC"))
        {
            IVBuffer = CryptographicBuffer.ConvertStringToBinary(IV, BinaryStringEncoding.Utf16LE);
        }
        // Set the data to encrypt.
        SourceTextBuffer = CryptographicBuffer.DecodeFromBase64String(SourceText);

        // Decrypt
        DecryptBuffer     = Windows.Security.Cryptography.Core.CryptographicEngine.Decrypt(CryptoKey, SourceTextBuffer, IVBuffer);
        DecryptTextOutput = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, DecryptBuffer);//Надо думать над реализацией Base64

        return(DecryptTextOutput);
    }
Exemplo n.º 11
0
        public IBuffer decode64BaseString(string str)
        {
            IBuffer buffFromBase64String = CryptographicBuffer.DecodeFromBase64String(str);

            return(buffFromBase64String);
        }
Exemplo n.º 12
0
        public async void downloadFile(StorageFolder folder, string filename, IList <string> chunkNameList, IList <string> chunkIdList,
                                       IList <string> providerNameList, IList <string> providerTokenList, IList <string> cloudFolderList)
        {
            // Store the result of chunk downloads
            _result = new List <string>();
            // Convert lists to arrays
            string[] chunkNames = new string[chunkNameList.Count];
            chunkNameList.CopyTo(chunkNames, 0);
            string[] chunkIds = new string[chunkIdList.Count];
            chunkIdList.CopyTo(chunkIds, 0);
            string[] providerNames = new string[providerNameList.Count];
            providerNameList.CopyTo(providerNames, 0);
            string[] providerTokens = new string[providerTokenList.Count];
            providerTokenList.CopyTo(providerTokens, 0);
            string[] cloudFolders = new string[cloudFolderList.Count];
            cloudFolderList.CopyTo(cloudFolders, 0);
            int chunkIdx = 0;

            try
            {
                // Open the stream to write
                DataWriter          writer;
                IRandomAccessStream stream = null;
                if (filename == "trustydrive_metadata")
                {
                    //DO NOT write the metadata to a file
                    stream = new InMemoryRandomAccessStream();
                    writer = new DataWriter(stream);
                }
                else
                {
                    StorageFile file = await folder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

                    stream = await file.OpenAsync(FileAccessMode.ReadWrite);

                    writer = new DataWriter(stream.GetOutputStreamAt(0));
                }
                int currentResult;
                int downloadIdx;
                while (chunkIdx < chunkNames.Length)
                {
                    currentResult = _result.Count;
                    // TODO Refactoring to increase the number of concurrent downloads
                    _downloads = new DownloadedChunk[5 * providerNames.Length];
                    for (downloadIdx = 0; downloadIdx < 5 * providerNames.Length && chunkIdx < chunkNames.Length; downloadIdx++, chunkIdx++)
                    {
                        int providerIdx = downloadIdx % providerNames.Length;
                        switch (providerNames[providerIdx])
                        {
                        case "dropbox":
                        case "onedrive":
                            downloadAsync(chunkNames[chunkIdx], providerNames[providerIdx], providerTokens[providerIdx], cloudFolders[providerIdx], downloadIdx);
                            break;

                        case "gdrive":
                            downloadAsync(chunkIds[chunkIdx], providerNames[providerIdx], providerTokens[providerIdx], cloudFolders[providerIdx], downloadIdx);
                            break;
                        }
                    }
                    // Wait the end of the downloads
                    while (_result.Count < currentResult + downloadIdx)
                    {
                        await Task.Delay(TimeSpan.FromMilliseconds(500));
                    }
                    // Write the file by putting chunks together
                    for (int d = 0; d < downloadIdx; d += providerNames.Length)
                    {
                        for (int i = 0; i < _downloads[d].size; i++)
                        {
                            for (int j = d; j < d + providerNames.Length; j++)
                            {
                                if (i < _downloads[j].size)
                                {
                                    writer.WriteByte(_downloads[j].readByte());
                                }
                            }
                        }
                    }
                    for (int d = 0; d < downloadIdx; d++)
                    {
                        _downloads[d].close();
                    }
                }
                await writer.StoreAsync();

                await writer.FlushAsync();

                if (filename == "trustydrive_metadata")
                {
                    // We just download the metadata
                    DataReader reader = new DataReader(stream.GetInputStreamAt(0));
                    reader.UnicodeEncoding = UnicodeEncoding.Utf8;
                    reader.ByteOrder       = ByteOrder.LittleEndian;
                    await reader.LoadAsync((uint)stream.Size);

                    metadata = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, reader.ReadBuffer((uint)stream.Size));
                    metadata = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, CryptographicBuffer.DecodeFromBase64String(metadata));
                }
                else
                {
                    stream.Dispose();
                }
                writer.Dispose();
                _downloaded = true;
            }
            catch
            {
                _result.Add("error");
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Decodes an instance from serialized XML.
        /// </summary>
        /// <param name="xml">The XML to deserialize.</param>
        /// <param name="parameters">Parameters controlling serialization.</param>
        public KdbxBinary(XElement xml, KdbxSerializationParameters parameters)
        {
            // Parse out int ID attribute
            string idAttr = xml?.Attribute("ID")?.Value;

            if (idAttr == null)
            {
                throw new KdbxParseException(
                          ReaderResult.FromXmlParseFailure($"KdbxBinary was missing required ID attribute")
                          );
            }

            if (!Int32.TryParse(idAttr, out int id))
            {
                throw new KdbxParseException(
                          ReaderResult.FromXmlParseFailure($"KdbxBinary ID attribute could not be parsed into an int")
                          );
            }

            Id = id;

            // Parse out bool Compressed attribute
            string compressAttr = xml?.Attribute("Compressed")?.Value ?? "false";

            if (!Boolean.TryParse(compressAttr, out bool compressed))
            {
                throw new KdbxParseException(
                          ReaderResult.FromXmlParseFailure($"KdbxBinary Compressed attribute could not be parsed into a bool")
                          );
            }

            // Parse base64-encoded content
            byte[] content;
            try
            {
                content = CryptographicBuffer.DecodeFromBase64String(xml?.Value)?.ToArray();
                if (content == null)
                {
                    content = new byte[0];
                }
            }
            catch (Exception)
            {
                throw new KdbxParseException(
                          ReaderResult.FromXmlParseFailure($"Could not decode KdbxBinary content as base64 data")
                          );
            }

            // Decompress content if needed
            if (compressed && content.Length > 0)
            {
                byte[] decompressed;
                using (Stream memStream = new MemoryStream(content))
                {
                    using (Stream gzipStream = new GZipStream(memStream, CompressionMode.Decompress))
                    {
                        byte[]      buffer = new byte[1024];
                        int         read   = gzipStream.Read(buffer, 0, buffer.Length);
                        List <byte> bytes  = new List <byte>();
                        while (read > 0)
                        {
                            bytes.AddRange(buffer.Take(read));
                            read = gzipStream.Read(buffer, 0, buffer.Length);
                        }

                        decompressed = bytes.ToArray();
                    }
                }

                content = decompressed;
            }

            this.binaryData = new ProtectedBinary(content, false);
        }
Exemplo n.º 14
0
        public static async Task <bool> SignInWithHelloAsync(string userId, KeyCredentialRetrievalResult retrieveResult = null)
        {
            // Open the existing user key credential.
            if (retrieveResult == null)
            {
                retrieveResult = await KeyCredentialManager.OpenAsync(userId);
            }

            if (retrieveResult.Status != KeyCredentialStatus.Success)
            {
                return(false);
            }

            KeyCredential userCredential = retrieveResult.Credential;

            string publicKeyHint = CalculatePublicKeyHint(userCredential.RetrievePublicKey());

            var challengeResult = await PlayFab.PlayFabClientAPI.GetWindowsHelloChallengeAsync(new GetWindowsHelloChallengeRequest
            {
                PublicKeyHint = publicKeyHint,
                TitleId       = PlayFab.PlayFabSettings.TitleId
            });

            if (challengeResult.Error != null)
            {
                // TODO: Failed to get a challenge, handle the error
                MessageDialog message = new MessageDialog($"Error during getting challenge: {challengeResult.Error.Error}");
                await message.ShowAsync();

                return(false);
            }

            // Sign the challenge using the user's KeyCredential.
            IBuffer challengeBuffer = CryptographicBuffer.DecodeFromBase64String(challengeResult.Result.Challenge);
            KeyCredentialOperationResult opResult = await userCredential.RequestSignAsync(challengeBuffer);

            if (opResult.Status != KeyCredentialStatus.Success)
            {
                MessageDialog message = new MessageDialog("Failed to have user sign the challenge string.");
                await message.ShowAsync();

                return(false);
            }

            // Get the signature.
            IBuffer signatureBuffer = opResult.Result;

            // Send the signature back to the server to confirm our identity.
            // The publicKeyHint tells the server which public key to use to verify the signature.
            var loginResult = await PlayFab.PlayFabClientAPI.LoginWithWindowsHelloAsync(new LoginWithWindowsHelloRequest
            {
                ChallengeSignature = CryptographicBuffer.EncodeToBase64String(signatureBuffer),
                PublicKeyHint      = publicKeyHint
            });

            if (loginResult.Error != null)
            {
                MessageDialog message = new MessageDialog($"Error during login: {loginResult.Error.Error}");
                await message.ShowAsync();

                return(false);
            }

            return(true);
        }
Exemplo n.º 15
0
 public IBuffer GetNonce()
 {
     return(CryptographicBuffer.DecodeFromBase64String(Nonce));
 }
Exemplo n.º 16
0
        /// <summary>
        /// Generates an encryption key derived using a password, a random salt, and specified number of rounds of PBKDF2
        ///
        /// TODO: pass in password via SecureString?
        /// </summary>
        /// <param name="password"></param>
        /// <param name="salt"></param>
        /// <returns></returns>
        public static IBuffer GetEncryptionKey(string password, string salt)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Password is empty");
            }
            if (salt == null || salt.Length == 0)
            {
                throw new ArgumentException("Salt is empty");
            }

            KeyDerivationAlgorithmProvider pbkdf2 = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1);

            IBuffer          buffSecret = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            CryptographicKey key        = pbkdf2.CreateKey(buffSecret);

            KeyDerivationParameters parameters = KeyDerivationParameters.BuildForPbkdf2(CryptographicBuffer.DecodeFromBase64String(salt), PBKDF2_ITERATIONS);

            return(CryptographicEngine.DeriveKeyMaterial(key, parameters, KEY_SIZE_BYTES));
        }
        public void TestIv()
        {
            IBuffer iv = CryptographicBuffer.DecodeFromBase64String(FileEncryptor.GetInitializationVector());

            Assert.AreEqual(16U, iv.Length);
        }
        private string DecryptChannelUri(string uri)
        {
            var channelBuffer = CryptographicBuffer.DecodeFromBase64String(uri);

            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, channelBuffer));
        }
Exemplo n.º 19
0
 public Salsa20RandomGeneratorTests()
 {
     _key = CryptographicBuffer.DecodeFromBase64String(
         "SU2mgYhg2SUHDlM/ReJv49vIYEY6dXVjz7EYlRPqh00=");
 }
Exemplo n.º 20
0
        /// <summary>
        /// Create a new note in the account of the user with the specified developer token.
        /// </summary>
        /// <returns>true if the note was created successfully, false otherwise.</returns>
        public bool createNote(String developerToken)
        {
            try
            {
                try
                {
                    if (!auth(developerToken))
                    {
                        // This is an unrecoverable error - our protocol version is out of date
                        return(false);
                    }
                }
                catch (EDAMUserException eux)
                {
                    // TODO - do proper error handling
                    return(false);
                }

                THttpClient noteStoreTransport = new THttpClient(new Uri(noteStoreUrl));
                noteStoreTransport.CustomHeaders[HttpRequestHeader.UserAgent.ToString()] = USER_AGENT;
                TProtocol        noteStoreProtocol = new TBinaryProtocol(noteStoreTransport);
                NoteStore.Client noteStore         = new NoteStore.Client(noteStoreProtocol);

                // The bytes of the image we want to send up to the service
                // In this test, we use an image hardcoded as a base64-encoded string
                IBuffer imageBuffer = CryptographicBuffer.DecodeFromBase64String(imgBase64);
                byte[]  imageBytes  = WindowsRuntimeBufferExtensions.ToArray(imageBuffer);

                HashAlgorithmProvider provider = HashAlgorithmProvider.OpenAlgorithm("MD5");
                IBuffer hashBuffer             = provider.HashData(imageBuffer);
                byte[]  hash    = WindowsRuntimeBufferExtensions.ToArray(hashBuffer);
                String  hashHex = CryptographicBuffer.EncodeToHexString(hashBuffer);

                Data data = new Data();
                data.Size     = imageBytes.Length;
                data.BodyHash = hash;
                data.Body     = imageBytes;

                Resource resource = new Resource();
                resource.Mime = "image/png";
                resource.Data = data;

                Note note = new Note();
                note.Title   = "Hello, World!";
                note.Content = EDAM_NOTE_PREAMBLE +
                               "<h2>This note is created by the Evernote sample code for Windows Store applications!</h2>" +
                               "<br />" +
                               "<en-media type=\"image/png\" hash=\"" + hashHex + "\"/>" +
                               EDAM_NOTE_POSTAMBLE;
                note.Resources = new List <Resource>();
                note.Resources.Add(resource);

                try
                {
                    noteStore.createNote(authToken, note);
                    return(true);
                }
                catch (EDAMUserException ex)
                {
                    // Handle note creation failure
                }
            }
            catch (TApplicationException tax)
            {
                // Handle generic Thrift error
            }
            catch (TTransportException ttx)
            {
                // Handle networking error
            }
            catch (EDAMSystemException esx)
            {
                // Handle unrecoverable Evernote error (i.e., error not caused by bad user input)
            }

            return(false);
        }
Exemplo n.º 21
0
        public string Decrypt(string toDecrypt, string key)
        {
            IBuffer toDecryptBuffer = CryptographicBuffer.DecodeFromBase64String(toDecrypt);

            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, Decrypt(toDecryptBuffer, key)));
        }
        /// <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)
        {
            IBuffer buffer;

            Scenario1Text.Text = "";

            // Initialize example data.
            byte[] ByteArray    = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
            String base64String = "uiwyeroiugfyqcajkds897945234==";
            String hexString    = "30313233";
            String inputString  = "Input string";

            // Generate random bytes.
            buffer              = CryptographicBuffer.GenerateRandom(32);
            Scenario1Text.Text += "GenerateRandom\n";
            Scenario1Text.Text += "  Buffer: " + CryptographicBuffer.EncodeToHexString(buffer) + "\n\n";

            // Convert from a byte array.
            buffer              = CryptographicBuffer.CreateFromByteArray(ByteArray);
            Scenario1Text.Text += "CreateFromByteArray\n";
            Scenario1Text.Text += "  Buffer: " + CryptographicBuffer.EncodeToHexString(buffer) + "\n\n";

            // Decode a Base64 encoded string to binary.
            buffer              = CryptographicBuffer.DecodeFromBase64String(base64String);
            Scenario1Text.Text += "DecodeFromBase64String\n";
            Scenario1Text.Text += "  Base64 String: " + base64String + "\n";
            Scenario1Text.Text += "  Buffer:        " + CryptographicBuffer.EncodeToHexString(buffer) + "\n\n";

            // Decode a hexadecimal string to binary.
            buffer              = CryptographicBuffer.DecodeFromHexString(hexString);
            Scenario1Text.Text += "DecodeFromHexString\n";
            Scenario1Text.Text += "  Hex String: " + hexString + "\n";
            Scenario1Text.Text += "  Buffer:     " + CryptographicBuffer.EncodeToHexString(buffer) + "\n\n";

            // Convert a string to UTF16BE binary data.
            buffer              = CryptographicBuffer.ConvertStringToBinary(inputString, BinaryStringEncoding.Utf16BE);
            Scenario1Text.Text += "ConvertStringToBinary (Utf16BE)\n";
            Scenario1Text.Text += "  String: " + inputString + "\n";
            Scenario1Text.Text += "  Buffer: " + CryptographicBuffer.EncodeToHexString(buffer) + "\n\n";

            // Convert a string to UTF16LE binary data.
            buffer              = CryptographicBuffer.ConvertStringToBinary(inputString, BinaryStringEncoding.Utf16LE);
            Scenario1Text.Text += "ConvertStringToBinary (Utf16LE)\n";
            Scenario1Text.Text += "  String: " + inputString + "\n";
            Scenario1Text.Text += "  Buffer: " + CryptographicBuffer.EncodeToHexString(buffer) + "\n\n";

            // Convert a string to UTF8 binary data.
            buffer              = CryptographicBuffer.ConvertStringToBinary(inputString, BinaryStringEncoding.Utf8);
            Scenario1Text.Text += "ConvertStringToBinary (Utf8)\n";
            Scenario1Text.Text += "  String: " + inputString + "\n";
            Scenario1Text.Text += "  Buffer: " + CryptographicBuffer.EncodeToHexString(buffer) + "\n\n";

            // Decode from a Base64 encoded string.
            buffer              = CryptographicBuffer.DecodeFromBase64String(base64String);
            Scenario1Text.Text += "DecodeFromBase64String \n";
            Scenario1Text.Text += "  String: " + base64String + "\n";
            Scenario1Text.Text += "  Buffer (Hex): " + CryptographicBuffer.EncodeToHexString(buffer) + "\n\n";
            Scenario1Text.Text += "  Buffer (Base64): " + CryptographicBuffer.EncodeToBase64String(buffer) + "\n\n";

            // Decode from a hexadecimal encoded string.
            buffer              = CryptographicBuffer.DecodeFromHexString(hexString);
            Scenario1Text.Text += "DecodeFromHexString \n";
            Scenario1Text.Text += "  String: " + hexString + "\n";
            Scenario1Text.Text += "  Buffer: " + CryptographicBuffer.EncodeToHexString(buffer) + "\n\n";
        }
Exemplo n.º 23
0
        private void StartResultReceivingThread()
        {
            IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync(
                async(workItem) =>
            {
                while (true)
                {
                    // receive current time at server
                    string recvMsg = await receiveMsgAsync(_resultReceivingSocketReader);
                    Debug.WriteLine(recvMsg);

                    JsonObject obj  = JsonValue.Parse(recvMsg).GetObject();
                    string status   = null;
                    string result   = null;
                    long frameID    = -1;
                    string engineID = null;
                    try
                    {
                        status   = obj.GetNamedString("status");
                        result   = obj.GetNamedString("result");
                        frameID  = (long)obj.GetNamedNumber("frame_id");
                        engineID = obj.GetNamedString("engine_id");
                    }
                    catch (Exception)
                    {
                        Debug.WriteLine("the return message has no status field");
                        return;
                    }

                    ReceivedPacketInfo receivedPacketInfo = new ReceivedPacketInfo(frameID, engineID, status);
                    receivedPacketInfo.setMsgRecvTime(GetTimeMillis());
                    if (!status.Equals("success"))
                    {
                        receivedPacketInfo.setGuidanceDoneTime(GetTimeMillis());
                        await _tokenController.ProcessReceivedPacket(receivedPacketInfo);
                        continue;
                    }

                    if (result != null)
                    {
                        /* parsing result */
                        JsonObject resultJSON = JsonValue.Parse(result).GetObject();

                        // image guidance
                        string imageFeedbackString = null;
                        try
                        {
                            imageFeedbackString = resultJSON.GetNamedString("image");
                        }
                        catch (Exception)
                        {
                            Debug.WriteLine("no image guidance found");
                        }
                        if (imageFeedbackString != null)
                        {
                            IBuffer buffer = CryptographicBuffer.DecodeFromBase64String(imageFeedbackString);
                            //byte[] imageFeedbackBytes;
                            //CryptographicBuffer.CopyToByteArray(buffer, out imageFeedbackBytes);
                            using (var stream = new InMemoryRandomAccessStream())
                            {
                                using (var dataWriter = new DataWriter(stream))
                                {
                                    dataWriter.WriteBuffer(buffer);
                                    await dataWriter.StoreAsync();
                                    BitmapDecoder decoder               = await BitmapDecoder.CreateAsync(stream);
                                    SoftwareBitmap imageFeedback        = await decoder.GetSoftwareBitmapAsync();
                                    SoftwareBitmap imageFeedbackDisplay = SoftwareBitmap.Convert(imageFeedback, BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied);
                                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => {
                                        var sbSource = new SoftwareBitmapSource();
                                        await sbSource.SetBitmapAsync(imageFeedbackDisplay);
                                        GuidanceImage.Source = sbSource;
                                    });
                                }
                            }
                        }
                        // speech guidance
                        string speechFeedback = null;
                        try
                        {
                            speechFeedback = resultJSON.GetNamedString("speech");
                        }
                        catch (Exception)
                        {
                            Debug.WriteLine("no speech guidance found");
                        }

                        if (speechFeedback != null)
                        {
                            SpeechSynthesisStream stream = null;
                            using (SpeechSynthesizer synthesizer = new SpeechSynthesizer())
                            {
                                stream = await synthesizer.SynthesizeTextToStreamAsync(speechFeedback);
                            }

                            // Send the stream to the media object.
                            await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
                                _mediaElement.SetSource(stream, stream.ContentType);
                                _mediaElement.Play();
                            });
                        }

                        receivedPacketInfo.setGuidanceDoneTime(GetTimeMillis());
                        await _tokenController.ProcessReceivedPacket(receivedPacketInfo);
                    }
                }
            });

            // A reference to the work item is cached so that we can trigger a
            // cancellation when the user presses the Cancel button.
            _resultReceivingWorkItem = asyncAction;
        }
Exemplo n.º 24
0
 public Rc4RandomGeneratorTests()
 {
     _key = CryptographicBuffer.DecodeFromBase64String(
         "SfJI2VqUv500zHC3qgkJF5yCTiVmGDdIVdLxcp2uPf8=");
 }
Exemplo n.º 25
0
 private static string Base64Decode(string value)
 {
     return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, CryptographicBuffer.DecodeFromBase64String(value)));
 }
Exemplo n.º 26
0
        public static string FromBase64(string str)
        {
            var buffer = CryptographicBuffer.DecodeFromBase64String(str);

            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffer));
        }
        public void TestSalt()
        {
            IBuffer iv = CryptographicBuffer.DecodeFromBase64String(FileEncryptor.GetRandomSalt());

            Assert.AreEqual(8U, iv.Length);
        }
        /// <summary>
        /// Decode a string that has been base64 encoded
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string DecodeBase64(string data)
        {
#if NETFX_CORE || (ENABLE_IL2CPP && UNITY_WSA_10_0)
            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, CryptographicBuffer.DecodeFromBase64String(data)));
#else
            return(string.Empty);
#endif
        }
Exemplo n.º 29
0
        public static string DecodeFromBase64String(string value)
        {
            IBuffer buffer = CryptographicBuffer.DecodeFromBase64String(value);

            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffer));
        }
Exemplo n.º 30
0
        public string Decode(string encodedString)
        {
            var buffer = CryptographicBuffer.DecodeFromBase64String(encodedString);

            return(CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffer));
        }