#pragma warning restore 1998

        /// <summary>
        /// Gets the device unique identifier.
        /// </summary>
        /// <returns>The discovered device identifier.</returns>
        public virtual string GetDeviceUniqueId()
        {
            string deviceId = null;

            try
            {
                // Per documentation here http://msdn.microsoft.com/en-us/library/windows/apps/jj553431.aspx we are selectively pulling out
                // specific items from the hardware ID.
                StringBuilder builder = new StringBuilder();
                HardwareToken token   = HardwareIdentification.GetPackageSpecificToken(null);
                using (DataReader dataReader = DataReader.FromBuffer(token.Id))
                {
                    int offset = 0;
                    while (offset < token.Id.Length)
                    {
                        // The first two bytes contain the type of the component and the next two bytes contain the value.
                        byte[] hardwareEntry = new byte[4];
                        dataReader.ReadBytes(hardwareEntry);

                        if ((hardwareEntry[0] == 1 ||  // CPU ID of the processor
                             hardwareEntry[0] == 2 ||  // Size of the memory
                             hardwareEntry[0] == 3 ||  // Serial number of the disk device
                             hardwareEntry[0] == 7 ||  // Mobile broadband ID
                             hardwareEntry[0] == 9) && // BIOS
                            hardwareEntry[1] == 0)
                        {
                            if (builder.Length > 0)
                            {
                                builder.Append(',');
                            }

                            builder.Append(hardwareEntry[2]);
                            builder.Append('_');
                            builder.Append(hardwareEntry[3]);
                        }

                        offset += 4;
                    }
                }

                // create a buffer containing the cleartext device ID
                IBuffer clearBuffer = CryptographicBuffer.ConvertStringToBinary(builder.ToString(), BinaryStringEncoding.Utf8);

                // get a provider for the SHA256 algorithm
                HashAlgorithmProvider hashAlgorithmProvider = HashAlgorithmProvider.OpenAlgorithm("SHA256");

                // hash the input buffer
                IBuffer hashedBuffer = hashAlgorithmProvider.HashData(clearBuffer);

                deviceId = CryptographicBuffer.EncodeToBase64String(hashedBuffer);
            }
            catch (Exception)
            {
                // For IoT sceanrios we will alwasy set the device id to IoT
                // Becuase HardwareIdentification API will always throw
                deviceId = "IoT";
            }

            return(deviceId);
        }
Exemple #2
0
        internal static string EncryptThisData(string input, string pass)
        {
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            string encrypted = "";

            try
            {
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(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.CreateFromByteArray(Encoding.UTF8.GetBytes(input));
                encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));

                return(encrypted);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(null);
            }
        }
Exemple #3
0
        /// <summary>
        /// Retrieves the string representation of the hash. (Completes the creation of the hash).
        /// </summary>
        /// <returns>A byte array that is the content of the hash.</returns>
        internal string ComputeHash()
        {
#if RT
            IBuffer md5HashBuff = this.hash.GetValueAndReset();
            return(CryptographicBuffer.EncodeToBase64String(md5HashBuff));
#elif COMMON
            return(null);
#elif DNCP && !XAMIOS
            byte[] bytes;
            if (this.version1MD5)
            {
                this.hash.TransformFinalBlock(new byte[0], 0, 0);
                bytes = this.hash.Hash;
            }
            else
            {
                bytes = this.nativeMD5Hash.TransformFinalBlock(new byte[0], 0, 0);
            }

            // Convert hash to string
            return(Convert.ToBase64String(bytes));
#elif XAMIOS
            this.hash.TransformFinalBlock(new byte[0], 0, 0);
            byte[] bytes = this.hash.Hash;

            return(Convert.ToBase64String(bytes));
#endif
        }
        private string AesEncrypt(string encryptionKey, string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(value);
            }

            IBuffer passwordBuffer = CryptographicBuffer.ConvertStringToBinary(encryptionKey, BinaryStringEncoding.Utf8);
            IBuffer saltBuffer     = CryptographicBuffer.CreateFromByteArray(new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            IBuffer contentBuffer  = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);

            KeyDerivationAlgorithmProvider keyDerivationProvider = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha1);
            KeyDerivationParameters        pbkdf2Parms           = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);

            CryptographicKey keyOriginal  = keyDerivationProvider.CreateKey(passwordBuffer);
            IBuffer          keyMaterial  = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
            CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(passwordBuffer);

            IBuffer ivBuffer = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

            SymmetricKeyAlgorithmProvider aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);

            CryptographicKey aesKey = aes.CreateSymmetricKey(keyMaterial);

            return(CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(aesKey, contentBuffer, ivBuffer)));
        }
