private byte[] imm_computeAUTH(String user, String pass, String serial, long noune)
        {
            String ha1_str = user + ":" + serial + ":" + pass;

            //WSLOG(String.Format("AUTH: {0}:{1} serial={2} noune={3:X}", user, pass, serial, noune));

            byte[]  bytes_to_hash = YAPI.DefaultEncoding.GetBytes(ha1_str);
            IBuffer md5digest     = _md5Alg.HashData(bytes_to_hash.AsBuffer());

            byte[] digest   = md5digest.ToArray();
            String ha1      = YAPIContext.imm_bytesToHexStr(digest, 0, digest.Length).ToLower();
            String sha1_raw = ha1 + string.Format("{0:x2}{1:x2}{2:x2}{3:x2}", noune & 0xff, (noune >> 8) & 0xff, (noune >> 16) & 0xff, (noune >> 24) & 0xff);

            //WSLOG("raw:" + sha1_raw);
            byte[]  bytes_to_sha1 = YAPI.DefaultEncoding.GetBytes(sha1_raw);
            IBuffer sha1digest    = _sha1Alg.HashData(bytes_to_sha1.AsBuffer());

            return(sha1digest.ToArray());
        }
Beispiel #2
0
        private static IBuffer GetMD5Hash(string key)
        {
            // Convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(key, BinaryStringEncoding.Utf16BE);

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

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

            return(buffHash);
        }
Beispiel #3
0
        /// <summary>
        /// Hashes the given <paramref name="data"/> with the given <paramref name="algName"/> and returns it.
        /// <para/>
        /// Source: https://docs.microsoft.com/en-us/uwp/api/windows.security.cryptography.core.hashalgorithmprovider
        /// </summary>
        /// <param name="data">The data that should get hashed.</param>
        /// <param name="algName">The <see cref="HashAlgorithmNames"/> name that should get used for hashing.</param>
        /// <returns></returns>
        private static byte[] hash(byte[] data, string algName)
        {
            // Convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.CreateFromByteArray(data);

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

            // 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 InvalidOperationException("There was an error creating the hash");
            }

            // Return the encoded string
            return(buffHash.ToArray());
        }
Beispiel #4
0
        private void login_button_Click(object sender, RoutedEventArgs e)
        {
            //Todo
            if (!isEmailLegal(email_textbox.Text))
            {
                //   return;
            }
            if (!isPasswordLegal(password_textbox.Password))
            {
                //    return;
            }

            HashAlgorithmProvider hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);

            Windows.Storage.Streams.IBuffer hash_result = hash.HashData(CryptographicBuffer.ConvertStringToBinary(password_textbox.Password, BinaryStringEncoding.Utf8));
            string password_result = CryptographicBuffer.EncodeToHexString(hash_result);
            Frame  frame           = Window.Current.Content as Frame;

            frame.Navigate(typeof(GoodNightPage));
        }
Beispiel #5
0
        //public LoginVM()
        //{
        //    LoginCommand = new RelayCommand(IzvrsiLogin);

        //}


        protected string GenerateHashFromString(string strMsg)
        {
            string  strAlgName  = HashAlgorithmNames.Md5;
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8);

            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);

            strAlgName = objAlgProv.AlgorithmName;

            IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

            if (buffHash.Length != objAlgProv.HashLength)
            {
                throw new Exception("There was an error creating the hash");
            }

            string hex = CryptographicBuffer.EncodeToHexString(buffHash);

            return(hex);
        }
        /// <summary>
        /// Generates the SHA1 hash of the input byte array and encodes to base64 string.
        /// </summary>
        /// <param name="bytes">The input byte array.</param>
        /// <returns>Base64 string.</returns>
        public static string MakeSHA1HashBase64(byte[] bytes)
        {
            try
            {
                HashAlgorithmProvider provider = HashAlgorithmProvider.OpenAlgorithm(
                    HashAlgorithmNames.Sha1);

                IBuffer sha1HashBuffer = provider.HashData(bytes.AsBuffer());

                // http://stackoverflow.com/questions/26353710/how-to-achieve-base64-url-safe-encoding-in-c
                return(CryptographicBuffer
                       .EncodeToBase64String(sha1HashBuffer)
                       .TrimEnd(PADDING)
                       .Replace('+', '-')
                       .Replace('/', '_'));
            }
            catch (ArgumentNullException)
            {
                throw;
            }
        }