Exemple #5
0
        public static string AesDecrypt(this byte[] encrypted, string password, string salt)
        {
            IBuffer pwBuffer     = CryptographicBuffer.ConvertStringToBinary(password, BinaryStringEncoding.Utf8);
            IBuffer saltBuffer   = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
            IBuffer cipherBuffer = CryptographicBuffer.CreateFromByteArray(encrypted);

            // Derive key material for password size 32 bytes for AES256 algorithm
            KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
            // using salt and 1000 iterations
            KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 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 salt from derived password key
            IBuffer saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16);

            // display the keys – because KeyDerivationProvider always gets cleared after each use, they are very similar unforunately
            string keyMaterialString  = CryptographicBuffer.EncodeToBase64String(keyMaterial);
            string saltMaterialString = CryptographicBuffer.EncodeToBase64String(saltMaterial);

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

            // encrypt data buffer using symmetric key and derived salt material
            IBuffer resultBuffer = CryptographicEngine.Decrypt(symmKey, cipherBuffer, saltMaterial);
            string  result       = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, resultBuffer);

            return(result);
        }
        // method to decrypt ciphertext of AES key
        public async void asymmetricDecryptAESKeySender(
            String strAsymmetricAlgName,
            IBuffer buffEncryptedAESKey)
        {
            // Open the algorithm provider for the specified asymmetric algorithm.
            AsymmetricKeyAlgorithmProvider objAsymmAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);

            CryptographicKey pair = objAsymmAlgProv.ImportKeyPair(DataContainer.senderKeyPair);

            try
            {
                // Use the private key embedded in the key pair to decrypt the session key.
                keyMaterialSender = CryptographicEngine.Decrypt(pair, buffEncryptedAESKey, null);
            }
            catch (System.ArgumentException ar)
            {
                Debug.WriteLine(ar.ToString());
                var dialog = new MessageDialog("Error: Key Mismatch. Unable to display new messages.");
                await dialog.ShowAsync();

                // CoreApplication.Exit();
            }


            //convert to string
            keyMaterialStringSender = CryptographicBuffer.EncodeToBase64String(keyMaterialSender);
        }
Exemple #7
0
        public string OAuthSignature(string SigBaseString, SignatureAuthType signType)
        {
            string signingKey = string.Empty;

            //Debug.WriteLine("In OAuthSignature function");

            switch (signType)
            {
            case SignatureAuthType.ConsumerSecret:
                signingKey = string.Format("{0}&{1}", OAuth.OAuthTypes.OAuthConsumerSecret, "");
                break;

            case SignatureAuthType.RequestSecretToken:
                signingKey = string.Format("{0}&{1}", OAuth.OAuthTypes.OAuthConsumerSecret, !string.IsNullOrEmpty(OAuth.OAuthTypes.OAuthRequestTokenSecretKey) ? OAuth.OAuthTypes.OAuthRequestTokenSecretKey : String.Empty);
                break;

            case SignatureAuthType.AccessSecretToken:
                signingKey = string.Format("{0}&{1}", OAuth.OAuthTypes.OAuthConsumerSecret, !string.IsNullOrEmpty(OAuth.OAuthTypes.OAuthAccessTokenSecretKey) ? OAuth.OAuthTypes.OAuthAccessTokenSecretKey : String.Empty);
                break;

            default:
                break;
            }

            IBuffer KeyBuffer = CryptographicBuffer.ConvertStringToBinary(signingKey, BinaryStringEncoding.Utf8);
            MacAlgorithmProvider HmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha1);
            CryptographicKey     MacKey           = HmacSha1Provider.CreateKey(KeyBuffer);
            IBuffer DataToBeSigned  = CryptographicBuffer.ConvertStringToBinary(SigBaseString, BinaryStringEncoding.Utf8);
            IBuffer SignatureBuffer = CryptographicEngine.Sign(MacKey, DataToBeSigned);
            String  Signature       = CryptographicBuffer.EncodeToBase64String(SignatureBuffer);

            //Debug.WriteLine("Signed Signature: " + Signature);
            return(Signature);
        }
    public static byte[] Encrypt(string plainText, string pw, string salt)
    {
        //password buffer is created
        IBuffer pwBuffer = CryptographicBuffer.ConvertStringToBinary(pw, BinaryStringEncoding.Utf8);
        //salt buffer is created
        IBuffer saltBuffer  = CryptographicBuffer.ConvertStringToBinary(salt, BinaryStringEncoding.Utf16LE);
        IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(plainText, BinaryStringEncoding.Utf16LE);
        KeyDerivationAlgorithmProvider keyDerivationProvider = Windows.Security.Cryptography.Core.KeyDerivationAlgorithmProvider.OpenAlgorithm("PBKDF2_SHA1");
        //key parameters are passed
        KeyDerivationParameters pbkdf2Parms = KeyDerivationParameters.BuildForPbkdf2(saltBuffer, 1000);
        //original key is created and stored
        CryptographicKey keyOriginal = keyDerivationProvider.CreateKey(pwBuffer);
        IBuffer          keyMaterial = CryptographicEngine.DeriveKeyMaterial(keyOriginal, pbkdf2Parms, 32);
        CryptographicKey derivedPwKey = keyDerivationProvider.CreateKey(pwBuffer);
        IBuffer          saltMaterial = CryptographicEngine.DeriveKeyMaterial(derivedPwKey, pbkdf2Parms, 16); string keyMaterialString = CryptographicBuffer.EncodeToBase64String(keyMaterial);
        string           saltMaterialString =
            CryptographicBuffer.EncodeToBase64String(saltMaterial);
        //A variable that holds symmetric key provider
        SymmetricKeyAlgorithmProvider symProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");
        //Symmetric key is created and stored in symKey
        CryptographicKey symmKey = symProvider.CreateSymmetricKey(keyMaterial);
        IBuffer          resultBuffer = CryptographicEngine.Encrypt(symmKey, plainBuffer, saltMaterial); byte[] result; CryptographicBuffer.CopyToByteArray(resultBuffer, out result);

        return(result);
    }
Exemple #9
0
        /// <summary>
        /// Sets attributes and encoded base64 data, compressed if needed.
        /// </summary>
        /// <param name="xml">The Binary node to populate with attributes and a value.</param>
        /// <param name="rng">Not used.</param>
        /// <param name="parameters">Parameters for serialization.</param>
        public override void PopulateChildren(XElement xml, IRandomNumberGenerator rng, KdbxSerializationParameters parameters)
        {
            xml.Add(new XAttribute("ID", Id));

            byte[] data = BinaryData.GetClearData();
            if (ShouldCompress(parameters))
            {
                xml.Add(new XAttribute("Compressed", ToKeePassBool(true)));

                // Compress data if needed
                if (data.Length > 0)
                {
                    using (MemoryStream memStream = new MemoryStream())
                    {
                        using (Stream gzipStream = new GZipStream(memStream, CompressionMode.Compress))
                        {
                            gzipStream.Write(data, 0, data.Length);
                        }

                        memStream.Flush();
                        data = memStream.ToArray();
                    }
                }
            }

            string encoded = CryptographicBuffer.EncodeToBase64String(data.AsBuffer());

            xml.SetValue(encoded);
        }