Beispiel #7
0
        public byte[] HashSHA1(string str)
        {
            // convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);

            // create a HashAlgorithmProvider object.
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);

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

            var sha1 = buffHash.ToArray();

            return(sha1);
        }
        public string EncodeToMd5(string pass)
        {
            string hash = null;

            if (pass != null)
            {
                string  algo        = HashAlgorithmNames.Md5;
                IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(pass, BinaryStringEncoding.Utf8);

                HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(algo);
                hash = objAlgProv.AlgorithmName;

                IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

                hash = CryptographicBuffer.EncodeToHexString(buffHash);
                hash = Convert.ToBase64String(Encoding.UTF8.GetBytes(hash));
            }


            return(hash);
        }
Beispiel #9
0
        public static string HashString(string str)
        //This class returns the SHA1 hash of a string
        {
            // Convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8);

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

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

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

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

            // Return the encoded string
            return(strHashBase64);
        }
Beispiel #10
0
        public static string Checksum(string text)
        {
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(text, BinaryStringEncoding.Utf8);
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
            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("Utils.fileChecksum: There was an error creating the hash");
            }

            string strHashBase64 = CryptographicBuffer.EncodeToHexString(buffHash);

            // pad with zeros to length of 40 - SHA1 is 160bit long
            if (strHashBase64.Length < 40)
            {
                string padString = new string('0', 40);
                strHashBase64 = padString.Substring(0, 40 - strHashBase64.Length) + strHashBase64;
            }
            return(strHashBase64);
        }
        public String SampleHashMsg(String strAlgName, String strMsg)

        {
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(strMsg, BinaryStringEncoding.Utf8);

            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(strAlgName);



            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.EncodeToHexString(buffHash);



            // Return the encoded string

            return(strHashBase64);
        }
Beispiel #12
0
        /**
         * Genera el hashe MD5 de la contraseña.
         *
         * @param password
         * @param key
         * @return string plano con hash */
        private static string Hash(string password, string key)
        {
            if (password == null || password.Length == 0)
            {
                throw new Exception("Empty passwords are not supported.");
            }

            string  AlgName     = HashAlgorithmNames.Sha512;
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(password + key, BinaryStringEncoding.Utf8);
            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(AlgName);
            IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

            if (buffHash.Length != objAlgProv.HashLength)
            {
                throw new Exception("There was an error creating the hash");
            }

            string strHash = CryptographicBuffer.EncodeToHexString(buffHash);

            // Return the encoded string
            return(strHash);
        }
Beispiel #13
0
        /// <summary>
        /// Hashes the client WebSocket key for the server
        /// </summary>
        /// <param name="webSocketKey"></param>
        /// <returns></returns>
        public static string HashWebSocketKey(string webSocketKey)
        {
            if (webSocketKey == null)
            {
                throw new ArgumentNullException("webSocketKey");
            }

            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(webSocketKey + _guid, BinaryStringEncoding.Utf8);

            HashAlgorithmProvider objAlgProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);

            IBuffer buffHash = objAlgProv.HashData(buffUtf8Msg);

            if (buffHash.Length != objAlgProv.HashLength)
            {
                throw new Exception("There was an error creating the hash");
            }

            String strHashBase64 = CryptographicBuffer.EncodeToBase64String(buffHash);

            return(strHashBase64);
        }
Beispiel #14
0
        private string create_hash(string msg)
        {
            // Convert the message string to binary data.
            IBuffer buffMsg = CryptographicBuffer.ConvertStringToBinary(msg, BinaryStringEncoding.Utf8);

            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider algProv = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha256);

            // Hash the message.
            IBuffer buffHash = algProv.HashData(buffMsg);

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

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

            // Return the encoded string
            return(strHashBase64);
        }
Beispiel #15
0
        /// <summary>
        /// Creates an RSA PKCS#1 v1.5 signature of a SHA1 for the stream.
        /// </summary>
        private static byte[] RsaPkcs15Sha1_Sign(
            ArraySegment <byte> dataToSign,
            X509Certificate2 signingCertificate)
        {
            // extract the private key.
            RSA rsa = null;

            try
            {
                rsa = signingCertificate.GetRSAPrivateKey();
            }
            catch (Exception ex)
            {
                throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No private key for certificate: " + ex.Message);
            }

            if (rsa == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "No private key for certificate.");
            }

            // compute the hash of message.
            MemoryStream istrm = new MemoryStream(dataToSign.Array, dataToSign.Offset, dataToSign.Count, false);

            HashAlgorithmProvider sha1Provider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
            IBuffer buffer = CryptographicBuffer.CreateFromByteArray(istrm.ToArray());

            buffer = sha1Provider.HashData(buffer);
            byte[] digest = new byte[buffer.Length];
            CryptographicBuffer.CopyToByteArray(buffer, out digest);

            istrm.Dispose();

            // create the signature.
            return(rsa.SignHash(digest, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1));
        }
        protected override DeviceId ComputeDeviceID()
        {
            DeviceId dId;

            if (preferredIdMethod == DeviceIdMethodInternal.winHardwareToken)
            {
                HardwareToken token      = HardwareIdentification.GetPackageSpecificToken(null);
                IBuffer       hardwareId = token.Id;

                HashAlgorithmProvider hasher = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
                IBuffer hashed = hasher.HashData(hardwareId);

                string newId = CryptographicBuffer.EncodeToHexString(hashed);

                dId = new DeviceId(newId, DeviceIdMethodInternal.winHardwareToken);
            }
            else
            {
                //The other remaining option is either Guid or 'developer supplied'
                dId = CreateGUIDDeviceId();
            }

            return(dId);
        }