Exemple #10
0
        private static string CalculatePublicKeyHint(IBuffer publicKey)
        {
            HashAlgorithmProvider hashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);
            IBuffer publicKeyHash = hashProvider.HashData(publicKey);

            return(CryptographicBuffer.EncodeToBase64String(publicKeyHash));
        }
        public void AddUser(User user, string password, List <string> preferences, List <string> groups, string type = "User")
        {
            var input = CryptographicBuffer.ConvertStringToBinary(password,
                                                                  BinaryStringEncoding.Utf8);
            var hasher = HashAlgorithmProvider.OpenAlgorithm("SHA256");
            var hashed = hasher.HashData(input);
            var pwd    = CryptographicBuffer.EncodeToBase64String(hashed);
            var sql    = string.Format("INSERT INTO Users(UserName, FirstName, LastName, Email, PhoneNumber," +
                                       "Password, Banned, Type, KeyWordsSearches) " +
                                       "values('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', {6}, '{7}', '{8}');",
                                       user.UserName, user.FirstName, user.LastName, user.Email, user.PhoneNumber, pwd,
                                       false, type, user.KeyWordSearches);

            sql += "SELECT LAST_INSERT_ID();";
            var idUser = _dbWrapper.QueryValue <int>(sql);

            sql = string.Empty;
            foreach (var preference in preferences)
            {
                var id = _dbWrapper.QueryValue <int>(string.Format("Select Id from Preferences Where Name='{0}'", preference));
                sql += string.Format("INSERT INTO ChoosePreferences(IDUser,IDPreference) values('{0}','{1}');", idUser, id);
            }
            foreach (var group in groups)
            {
                var id = _dbWrapper.QueryValue <int>(string.Format("Select Id from Groups Where Name='{0}'", group));
                sql += string.Format("INSERT INTO ChooseGroups(IDUser,IDGroup) values('{0}','{1}');", idUser, id);
            }
            _dbWrapper.QueryValue <object>(sql);
        }
Exemple #12
0
        public static string AES_Encrypt(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 encrypted = 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.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(input));
                encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));

                return(encrypted);
            }
            catch
            {
                throw new T360Exception(T360ErrorCodes.EncryptionFailed);
            }
        }