Beispiel #17
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());
        }
Beispiel #18
0
        private string HashString(string algorithmName, string stringValue)
        {
            // Convert the message string to binary data.
            IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(stringValue, BinaryStringEncoding.Utf8);

            // Create a HashAlgorithmProvider object.
            HashAlgorithmProvider hashAlgorithmProvider = HashAlgorithmProvider.OpenAlgorithm(algorithmName);

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

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

            // Convert to Hex
            var hashedStringHexValue = BitConverter.ToString(buffHash.ToArray());

            // Get rid of the dashes
            return(hashedStringHexValue.Replace("-", ""));
        }
Beispiel #19
0
        private static Uri CreateGravatarUri(string email, int width)
        {
            if (string.IsNullOrEmpty(email))
            {
                return(null);
            }

            // Reference: http://en.gravatar.com/site/implement/url
            var sb = new StringBuilder();

            sb.Append("http://www.gravatar.com/avatar/");

            IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(email, BinaryStringEncoding.Utf8);
            HashAlgorithmProvider algorithmProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
            IBuffer hashedBuffer = algorithmProvider.HashData(buffer);

            sb.Append(CryptographicBuffer.EncodeToHexString(hashedBuffer));
            sb.Append(".jpg");

            sb.Append("?s=");
            sb.Append(width);

            return(new Uri(sb.ToString()));
        }
Beispiel #20
0
 private static IBuffer ComputeHash(this HashAlgorithmProvider algorithm, byte[] buffer)
 {
     return(algorithm.HashData(buffer.ToIBuffer()));
 }
Beispiel #21
0
        public static async Task <IBuffer> GetBufferFromUrlAsync([NotNull] String url, CancellationToken token)
        {
            // URL check
            if (String.IsNullOrEmpty(url))
            {
                return(null);
            }

            // Loop to make sure to retry once if the existing cached file is invalid
            while (true)
            {
                // Input check
                if (token.IsCancellationRequested)
                {
                    return(null);
                }

                // Get the filename for the cache storage
                byte[]      bytes = Encoding.Unicode.GetBytes(url);
                IBuffer     hash = HashProvider.HashData(bytes.AsBuffer());
                String      hex = CryptographicBuffer.EncodeToHexString(hash), cacheFilename = $"{hex}{CacheExtension}";
                StorageFile file = await ApplicationData.Current.LocalCacheFolder.TryGetItemAsync(cacheFilename) as StorageFile;

                // Check the cache result
                if (file == null)
                {
                    // Try to get the remote buffer
                    IBuffer buffer = await DownloadDataAsync(url, token);

                    if (buffer == null)
                    {
                        return(null);
                    }

                    // Save the buffer if possible
                    StorageFile cacheFile = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(cacheFilename, CreationCollisionOption.OpenIfExists);

                    using (IRandomAccessStream outputStream = await cacheFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        await outputStream.WriteAsync(buffer);

                        return(buffer);
                    }
                }

                // Load the buffer from the cached file
                if (token.IsCancellationRequested)
                {
                    return(null);
                }
                using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read))
                {
                    try
                    {
                        byte[] data = new byte[stream.Size];
                        return(await stream.ReadAsync(data.AsBuffer(), (uint)data.Length, InputStreamOptions.None));
                    }
                    catch
                    {
                        // Invalid file
                    }
                }

                // Delete the cached file
                try
                {
                    await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
                }
                catch
                {
                    return(null);
                }
            }
        }
Beispiel #22
0
 private static IBuffer ComputeHash(this HashAlgorithmProvider algorithm, Stream inputStream)
 {
     return(algorithm.HashData(inputStream.ToIBuffer()));
 }