Exemple #13
0
        /// <summary>
        /// Encrypts the specified input.
        /// </summary>
        /// <param name="input">The input to encrypt.</param>
        /// <param name="password">The password to use.</param>
        /// <returns>Encrypted input</returns>
        public static string Encrypt(string input, string password)
        {
            var rawPassword   = Encoding.UTF8.GetBytes(password);
            var finalPassword = new List <byte>();

            // create password byte array
            for (int byteCounter = 0; byteCounter < 128; byteCounter += 8)
            {
                finalPassword.Add(rawPassword[(byteCounter / 8) % rawPassword.Length]);
            }
            var passwordByteArray = finalPassword.ToArray();

            // create buffer for password for encryption
            var passwordBuffer = CryptographicBuffer.CreateFromByteArray(passwordByteArray);

            // create salt buffer
            var saltBuffer =
                CryptographicBuffer.CreateFromByteArray(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
            var asciiEncoding = Encoding.GetEncoding("ASCII");
            var inputBuffer   = CryptographicBuffer.CreateFromByteArray(asciiEncoding.GetBytes(input));

            // create provider
            var symmetricAlgorithmProvider = SymmetricKeyAlgorithmProvider.OpenAlgorithm("AES_CBC_PKCS7");

            // create key
            var symmetricKey = symmetricAlgorithmProvider.CreateSymmetricKey(passwordBuffer);

            // encrypt data buffer using symmetric key and derived salt material
            var resultBuffer = CryptographicEngine.Encrypt(symmetricKey, inputBuffer, saltBuffer);
            // convert result to encoded string
            string result = CryptographicBuffer.EncodeToBase64String(resultBuffer);

            return(result);
        }
        private string GenerateHash(string input)
        {
            IBuffer buffer     = CryptographicBuffer.ConvertStringToBinary(input, BinaryStringEncoding.Utf8);
            IBuffer hashBuffer = _hashAlgorithm.HashData(buffer);

            return(CryptographicBuffer.EncodeToBase64String(hashBuffer));
        }
Exemple #15
0
        private async void InstallClientCert_Click(object sender, RoutedEventArgs e)
        {
            InstallClientCertCompleted.Visibility = Visibility.Collapsed;

            try
            {
                Uri uri  = new Uri("ms-appx:///Assets/tempClientCert.pfx");
                var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

                IBuffer buffer = await FileIO.ReadBufferAsync(file);

                //byte[] bytes;
                //CryptographicBuffer.CopyToByteArray(buffer, out bytes);

                string pfxData = CryptographicBuffer.EncodeToBase64String(buffer);

                // UserCertificateEnrollmentManager requires 'Shared User certificates' capability.
                //await CertificateEnrollmentManager.UserCertificateEnrollmentManager.ImportPfxDataAsync(...);

                await CertificateEnrollmentManager.ImportPfxDataAsync(
                    pfxData,
                    String.Empty, // password
                    ExportOption.Exportable,
                    KeyProtectionLevel.NoConsent,
                    InstallOptions.None,
                    "tempClientCert");
            }
            catch (Exception ex)
            {
                DisplayException(ex);
            }

            InstallClientCertCompleted.Visibility = Visibility.Visible;
        }
Exemple #16
0
        public String SampleHashMsg(String strAlgName, String strMsg)
        {
            // Convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8);

            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Demonstrate how to retrieve the name of the hashing algorithm.
            String strAlgNameUsed = objAlgProv.AlgorithmName;

            // Hash the message.
            IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

            // Verify that the hash length equals the length specified for the algorithm.
            if (buffHash.Length != objAlgProv.HashLength)
            {
                throw new Exception("There was an error creating the hash");
            }

            // Convert the hash to a string (for display).
            String strHashBase64 = CryptographicBuffer.EncodeToBase64String(buffHash);

            // Return the encoded string
            return(strHashBase64);
        }
Exemple #17
0
        // Encryption and authentication method for recipient
        private void AuthenticatedEncryptionRecipient(
            String strMsg,
            String strAlgName,
            UInt32 keyLength)
        {
            // Open a SymmetricKeyAlgorithmProvider object for the specified algorithm.
            SymmetricKeyAlgorithmProvider objAlgProv = SymmetricKeyAlgorithmProvider.OpenAlgorithm(strAlgName);

            // Create a buffer that contains the data to be encrypted.
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(strMsg, encoding);

            // Generate a symmetric key.
            keyMaterialRecipient       = CryptographicBuffer.GenerateRandom(keyLength);
            keyMaterialStringRecipient = CryptographicBuffer.EncodeToBase64String(keyMaterialRecipient);
            keyRecipient = objAlgProv.CreateSymmetricKey(keyMaterialRecipient);

            // Generate a new nonce value.
            buffNonceRecipient = GetNonce();

            // Encrypt and authenticate the message.
            EncryptedAndAuthenticatedData objEncrypted = CryptographicEngine.EncryptAndAuthenticate(
                keyRecipient,
                buffMsg,
                buffNonceRecipient,
                null);

            encryptedMessageDataRecipient       = objEncrypted.EncryptedData;
            authenticationTagRecipient          = objEncrypted.AuthenticationTag;
            encryptedMessageDataStringRecipient = CryptographicBuffer.EncodeToBase64String(encryptedMessageDataRecipient);
            authenticationTagStringRecipient    = CryptographicBuffer.EncodeToBase64String(authenticationTagRecipient);
            nonceStringRecipient = CryptographicBuffer.EncodeToBase64String(buffNonceRecipient);
        }
Exemple #18
0
        public static string WinRTEncrypt(string publicKey, string data)
        {
            string strIn = "Input String";

            IBuffer buffUTF8 = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8);
            String  strUTF8  = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, buffUTF8);

            IBuffer keyBuffer = CryptographicBuffer.DecodeFromBase64String(publicKey);

            AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            //AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha256);

            CryptographicKey key = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);

            IBuffer plainBuffer     = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8);
            IBuffer encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null);


            //string result = CryptographicBuffer.EncodeToHexString(encryptedBuffer);

            //string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, encryptedBuffer);

            string result = CryptographicBuffer.EncodeToBase64String(encryptedBuffer);

            return(result);
        }
Exemple #19
0
        public static string AES_Encrypt(string input, string pass)
        {
            SymmetricKeyAlgorithmProvider sap = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      aes;
            HashAlgorithmProvider hap      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     hash_AES = hap.CreateHash();

            string encrypted = "";

            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.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(input));
                encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(aes, buffer, null));

                return(encrypted);
            }
            catch
            {
                return(null);
            }
        }