Beispiel #23
0
 public static SHA1Value Compute(byte[] data)
 {
     return(new SHA1Value(sha1compute.HashData(data.AsBuffer())));
 }
Beispiel #24
0
        private async Task <bool> DeployMFUpdateAsync(StorageFile zipFile, CancellationToken cancellationToken, IProgress <ProgressReport> progress = null)
        {
            if (zipFile.IsAvailable)
            {
                byte[] packet = new byte[DebugEngine.WireProtocolPacketSize];
                try
                {
                    int handle = -1;
                    int idx    = 0;

                    var fileInfo = await zipFile.GetBasicPropertiesAsync();

                    uint numPkts = (uint)(fileInfo.Size + DebugEngine.WireProtocolPacketSize - 1) / DebugEngine.WireProtocolPacketSize;

                    byte[] hashData = UTF8Encoding.UTF8.GetBytes(zipFile.Name + fileInfo.DateModified.ToString());

                    uint updateId = CRC.ComputeCRC(hashData, 0, hashData.Length, 0);
                    uint imageCRC = 0;

                    byte[] sig = null;

                    //Debug.WriteLine(updateId);

                    handle = DebugEngine.StartUpdate("NetMF", 4, 4, updateId, 0, 0, (uint)fileInfo.Size, (uint)DebugEngine.WireProtocolPacketSize, 0);
                    if (handle > -1)
                    {
                        uint         authType;
                        IAsyncResult iar = null;

                        // perform request
                        var resp = DebugEngine.UpdateAuthCommand(handle, 1, null);

                        // check result
                        if (!resp.Success || resp.Response.Length < 4)
                        {
                            return(false);
                        }


                        using (MemoryStream ms = new MemoryStream(resp.Item1))
                            using (BinaryReader br = new BinaryReader(ms))
                            {
                                authType = br.ReadUInt32();
                            }


                        byte[] pubKey = null;

                        // FIXME
                        //if (m_serverCert != null)
                        //{

                        //    RSACryptoServiceProvider rsa = m_serverCert.PrivateKey as RSACryptoServiceProvider;

                        //    if (rsa != null)
                        //    {
                        //        pubKey = rsa.ExportCspBlob(false);
                        //    }
                        //}

                        if (!DebugEngine.UpdateAuthenticate(handle, pubKey))
                        {
                            return(false);
                        }

                        // FIXME
                        //if (authType == 1 && m_serverCert != null)
                        //{
                        //    iar = await DebugEngine.UpgradeConnectionToSsl_Begin(m_serverCert, m_requireClientCert);

                        //    if (0 == WaitHandle.WaitAny(new WaitHandle[] { iar.AsyncWaitHandle, EventCancel }, 10000))
                        //    {
                        //        try
                        //        {
                        //            if (!m_eng.UpgradeConnectionToSSL_End(iar))
                        //            {
                        //                m_eng.Dispose();
                        //                m_eng = null;
                        //                return false;
                        //            }
                        //        }
                        //        catch
                        //        {
                        //            m_eng.Dispose();
                        //            m_eng = null;
                        //            return false;
                        //        }
                        //    }
                        //    else
                        //    {
                        //        return false;
                        //    }
                        //}

                        // FIXME
                        //RSAPKCS1SignatureFormatter alg = null;
                        object alg = null;
                        HashAlgorithmProvider hash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
                        byte[] hashValue           = null;

                        try
                        {
                            if (m_serverCert != null)
                            {
                                //alg = new RSAPKCS1SignatureFormatter(m_serverCert.PrivateKey);
                                //alg.SetHashAlgorithm("SHA1");
                                hash      = HashAlgorithmProvider.OpenAlgorithm("SHA1");
                                hashValue = new byte[hash.HashLength / 8];
                            }
                        }
                        catch
                        {
                        }

                        IBuffer buffer = await FileIO.ReadBufferAsync(zipFile);

                        using (DataReader dataReader = DataReader.FromBuffer(buffer))
                        {
                            dataReader.ReadBytes(packet);

                            uint crc = CRC.ComputeCRC(packet, 0, packet.Length, 0);

                            if (!DebugEngine.AddPacket(handle, (uint)idx++, packet, CRC.ComputeCRC(packet, 0, packet.Length, 0)))
                            {
                                return(false);
                            }

                            imageCRC = CRC.ComputeCRC(packet, 0, packet.Length, imageCRC);

                            progress?.Report(new ProgressReport(idx, numPkts, string.Format("Deploying {0}...", idx)));
                        }

                        if (hash != null)
                        {
                            buffer = await FileIO.ReadBufferAsync(zipFile);

                            // hash it
                            IBuffer hashed = hash.HashData(buffer);
                            CryptographicBuffer.CopyToByteArray(hashed, out sig);
                        }

                        if (alg != null)
                        {
                            //sig = alg.CreateSignature(hash);
                            //CryptographicBuffer.CopyToByteArray(sig)
                        }
                        else
                        {
                            sig = new byte[4];
                            using (MemoryStream ms = new MemoryStream(sig))
                                using (BinaryWriter br = new BinaryWriter(ms))
                                {
                                    br.Write(imageCRC);
                                }
                        }

                        if (DebugEngine.InstallUpdate(handle, sig))
                        {
                            return(true);
                        }
                    }
                }
                catch
                {
                }
            }

            return(false);
        }
 public static string Md5Encrypt(IBuffer data)
 {
     HashAlgorithmProvider md5 = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
     IBuffer hashedData = md5.HashData(data);
     return CryptographicBuffer.EncodeToHexString(hashedData);
 }