Exemple #20
0
        public string WinRTEncrypt1(byte[] test, string publicKey)
        {
            string strIn = "))))";

            IBuffer plainBuffer = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8);

            strIn = CryptographicBuffer.EncodeToBase64String(plainBuffer);

            plainBuffer = CryptographicBuffer.ConvertStringToBinary(strIn, BinaryStringEncoding.Utf8);


            // <asymmetric>
            AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaPkcs1);
            //AsymmetricKeyAlgorithmProvider asym = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaOaepSha256);

            IBuffer          keyBuffer       = CryptographicBuffer.DecodeFromBase64String(publicKey);
            CryptographicKey key             = asym.ImportPublicKey(keyBuffer, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey);
            IBuffer          encryptedBuffer = CryptographicEngine.Encrypt(key, plainBuffer, null);

            // </asymmetric>

            /*
             * // <symmetric>
             * SymmetricKeyAlgorithmProvider sym = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbc);
             *
             * IBuffer temp_key = CryptographicBuffer.ConvertStringToBinary("1234567890", BinaryStringEncoding.Utf8);
             *
             * string keyblyad = CryptographicBuffer.EncodeToBase64String(temp_key);
             *
             * IBuffer key_buffer = CryptographicBuffer.ConvertStringToBinary(keyblyad, BinaryStringEncoding.Utf8);
             *
             * CryptographicKey key1 = sym.CreateSymmetricKey(key_buffer);
             * IBuffer encryptedBuffer = CryptographicEngine.Encrypt(key1, plainBuffer, null);
             * // </symmetric>
             */


            byte[] lole = encryptedBuffer.ToArray();

            string lol = "";

            for (int i = 0; i < lole.Length; i++)
            {
                lol += (char)lole[i];
            }

            textBox3.Text = lol;

            //string result = CryptographicBuffer.EncodeToHexString(encryptedBuffer);

            //string result = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf16LE, encryptedBuffer);

            string result = CryptographicBuffer.EncodeToBase64String(encryptedBuffer);

            //result = CryptographicBuffer.EncodeToBase64String(encryptedSymBuffer);

            //string result = CryptographicBuffer.EncodeToBase64String(buffUTF8);

            return(result);
        }
        public async Task <DavItem> Upload(Uri url, StorageFile file)
        {
            if (!url.IsAbsoluteUri)
            {
                url = new Uri(_serverUrl, url);
            }

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.CostPolicy = ExecutionContext.Instance.IsBackgroundTask
                ? BackgroundTransferCostPolicy.UnrestrictedOnly
                : BackgroundTransferCostPolicy.Always;
            uploader.Method = "PUT";
            var buffer = CryptographicBuffer.ConvertStringToBinary(_credential.UserName + ":" + _credential.Password, BinaryStringEncoding.Utf8);
            var token  = CryptographicBuffer.EncodeToBase64String(buffer);
            var value  = new HttpCredentialsHeaderValue("Basic", token);

            uploader.SetRequestHeader("Authorization", value.ToString());

            var upload = uploader.CreateUpload(url, file);
            Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(async operation => await OnUploadProgressChanged(operation));
            var task  = upload.StartAsync().AsTask(progressCallback);
            var task2 = await task.ContinueWith(OnUploadCompleted);

            return(await task2);
        }
        public static string AES_Encrypt(String plainText, String EncryptionKey)
        {
            string encrypted = "";
            SymmetricKeyAlgorithmProvider SAP      = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            HashAlgorithmProvider         HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash             Hash_AES = HAP.CreateHash();

            try
            {
                //byte[] KeyBytes = System.Text.Encoding.UTF8.GetBytes(password);
                byte[] KeyBytes16 = new byte[16];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(EncryptionKey)));
                byte[] KeyBytes;
                CryptographicBuffer.CopyToByteArray(Hash_AES.GetValueAndReset(), out KeyBytes);
                for (int i = 0; i < KeyBytes.Length; i++)
                {
                    KeyBytes16[i] = KeyBytes[i];
                }

                CryptographicKey key = SAP.CreateSymmetricKey(CryptographicBuffer.CreateFromByteArray(KeyBytes16));

                IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(plainText));
                encrypted = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(key, Buffer, null));

                return(encrypted);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                return("Error in Encryption:With Aes ");
            }
        }
 private static byte[] CalculateSha256(byte[] data)
 {
     return(Encoding.UTF8.GetBytes(
                CryptographicBuffer.EncodeToBase64String(
                    Sha256Provider.HashData(
                        CryptographicBuffer.CreateFromByteArray(data)))));
 }