Beispiel #26
0
 private static IBuffer ComputeHash(this HashAlgorithmProvider algorithm, byte[] buffer, int offset, int count)
 {
     return(algorithm.HashData(buffer.ToIBuffer(offset, count)));
 }
Beispiel #27
0
        public byte[] ComputeHash(byte[] input)
        {
            var hashed = hashProvider.HashData(CryptographicBuffer.CreateFromByteArray(input));

            return(hashed.ToArray());
        }
Beispiel #28
0
        private void GenerateResponseHash()
        {
            var ae = new UTF8Encoding();

            long v = NextInt64();

            // Create cnonce value using a random number, username and password
            var sb = new StringBuilder();

            sb.Append(v.ToString());
            sb.Append(":");
            sb.Append(Id.User);
            sb.Append(":");
            sb.Append(Password);

            _cnonce = HexString(ae.GetBytes(sb.ToString())).ToLower();

            // Create the nonce count which states how many times we have sent this packet.
            _nc++;
            _ncString = _nc.ToString().PadLeft(8, '0');

            // Create H1.  This value is the username/password portion of A1 according to the SASL DIGEST-MD5 RFC.
            sb.Remove(0, sb.Length);
            sb.Append(Id.User);
            sb.Append(":");
            sb.Append(this["realm"]);
            sb.Append(":");
            sb.Append(Password);
            byte[] h1 = _md5.HashData(ae.GetBytes(sb.ToString()).AsBuffer()).ToArray();

            // Create the rest of A1 as stated in the RFC.
            sb.Remove(0, sb.Length);
            sb.Append(":");
            sb.Append(this["nonce"]);
            sb.Append(":");
            sb.Append(_cnonce);

            if (this["authzid"] != null)
            {
                sb.Append(":");
                sb.Append(this["authzid"]);
            }

            string a1 = sb.ToString();

            // Combine H1 and A1 into final A1
            var ms = new MemoryStream();

            ms.Write(h1, 0, 16);
            byte[] temp = ae.GetBytes(a1);
            ms.Write(temp, 0, temp.Length);
            ms.Seek(0, SeekOrigin.Begin);
            h1 = _md5.HashData(ms.GetWindowsRuntimeBuffer()).ToArray();

            // Create A2
            sb.Remove(0, sb.Length);
            sb.Append("AUTHENTICATE:");
            sb.Append(_digestUri);
            if (this["qop"].CompareTo("auth") != 0)
            {
                sb.Append(":00000000000000000000000000000000");
            }

            string a2 = sb.ToString();

            byte[] h2 = _md5.HashData(ae.GetBytes(a2).AsBuffer()).ToArray();

            // Make A1 and A2 hex strings
            string p1 = HexString(h1).ToLower();
            string p2 = HexString(h2).ToLower();

            // Combine all portions into the final response hex string
            sb.Remove(0, sb.Length);
            sb.Append(p1);
            sb.Append(":");
            sb.Append(this["nonce"]);
            sb.Append(":");
            sb.Append(_ncString);
            sb.Append(":");
            sb.Append(_cnonce);
            sb.Append(":");
            sb.Append(this["qop"]);
            sb.Append(":");
            sb.Append(p2);

            string a3 = sb.ToString();

            byte[] h3 = _md5.HashData(ae.GetBytes(a3).AsBuffer()).ToArray();
            _responseHash = HexString(h3).ToLower();
        }
Beispiel #29
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);
        }
Beispiel #30
0
 public static string GetMd5Hash(string input)
 {
     return(EncodeToHexString(md5.HashData(ConvertStringToBinary(input, BinaryStringEncoding.Utf8))));
 }