Exemple #24
0
        //private String mDBPartition;

        public int dbDecrypt(String partition, int size, String data, out String decryptedData)
        {
            SymmetricKeyAlgorithmProvider SAP = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);
            CryptographicKey      AES;
            HashAlgorithmProvider HAP      = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            CryptographicHash     Hash_AES = HAP.CreateHash();

            try
            {
                byte[] hash = new byte[32];
                Hash_AES.Append(CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(data)));
                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));

                Windows.Storage.Streams.IBuffer Buffer = CryptographicBuffer.CreateFromByteArray(System.Text.Encoding.UTF8.GetBytes(partition));
                decryptedData = CryptographicBuffer.EncodeToBase64String(CryptographicEngine.Encrypt(AES, Buffer, null));
            }
            catch (Exception ex)
            {
                decryptedData = "";
                return(getErrorCode() == 0 ? 1 : 0);
            }
            return(getErrorCode() == 0 ? 1 : 0);
        }
Exemple #25
0
        /// <summary>
        /// Encrypts a string given a password, salt, and initialization vector, then returns result in base64 encoded string.
        ///
        /// To retrieve this data, you must decrypt with the same password, salt, IV, and cyphertext that was used during encryption
        /// </summary>
        /// <param name="password"></param>
        /// <param name="passwordSalt"></param>
        /// <param name="IV"></param>
        /// <param name="plaintext"></param>
        /// <returns></returns>
        public static string EncryptData(string password, string passwordSalt, string IV, string plaintext)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Password is empty");
            }
            if (string.IsNullOrEmpty(passwordSalt))
            {
                throw new ArgumentException("Salt is empty");
            }
            if (string.IsNullOrEmpty(IV))
            {
                throw new ArgumentException("Initialization Vector is empty");
            }
            if (string.IsNullOrEmpty(plaintext))
            {
                throw new ArgumentException("Plaintext data is empty");
            }
            IBuffer plainText = CryptographicBuffer.CreateFromByteArray(Encoding.UTF8.GetBytes(plaintext));
            IBuffer iv        = CryptographicBuffer.DecodeFromBase64String(IV);
            IBuffer key       = GetEncryptionKey(password, passwordSalt);

            SymmetricKeyAlgorithmProvider aes256 = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesCbcPkcs7);
            CryptographicKey k = aes256.CreateSymmetricKey(key);

            IBuffer encrypted = CryptographicEngine.Encrypt(k, plainText, iv);

            return(CryptographicBuffer.EncodeToBase64String(encrypted));
        }
Exemple #26
0
        /// <summary>
        /// Encypts a string using a key signed by a KeyCredential.
        /// </summary>
        /// <param name="strClearText">Text to encrypt.</param>
        /// <param name="rResult">KeyCredential object used to sign a key to encrypt the text.</param>
        /// <returns>Encrypted text.</returns>
        internal static async Task <string> Encrypt(ProtectedString ps, KeyCredentialRetrievalResult rResult)
        {
            Assembly assembly  = Assembly.GetExecutingAssembly();
            var      attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
            var      id        = attribute.Value;                                         // Any text can be used, it will be signed with the KeyCredential to encrypt the string
            IBuffer  buffMsg   = CryptographicBuffer.ConvertStringToBinary(id, encoding); // converted to an IBuffer

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

            IBuffer signedData = opResult.Result;

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

            // Encryption of the data using the key created (mKey)
            var     pb            = ps.ReadUtf8();
            IBuffer buffClear     = CryptographicBuffer.CreateFromByteArray(pb);
            IBuffer buffProtected = CryptographicEngine.Encrypt(myKey, buffClear, null);

            buffClear = null;
            MemUtil.ZeroByteArray(pb);
            return(CryptographicBuffer.EncodeToBase64String(buffProtected));
        }
Exemple #27
0
        /// <summary>
        /// Encrypt a string using dual encryption method. Returns an encrypted text.
        /// </summary>
        /// <param name="toEncrypt">String to be encrypted</param>
        /// <param name="key">Unique key for encryption/decryption</param>m>
        /// <returns>Returns encrypted string.</returns>
        public static string EncryptString(string toEncrypt, string key)
        {
            try
            {
                // Get the MD5 key hash (you can as well use the binary of the key string)
                var keyHash = GetMD5HashKey(key);

                // Create a buffer that contains the encoded message to be encrypted.
                var toDecryptBuffer = CryptographicBuffer.ConvertStringToBinary(toEncrypt, BinaryStringEncoding.Utf8);

                // Open a symmetric algorithm provider for the specified algorithm.
                var aes = SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithmNames.AesEcbPkcs7);

                // Create a symmetric key.
                var symetricKey = aes.CreateSymmetricKey(keyHash);

                // The input key must be securely shared between the sender of the cryptic message
                // and the recipient. The initialization vector must also be shared but does not
                // need to be shared in a secure manner. If the sender encodes a message string
                // to a buffer, the binary encoding method must also be shared with the recipient.
                var buffEncrypted = CryptographicEngine.Encrypt(symetricKey, toDecryptBuffer, null);

                // Convert the encrypted buffer to a string (for display).
                // We are using Base64 to convert bytes to string since you might get unmatched characters
                // in the encrypted buffer that we cannot convert to string with UTF8.
                var strEncrypted = CryptographicBuffer.EncodeToBase64String(buffEncrypted);

                return(strEncrypted);
            }
            catch (Exception ex)
            {
                // MetroEventSource.Log.Error(ex.Message);
                return("");
            }
        }
Exemple #28
0
        private async Task <HttpResponseMessage> ExecuteCommandUsingRESTApi(string ipAddress, string username, string password, string runCommand, bool isOutputRequired = true)
        {
            var client  = new HttpClient();
            var command = CryptographicBuffer.ConvertStringToBinary(runCommand, BinaryStringEncoding.Utf8);
            var runAsDefaultAccountFalse = CryptographicBuffer.ConvertStringToBinary("false", BinaryStringEncoding.Utf8);
            var timeout = CryptographicBuffer.ConvertStringToBinary(String.Format("{0}", TimeOutAfterNoOutput.TotalMilliseconds), BinaryStringEncoding.Utf8);

            var urlContent = new HttpFormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("command", CryptographicBuffer.EncodeToBase64String(command)),
                new KeyValuePair <string, string>("runasdefaultaccount", CryptographicBuffer.EncodeToBase64String(runAsDefaultAccountFalse)),
                new KeyValuePair <string, string>("timeout", CryptographicBuffer.EncodeToBase64String(timeout)),
            });

            var wdpCommand = isOutputRequired ? WdpRunCommandWithOutputApi : WdpRunCommandApi;
            var uriString  = String.Format("{0}://{1}:{2}{3}?{4}", DefaultProtocol, ipAddress, DefaultPort, wdpCommand, await urlContent.ReadAsStringAsync());
            var uri        = new Uri(uriString);

            var authBuffer = CryptographicBuffer.ConvertStringToBinary(String.Format("{0}:{1}", username, password), BinaryStringEncoding.Utf8);

            client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Basic", CryptographicBuffer.EncodeToBase64String(authBuffer));

            HttpResponseMessage response = await client.PostAsync(uri, null);

            return(response);
        }
Exemple #29
0
        /// <summary>
        /// Computes the hash value of the specified MemoryStream.
        /// </summary>
        /// <param name="memoryStream">The memory stream to calculate hash on. </param>
        /// <returns>The computed hash value string.</returns>
        internal string ComputeHash(MemoryStream memoryStream)
        {
#if RT
            this.hash.Append(memoryStream.GetWindowsRuntimeBuffer());
            IBuffer md5HashBuff = this.hash.GetValueAndReset();
            return(CryptographicBuffer.EncodeToBase64String(md5HashBuff));
#elif COMMON
            return(null);
#elif DNCP && !XAMIOS
            byte[] bytes;

            if (this.version1MD5)
            {
                bytes = this.hash.ComputeHash(memoryStream);
            }
            else
            {
                int length = (int)memoryStream.Length;
                this.nativeMD5Hash.TransformBlock(memoryStream.ToArray(), 0, length);
                bytes = this.nativeMD5Hash.TransformFinalBlock(new byte[0], 0, 0);
            }

            // Convert hash to string
            return(Convert.ToBase64String(bytes));
#elif XAMIOS
            byte[] bytes;
            int    length = (int)memoryStream.Length;
            bytes = this.hash.TransformFinalBlock(memoryStream.ToArray(), 0, 0);
            return(Convert.ToBase64String(bytes));
#endif
        }
        public string GenerateSha1Hash(string str)
        {
            var hashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
            var hash         = hashProvider.HashData(CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8));

            return(CryptographicBuffer.EncodeToBase64String(hash));
        }