Exemplo n.º 1
0
        /// <summary>
        /// Uploads the local configuration file as plugin
        /// </summary>
        private static Plugin UploadConfigurationFile(IHiveService service, List <Plugin> onlinePlugins)
        {
            string exeFilePath    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Settings.Default.HLBinaryName);
            string configFileName = Path.GetFileName(ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath);
            string configFilePath = ConfigurationManager.OpenExeConfiguration(exeFilePath).FilePath;

            byte[] hash;

            byte[] data = File.ReadAllBytes(configFilePath);
            using (SHA1 sha1 = SHA1.Create()) {
                hash = sha1.ComputeHash(data);
            }

            Plugin configPlugin = new Plugin()
            {
                Name = "Configuration", Version = new Version(), Hash = hash
            };
            PluginData configFile = new PluginData()
            {
                FileName = configFileName, Data = data
            };

            IEnumerable <Plugin> onlineConfig = onlinePlugins.Where(p => p.Hash.SequenceEqual(hash));

            if (onlineConfig.Count() > 0)
            {
                return(onlineConfig.First());
            }
            else
            {
                configPlugin.Id = service.AddPlugin(configPlugin, new List <PluginData> {
                    configFile
                });
                return(configPlugin);
            }
        }
Exemplo n.º 2
0
 public static string CalculateHashOfFile(string filePath)
 {
     try
     {
         byte[]        byteResult;
         StringBuilder result = new StringBuilder();
         int           i;
         using (FileStream stream = File.OpenRead(filePath))
         {
             stream.Position = 0;
             byteResult      = sha1.ComputeHash(stream);
             for (i = 0; i < byteResult.Length; i++)
             {
                 result.AppendFormat("{0:x2}", byteResult[i]);
             }
             return(result.ToString());
         }
     }
     catch (Exception ex)
     {
         Logger.Error(ex.ToString());
         return(null);
     }
 }
Exemplo n.º 3
0
        public async Task <IHttpActionResult> PostUser(User user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }


            SHA1 sha = SHA1.Create();

            byte[] buffer            = Encoding.ASCII.GetBytes(user.Password);
            byte[] hash              = sha.ComputeHash(buffer);
            string encryptedPassword = Convert.ToBase64String(hash);

            user.Password = encryptedPassword;

            db.Users.Add(user);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (UserExists(user.Name))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtRoute("DefaultApi", new { id = user.Name }, user));
        }
Exemplo n.º 4
0
        public async Task <IHttpActionResult> GetUser(string userName, string password)
        {
            SHA1 sha = SHA1.Create();

            byte[] buffer            = Encoding.ASCII.GetBytes(password);
            byte[] hash              = sha.ComputeHash(buffer);
            string encryptedPassword = Convert.ToBase64String(hash);

            User user = await db.Users.FindAsync(userName);

            if (user == null)
            {
                return(Ok("user wasn't in db"));
            }

            if (user.Password != encryptedPassword)
            {
                return(Ok("incorrect password"));
            }
            else
            {
                return(Ok(user));
            }
        }
        public void TryDoFinal()
        {
            using SHA1 sha1 = SHA1.Create();

            byte[] data3 = new byte[147];

            Random r = new Random(42);

            r.NextBytes(data3);

            using SHA1 alternative = SHA1.Create();

            byte[] exceptedHash = alternative.ComputeHash(data3);

            sha1.Update(data3);

            byte[] hash = new byte[80];
            Assert.IsFalse(sha1.TryDoFinal(new Span <byte>(hash, 0, 5), out _));
            Assert.IsTrue(sha1.TryDoFinal(new Span <byte>(hash, 0, 78), out int witeBytes));

            byte[] subArray = hash.Take(witeBytes).ToArray();
            CollectionAssert.AreEquivalent(exceptedHash, subArray, "Error in cputed hash.");
            Assert.AreEqual(20, witeBytes);
        }
        public async Task UpdateWithStream()
        {
            using SHA1 sha1 = SHA1.Create();

            byte[] data1 = new byte[2];
            byte[] data2 = new byte[20];
            byte[] data3 = new byte[147];

            Random r = new Random(42);

            r.NextBytes(data1);
            r.NextBytes(data2);
            r.NextBytes(data3);

            using MemoryStream ms = new MemoryStream();
            ms.Write(data1);
            ms.Write(data2);
            ms.Write(data3);
            ms.Position = 0L;

            using MemoryStream hms = new MemoryStream();
            hms.Write(data2);
            hms.Write(data3);
            hms.Position = 0L;

            using SHA1 alternative = SHA1.Create();

            byte[] exceptedHash = alternative.ComputeHash(ms);

            sha1.Update(data1);
            await sha1.Update(hms);

            byte[] hash = sha1.DoFinal();

            CollectionAssert.AreEquivalent(exceptedHash, hash, "Error in cputed hash.");
        }
Exemplo n.º 7
0
        public DataTable valiLoginPwd(string LoginName, string LoginPwd)
        {
            DataSet ds   = null;
            SHA1    sha1 = SHA1.Create();

            byte[]         bytePassword = sha1.ComputeHash(Encoding.Unicode.GetBytes(LoginPwd));
            SqlParameter[] parameters   =
            {
                new SqlParameter("@LoginName",   SqlDbType.Char,      16),
                new SqlParameter("@PayPassword", SqlDbType.VarBinary, 50),
                new SqlParameter("@flag",        SqlDbType.VarChar,   50),
            };

            parameters[0].Value = LoginName;
            parameters[1].Value = bytePassword;
            parameters[2].Value = "valiloginpwd";
            try
            {
                ds = DbHelperSQL.RunProcedure("PayPwd", parameters, "ds");
            }
            catch
            { }
            return(ds.Tables[0]);
        }
Exemplo n.º 8
0
        private string getSignature(string ticket, string noncestr, string url, long stamp)
        {
            //   highlevel.redis.GetDatabase();

            SHA1 sha = SHA1.Create();

            //将mystr转换成byte[]

            ASCIIEncoding enc = new ASCIIEncoding();

            var str = string.Format("jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}", ticket, noncestr, stamp, url);

            byte[] dataToHash = enc.GetBytes(str);

            //Hash运算

            byte[] dataHashed = sha.ComputeHash(dataToHash);

            //将运算结果转换成string

            string hash = BitConverter.ToString(dataHashed).Replace("-", "");

            return(hash);
        }
Exemplo n.º 9
0
        /// <summary>
        /// From https://stackoverflow.com/a/41622689/1454643
        /// Generates Guid based on String. Key assumption for this algorithm is that name is unique (across where it it's being used)
        /// and if name byte length is less than 16 - it will be fetched directly into guid, if over 16 bytes - then we compute sha-1
        /// hash from string and then pass it to guid.
        /// </summary>
        /// <param name="name">Unique name which is unique across where this guid will be used.</param>
        /// <returns>For example "706C7567-696E-7300-0000-000000000000" for "plugins"</returns>
        public static string GenerateGuid(string name)
        {
            byte[] buf  = Encoding.UTF8.GetBytes(name);
            byte[] guid = new byte[16];
            if (buf.Length < 16)
            {
                Array.Copy(buf, guid, buf.Length);
            }
            else
            {
                using (SHA1 sha1 = SHA1.Create())
                {
                    byte[] hash = sha1.ComputeHash(buf);

                    // Hash is 20 bytes, but we need 16. We loose some of "uniqueness", but I doubt it will be fatal
                    Array.Copy(hash, guid, 16);
                }
            }

            // Don't use Guid constructor, it tends to swap bytes. We want to preserve original string as hex dump.
            string guidS = $"{guid[0]:X2}{guid[1]:X2}{guid[2]:X2}{guid[3]:X2}-{guid[4]:X2}{guid[5]:X2}-{guid[6]:X2}{guid[7]:X2}-{guid[8]:X2}{guid[9]:X2}-{guid[10]:X2}{guid[11]:X2}{guid[12]:X2}{guid[13]:X2}{guid[14]:X2}{guid[15]:X2}";

            return(guidS);
        }
Exemplo n.º 10
0
        public static void VerifyKnownSignature()
        {
            using (DSA dsa = DSAFactory.Create())
            {
                byte[]        data;
                byte[]        signature;
                DSAParameters dsaParameters;
                DSATestData.GetDSA1024_186_2(out dsaParameters, out signature, out data);

                byte[] hash;
                using (SHA1 alg = SHA1.Create())
                {
                    hash = alg.ComputeHash(data);
                }

                dsa.ImportParameters(dsaParameters);
                var deformatter = new DSASignatureDeformatter(dsa);
                deformatter.VerifySignature(hash, signature);

                // Negative case
                signature[signature.Length - 1] ^= 0xff;
                Assert.False(deformatter.VerifySignature(hash, signature));
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Computes the ETag for a Graph
        /// </summary>
        /// <param name="g">Graph</param>
        /// <returns></returns>
        public static String GetETag(this IGraph g)
        {
            List <Triple> ts = g.Triples.ToList();

            ts.Sort();

            StringBuilder hash = new StringBuilder();

            foreach (Triple t in ts)
            {
                hash.AppendLine(t.GetHashCode().ToString());
            }
            String h = hash.ToString().GetHashCode().ToString();

            SHA1 sha1 = SHA1.Create();

            byte[] hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(h));
            hash = new StringBuilder();
            foreach (byte b in hashBytes)
            {
                hash.Append(b.ToString("x2"));
            }
            return(hash.ToString());
        }
Exemplo n.º 12
0
        public static string HashSha1(this string source)
        {
            // create a byte array
            byte[] data;

            // create a .NET Hash provider object
            using (SHA1 sha1hash = SHA1.Create())
            {
                // hash the input
                data = sha1hash.ComputeHash(Encoding.UTF8.GetBytes(source));
            }

            // create an output stringBuilder
            var s = new StringBuilder();

            // loop through the hash creating letters for the stringBuilder
            for (int i = 0; i < data.Length; i++)
            {
                s.Append(data[i].ToString("x2"));
            }

            // return the hexadecimal string representation of the hash
            return(s.ToString());
        }
Exemplo n.º 13
0
        // Hash an input string and return the hash as
        // a 32 character hexadecimal string.
        public string getSha1Hash(string input)
        {
            // Create a new instance of the MD5CryptoServiceProvider object.
            SHA1 sha1Hasher = SHA1.Create();

            // Convert the input string to a byte array and compute the hash.
            //byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            byte[] data = sha1Hasher.ComputeHash(Encoding.Default.GetBytes(input));


            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return(sBuilder.ToString());
        }
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {//save button
            //save file
            var code = codeEdit.Text;

            byte[] bs      = System.Text.Encoding.UTF8.GetBytes(code);
            SHA1   sha1    = SHA1.Create();
            var    hash    = sha1.ComputeHash(bs);
            var    hashstr = ThinNeo.Helper.Bytes2HexString(hash);
            var    path    = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "temp");

            if (System.IO.Directory.Exists(path) == false)
            {
                System.IO.Directory.CreateDirectory(path);
            }

            var filename = System.IO.Path.Combine(path, hashstr + ".cs");

            System.IO.File.WriteAllBytes(filename, bs);


            //call api upload file
            var apitext = textAPI.Text;
            var url     = apitext + "parse?language=csharp";

            string strback = null;

            try
            {
                byte[] retvar = wc.UploadFile(url, filename);
                strback = System.Text.Encoding.UTF8.GetString(retvar);
            }
            catch (Exception err)
            {
                return;
            }
            ClearLog();
            this.textHash.Text      = "";
            this.textHexScript.Text = "";
            var compilereuslt = MyJson.Parse(strback).AsDict();

            if (compilereuslt.ContainsKey("tag"))
            {
                var tag = compilereuslt["tag"].AsInt();
                if (tag == 0)
                {
                    this.Log("build ok.");
                    var rhash = compilereuslt["hash"].AsString();
                    var rhex  = compilereuslt["hex"].AsString();
                    var rabi  = Uri.UnescapeDataString(compilereuslt["funcsigns"].AsString());
                    this.textHash.Text      = rhash;
                    this.textHexScript.Text = rhex;
                    updateASM(rhex);
                }
                else
                {
                    this.Log("build error:" + tag);
                    try
                    {
                        var msg = compilereuslt["msg"].AsString();
                        this.Log(msg);
                    }
                    catch
                    {
                    }
                    try
                    {
                        var error = compilereuslt["errors"].AsList();
                        foreach (MyJson.JsonNode_Object ee in error)
                        {
                            var    _tag  = ee.ContainsKey("tag") ? ee["tag"].AsString() : "";
                            var    _id   = ee.ContainsKey("id") ? ee["id"].AsString() : "";
                            var    _msg  = ee.ContainsKey("msg") ? ee["msg"].AsString() : "";
                            var    _line = ee.ContainsKey("line") ? ee["line"].AsInt() : -1;
                            var    _col  = ee.ContainsKey("col") ? ee["col"].AsInt() : -1;
                            string line  = _id + ":" + _tag + " " + _msg + "(" + _line + "," + _col + ")";
                            Log(line);
                        }
                    }
                    catch
                    {
                    }
                }
            }
        }
Exemplo n.º 15
0
        public static byte[] ToSha1Hash(this byte[] input)
        {
            SHA1 sha1 = SHA1.Create();

            return(sha1.ComputeHash(input));
        }
Exemplo n.º 16
0
        protected override void HandleLtMetadataMessage(PeerId id, LTMetadata message)
        {
            base.HandleLtMetadataMessage(id, message);

            switch (message.MetadataMessageType)
            {
            case LTMetadata.eMessageType.Data:
                if (stream == null)
                {
                    throw new Exception("Need extention handshake before ut_metadata message.");
                }

                stream.Seek(message.Piece * LTMetadata.BlockSize, SeekOrigin.Begin);
                stream.Write(message.MetadataPiece, 0, message.MetadataPiece.Length);
                bitField[message.Piece] = true;
                if (bitField.AllTrue)
                {
                    byte[] hash;
                    stream.Position = 0;
                    using (SHA1 hasher = HashAlgoFactory.Create <SHA1>())
                        hash = hasher.ComputeHash(stream);

                    if (!Manager.InfoHash.Equals(hash))
                    {
                        bitField.SetAll(false);
                    }
                    else
                    {
                        Torrent t;
                        stream.Position = 0;
                        BEncodedDictionary dict = new BEncodedDictionary();
                        dict.Add("info", BEncodedValue.Decode(stream));
                        // FIXME: Add the trackers too
                        if (Torrent.TryLoad(dict.Encode(), out t))
                        {
                            try
                            {
                                if (Directory.Exists(savePath))
                                {
                                    savePath = Path.Combine(savePath, Manager.InfoHash.ToHex() + ".torrent");
                                }
                                File.Delete(savePath);
                                File.WriteAllBytes(savePath, dict.Encode());
                            }
                            catch (Exception ex)
                            {
                                Logger.Log(null, "*METADATA EXCEPTION* - Can not write in {0} : {1}", savePath, ex);
                                Manager.Error = new Error(Reason.WriteFailure, ex);
                                Manager.Mode  = new ErrorMode(Manager);
                                return;
                            }
                            t.TorrentPath   = savePath;
                            Manager.Torrent = t;
                            SwitchToRegular();
                        }
                        else
                        {
                            bitField.SetAll(false);
                        }
                    }
                }
                //Double test because we can change the bitfield in the other block
                if (!bitField.AllTrue)
                {
                    RequestNextNeededPiece(id);
                }
                break;

            case LTMetadata.eMessageType.Reject:
                //TODO
                //Think to what we do in this situation
                //for moment nothing ;)
                //reject or flood?
                break;

            case LTMetadata.eMessageType.Request:    //ever done in base class but needed to avoid default
                break;

            default:
                throw new MessageException(string.Format("Invalid messagetype in LTMetadata: {0}", message.MetadataMessageType));
            }
        }
Exemplo n.º 17
0
 public byte[] Digest()
 {
     stream.Seek(0, SeekOrigin.Begin);
     return(md.ComputeHash(stream));
 }
Exemplo n.º 18
0
        public static string SHA1(this string str)
        {
            var data = _sha1.ComputeHash(Encoding.UTF8.GetBytes(str));

            return(data.ToHexString());
        }
Exemplo n.º 19
0
        public override decimal GetLucky(string server, string client, int nonce)
        {
            SHA1   betgenerator = SHA1.Create();
            string Seed         = server + "-" + client + "-" + nonce;

            byte[] serverb = new byte[Seed.Length];

            for (int i = 0; i < Seed.Length; i++)
            {
                serverb[i] = Convert.ToByte(Seed[i]);
            }
            decimal Lucky = 0;

            do
            {
                serverb = betgenerator.ComputeHash(serverb.ToArray());
                StringBuilder hex = new StringBuilder(serverb.Length * 2);
                foreach (byte b in serverb)
                {
                    hex.AppendFormat("{0:x2}", b);
                }

                string s = hex.ToString().Substring(0, 8);
                Lucky = long.Parse(s, System.Globalization.NumberStyles.HexNumber);
            } while (Lucky > 4294960000);
            Lucky = (Lucky % 10000.0m) / 100.0m;
            if (Lucky < 0)
            {
                return(-Lucky);
            }
            return(Lucky);

            /*
             * int charstouse = 5;
             * List<byte> serverb = new List<byte>();
             *
             * for (int i = 0; i < server.Length; i++)
             * {
             *  serverb.Add(Convert.ToByte(server[i]));
             * }
             *
             * betgenerator.Key = serverb.ToArray();
             *
             * List<byte> buffer = new List<byte>();
             * string msg = /*nonce.ToString() + ":" + client + ":" + nonce.ToString();
             * foreach (char c in msg)
             * {
             *  buffer.Add(Convert.ToByte(c));
             * }
             *
             * byte[] hash = betgenerator.ComputeHash(buffer.ToArray());
             *
             * StringBuilder hex = new StringBuilder(hash.Length * 2);
             * foreach (byte b in hash)
             *  hex.AppendFormat("{0:x2}", b);
             *
             *
             * for (int i = 0; i < hex.Length; i += charstouse)
             * {
             *
             *  string s = hex.ToString().Substring(i, charstouse);
             *
             *  decimal lucky = int.Parse(s, System.Globalization.NumberStyles.HexNumber);
             *  if (lucky < 1000000)
             *      return lucky / 10000;
             * }*/
            return(0);
        }
Exemplo n.º 20
0
        byte[] CreateHash(byte[] keyBuffer)
        {
            Log.Verbose($"Handshake Hashing {Encoding.ASCII.GetString(keyBuffer, 0, MergedKeyLength)}");

            return(sha1.ComputeHash(keyBuffer, 0, MergedKeyLength));
        }
Exemplo n.º 21
0
        /// <summary>
        /// </summary>
        /// <param name="pass"> </param>
        /// <returns> </returns>
        public static byte[] Sha1HashBytes(string pass)
        {
            SHA1 sha = SHA1.Create();

            return(sha.ComputeHash(Encoding.UTF8.GetBytes(pass)));
        }
        public static SongInfo DeserializeSongInfo(Byte[] data)
        {
            SongInfo songInfo = new SongInfo();

            string hash = BitConverter.ToString(data, 40, 20).Replace("-", String.Empty);

            hash = hash.ToUpper();
            Logger.log?.Warn(hash);
            CustomPreviewBeatmapLevel beatmap;

            using (SHA1 sha1Hash = SHA1.Create())
            {
                beatmap = SongCore.Loader.CustomLevels.FirstOrDefault(t => BitConverter.ToString(sha1Hash.ComputeHash(Encoding.UTF8.GetBytes(t.Value.levelID.ToUpper()))).Replace("-", String.Empty) == hash).Value;
            }
            GameplayModifiers modifiers = new GameplayModifiers();

            modifiers.batteryEnergy      = BitConverter.ToBoolean(data, 0);
            modifiers.disappearingArrows = BitConverter.ToBoolean(data, 1);
            modifiers.noObstacles        = BitConverter.ToBoolean(data, 2);
            modifiers.noBombs            = BitConverter.ToBoolean(data, 3);
            modifiers.noArrows           = BitConverter.ToBoolean(data, 4);
            bool slowerSong = BitConverter.ToBoolean(data, 5);

            modifiers.songSpeed = GameplayModifiers.SongSpeed.Normal;
            if (slowerSong)
            {
                modifiers.songSpeed = GameplayModifiers.SongSpeed.Slower;
            }
            modifiers.noFail     = BitConverter.ToBoolean(data, 6);
            modifiers.instaFail  = BitConverter.ToBoolean(data, 7);
            modifiers.ghostNotes = BitConverter.ToBoolean(data, 8);
            bool fasterSong = BitConverter.ToBoolean(data, 9);

            if (fasterSong)
            {
                modifiers.songSpeed = GameplayModifiers.SongSpeed.Faster;
            }
            songInfo.leftHanded = BitConverter.ToBoolean(data, 10);
            songInfo.difficulty = (BeatmapDifficulty)BitConverter.ToInt32(data, 12);
            songInfo.mode       = (BeatmapMode)BitConverter.ToInt32(data, 16);
            songInfo.beatmap    = beatmap;
            songInfo.modifiers  = modifiers;
            return(songInfo);
        }
Exemplo n.º 23
0
 public static byte[] ComputeSHAHash(byte[] bytes, int offset, int count)
 {
     return(s_sha.ComputeHash(bytes, offset, count));
 }
Exemplo n.º 24
0
 public string encrypt(string password)
 {
     byte[] b      = Encoding.ASCII.GetBytes(password);
     byte[] hashed = sh.ComputeHash(b);
     return(Convert.ToBase64String(hashed));
 }
Exemplo n.º 25
0
 private static byte[] ComputeHash(string str)
 {
     return(sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(str)));
 }
Exemplo n.º 26
0
        public static MemoryStream CreateInstaller(byte[] wadFileBytes, byte iosToUse)
        {
            const int injectionPosition     = 0x665FC;
            const int maxAllowedSizeForWads = 8 * 1024 * 1024 - 32; //(Max 4MB-32bytes )

            //0. Read length of the wad to ensure it has an allowed size
            uint wadLength = (uint)wadFileBytes.Length;

            if (wadLength > maxAllowedSizeForWads)
            {
                throw new ArgumentException(String.Format("The file is sized above the max allowed limit of {1} for network installation.", maxAllowedSizeForWads));
            }

            //1. Open the stub installer from resources
            MemoryStream compressedStubInstallerStream = LoadCompressedStubInstaller("WadInstaller.dol.z");

            compressedStubInstallerStream.Seek(0, SeekOrigin.Begin);

            //2. Decompress compressed installer
            MemoryStream uncompressedStubInstallerStream = new MemoryStream();

            using (GZipStream gzipStream = new GZipStream(compressedStubInstallerStream, CompressionMode.Decompress))
            {
                byte[] decompressedBuff = new byte[1024];
                while (true)
                {
                    int length = gzipStream.Read(decompressedBuff, 0, 1024);

                    if (length == 0)
                    {
                        break;
                    }

                    uncompressedStubInstallerStream.Write(decompressedBuff, 0, length);
                }
            }

            //3. Take SHA of the wad and store it in the stub installer along with the size of the wad

            byte[] shaHash;
            using (SHA1 shaGen = SHA1.Create())
            {
                shaHash = shaGen.ComputeHash(wadFileBytes);
            }

            //4. Inject the data into the installer

            //Write out the wad size
            uncompressedStubInstallerStream.Seek(injectionPosition, SeekOrigin.Begin);
            uncompressedStubInstallerStream.WriteByte((byte)((wadLength >> 24) & 0xff));
            uncompressedStubInstallerStream.WriteByte((byte)((wadLength >> 16) & 0xff));
            uncompressedStubInstallerStream.WriteByte((byte)((wadLength >> 8) & 0xff));
            uncompressedStubInstallerStream.WriteByte((byte)(wadLength & 0xff));

            //Write out the SHA1 value (Against corruption of the file on the network, this value will be checked by the installer)
            uncompressedStubInstallerStream.Write(shaHash, 0, 20);

            //Write out the ios to be used...
            uncompressedStubInstallerStream.WriteByte(iosToUse);

            //pad it with three zeroes (to align it into 32-bit)
            uncompressedStubInstallerStream.WriteByte(0); uncompressedStubInstallerStream.WriteByte(0); uncompressedStubInstallerStream.WriteByte(0);


            //Write out to be installed wad file's contents...
            uncompressedStubInstallerStream.Write(wadFileBytes, 0, (int)wadLength);

            return(uncompressedStubInstallerStream);
        }
Exemplo n.º 27
0
        protected void LoadInternal(BEncodedDictionary torrentInformation)
        {
            Check.TorrentInformation(torrentInformation);
            originalDictionary = torrentInformation;
            torrentPath        = "";

            try
            {
                foreach (KeyValuePair <BEncodedString, BEncodedValue> keypair in torrentInformation)
                {
                    switch (keypair.Key.Text)
                    {
                    case ("announce"):
                        // Ignore this if we have an announce-list
                        if (torrentInformation.ContainsKey("announce-list"))
                        {
                            break;
                        }
                        announceUrls.Add(new RawTrackerTier());
                        announceUrls[0].Add(keypair.Value.ToString());
                        break;

                    case ("creation date"):
                        try
                        {
                            try
                            {
                                creationDate = creationDate.AddSeconds(long.Parse(keypair.Value.ToString()));
                            }
                            catch (Exception e)
                            {
                                if (e is ArgumentOutOfRangeException)
                                {
                                    creationDate = creationDate.AddMilliseconds(long.Parse(keypair.Value.ToString()));
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            if (e is ArgumentOutOfRangeException)
                            {
                                throw new BEncodingException("Argument out of range exception when adding seconds to creation date.", e);
                            }
                            else if (e is FormatException)
                            {
                                throw new BEncodingException(String.Format("Could not parse {0} into a number", keypair.Value), e);
                            }
                            else
                            {
                                throw;
                            }
                        }
                        break;

                    case ("nodes"):
                        nodes = (BEncodedList)keypair.Value;
                        break;

                    case ("comment.utf-8"):
                        if (keypair.Value.ToString().Length != 0)
                        {
                            comment = keypair.Value.ToString();           // Always take the UTF-8 version
                        }
                        break;                                            // even if there's an existing value

                    case ("comment"):
                        if (String.IsNullOrEmpty(comment))
                        {
                            comment = keypair.Value.ToString();
                        }
                        break;

                    case ("publisher-url.utf-8"):                         // Always take the UTF-8 version
                        publisherUrl = keypair.Value.ToString();          // even if there's an existing value
                        break;

                    case ("publisher-url"):
                        if (String.IsNullOrEmpty(publisherUrl))
                        {
                            publisherUrl = keypair.Value.ToString();
                        }
                        break;

                    case ("azureus_properties"):
                        azureusProperties = keypair.Value;
                        break;

                    case ("created by"):
                        createdBy = keypair.Value.ToString();
                        break;

                    case ("encoding"):
                        encoding = keypair.Value.ToString();
                        break;

                    case ("info"):
                        using (SHA1 s = HashAlgoFactory.Create <SHA1>())
                            infoHash = new InfoHash(s.ComputeHash(keypair.Value.Encode()));
                        ProcessInfo(((BEncodedDictionary)keypair.Value));
                        break;

                    case ("name"):                                                   // Handled elsewhere
                        break;

                    case ("announce-list"):
                        if (keypair.Value is BEncodedString)
                        {
                            break;
                        }
                        BEncodedList announces = (BEncodedList)keypair.Value;

                        for (int j = 0; j < announces.Count; j++)
                        {
                            if (announces[j] is BEncodedList)
                            {
                                BEncodedList  bencodedTier = (BEncodedList)announces[j];
                                List <string> tier         = new List <string>(bencodedTier.Count);

                                for (int k = 0; k < bencodedTier.Count; k++)
                                {
                                    tier.Add(bencodedTier[k].ToString());
                                }

                                Toolbox.Randomize <string>(tier);

                                RawTrackerTier collection = new RawTrackerTier();
                                for (int k = 0; k < tier.Count; k++)
                                {
                                    collection.Add(tier[k]);
                                }

                                if (collection.Count != 0)
                                {
                                    announceUrls.Add(collection);
                                }
                            }
                            else
                            {
                                throw new BEncodingException(String.Format("Non-BEncodedList found in announce-list (found {0})",
                                                                           announces[j].GetType()));
                            }
                        }
                        break;

                    case ("httpseeds"):
                        // This form of web-seeding is not supported.
                        break;

                    case ("url-list"):
                        if (keypair.Value is BEncodedString)
                        {
                            getRightHttpSeeds.Add(((BEncodedString)keypair.Value).Text);
                        }
                        else if (keypair.Value is BEncodedList)
                        {
                            foreach (BEncodedString str in (BEncodedList)keypair.Value)
                            {
                                GetRightHttpSeeds.Add(str.Text);
                            }
                        }
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception e)
            {
                if (e is BEncodingException)
                {
                    throw;
                }
                else
                {
                    throw new BEncodingException("", e);
                }
            }
        }
Exemplo n.º 28
0
        public string GetData(String url, String getData, Account account, bool allowCaching, out String cookieHeader)
        {
            Console.WriteLine(url);
            try
            {
                String cachedFile = "";
                if (allowCaching)
                {
                    SHA1          sha1         = SHA1.Create();
                    byte[]        hashData     = sha1.ComputeHash(Encoding.UTF8.GetBytes("GET" + this.UrlEncode(account.accessToken) + "+" + this.UrlEncode(url) + "+" + this.UrlEncode(getData)));
                    StringBuilder cacheBuilder = new StringBuilder();
                    for (int i = 0; i < hashData.Length; i++)
                    {
                        cacheBuilder.Append(hashData[i].ToString());
                    }

                    cachedFile = cacheBuilder.ToString();
                    bool cacheValid = false;
                    if (File.Exists(Path.GetTempPath() + "Capella\\" + cachedFile + ".cache"))
                    {
                        if (!NetworkInterface.GetIsNetworkAvailable())
                        {
                            cacheValid = true;
                        }
                        DateTime lastModified = File.GetLastWriteTimeUtc(Path.GetTempPath() + "Capella\\" + cachedFile + ".cache");
                        TimeSpan ts           = DateTime.UtcNow - lastModified;
                        if (ts.TotalMinutes < 2)
                        {
                            cacheValid = true;
                        }
                    }
                    if (cacheValid)
                    {
                        cookieHeader = "";
                        return(File.ReadAllText(Path.GetTempPath() + "Capella\\" + cachedFile + ".cache", UTF8Encoding.UTF8));
                    }
                }

                String authorization = account.accessToken;

                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(new Uri(url + "?" + getData, UriKind.Absolute));
                req.Method    = "GET";
                req.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 11.0; Windows NT 6.1; en-US))";
                req.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
                req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
                req.Headers.Add("Authorization", "BEARER " + authorization);

                HttpWebResponse response = (HttpWebResponse)req.GetResponse();

                String cookie = response.GetResponseHeader("Set-Cookie");
                cookieHeader = cookie;

                Stream       stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream);

                String output = reader.ReadToEnd();
                if (allowCaching)
                {
                    if (!Directory.Exists(Path.GetTempPath() + "Capella\\"))
                    {
                        Directory.CreateDirectory(Path.GetTempPath() + "Capella\\");
                    }
                    try
                    {
                        File.WriteAllText(Path.GetTempPath() + "Capella\\" + cachedFile + ".cache", output);
                    }
                    catch (IOException c)
                    {
                        Console.WriteLine(c);
                    }
                }
                reader.Dispose();
                reader.Close();
                return(output);
            }
            catch (WebException err)
            {
                Console.WriteLine(err.ToString());
                using (WebResponse response = err.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                    using (Stream data = response.GetResponseStream())
                        using (var reader = new StreamReader(data))
                        {
                            string text = reader.ReadToEnd();
                            Console.WriteLine(text);
                            cookieHeader = "";
                            return(text);
                        }
                }
                return("");
            }
        }
Exemplo n.º 29
0
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        string loginName;
        string passWord;
        string companyname;    //单位名称
        string country;        //国家
        int    province = 0;   //省

        int city = 0;          //市

        int xian = 0;          //县

        int    sid;            //机构类别
        int    serviesgig = 0; //服务大类
        string serviesmall;    //服务小类
        int    scale   = 0;    //企业规模
        int    capital = 0;    //注册资金
        string createdate;     //企业创建时间
        string count;          // 营业额

        string directions;     //主营业务说明
        string website;        //网址
        string linkman;        //联系人

        string linktel;        //联系电话
        string fex;            //传真号码
        string email;          //电子邮件


        loginName   = this.usrname.Value;
        passWord    = Request.Form["repwd"];
        companyname = Request.Form["company"];
        country     = this.ZoneSelectControl1.CountryID.ToString();

        if (this.ZoneSelectControl1.CityID.ToString() != "")
        {
            city = int.Parse(this.ZoneSelectControl1.CityID.ToString());
        }

        if (this.ZoneSelectControl1.CountyID.ToString() != "")
        {
            xian = int.Parse(this.ZoneSelectControl1.CountyID.ToString());
        }
        if (this.ZoneSelectControl1.ProvinceID.ToString() != "")
        {
            province = int.Parse(this.ZoneSelectControl1.ProvinceID.ToString());
        }
        sid = Convert.ToInt32(structid.SelectedItem.Value);
        if (ServiesControl.ServicesBID.ToString() != "")
        {
            string[] Test      = ServiesControl.ServicesBID.Split(',');
            string   TestValue = Test[0].Trim();
            serviesgig = Convert.ToInt32(TestValue);
        }
        if (Request.Form["scale"].ToString() != "")
        {
            scale = int.Parse(Request.Form["scale"].ToString());
        }
        serviesmall = ServiesControl.ServicesMID.ToString();
        if (Request.Form["capital"].ToString() != "")
        {
            capital = int.Parse(Request.Form["capital"].ToString());
        }

        createdate = Request.Form["createdate"];
        count      = Request.Form["count"];
        directions = Request.Form["directions"];
        website    = Request.Form["website"];
        linkman    = Request.Form["linkman"];
        linktel    = Request.Form["linktel"];
        fex        = Request.Form["fex"];
        email      = Request.Form["email"];



        #region 验证提交的验证码并清空验证码
        ///--------------------------------------------------
        ///--验证提交的验证码并清空验证码
        ///--------------------------------------------------
        string vercode   = Request.Form["vercode"];
        string strRndNum = "";
        //SESSION丢失
        if (Session["valationNo"] == null)
        {
            Response.Write("<script>alert('操作超时!请刷新页面!');</script>");
            return;
        }
        else
        {
            if (vercode.Trim() == "")
            {
                Response.Write("<script>alert('验证码不能为空,请重新提交!');</script>");
                return;
            }
            else
            {
                strRndNum = Session["valationNo"].ToString();
                if (vercode.Trim() != "" && vercode.ToLower().Trim() == strRndNum.ToLower())
                {
                    Session["valationNo"] = "";
                }
                else
                {
                    Response.Write("<script>alert('验证码错误,请重新提交!');</script>");
                    return;
                }
            }
        }
        #endregion


        //注册信息
        SHA1   sha1      = SHA1.Create();
        byte[] passWord2 = sha1.ComputeHash(Encoding.Unicode.GetBytes(passWord.Trim()));

        LoginInfoModel model = new LoginInfoModel();

        if (Request.Cookies["adv_cpa"] != null)
        {
            HttpCookie logCook = Request.Cookies["adv_cpa"];
            model.adsiteID = logCook.Value.ToString();

            model.autoReg = 2;
        }

        model.LoginName     = loginName;
        model.Password      = passWord2;
        model.RoleName      = "0";//会员
        model.ManageTypeID  = "2007";
        model.MemberGradeID = "1001";
        model.IsCheckUp     = false;
        model.Email         = email;
        model.Tel           = linktel;
        model.CompanyName   = companyname;
        model.NickName      = " ";
        model.PWDAnswere    = "";
        model.PWDQuestion   = "";
        model.RequirInfo    = "";

        //--------会员信息
        MemberInfoModel memberModel = new MemberInfoModel();
        memberModel.LoginName    = loginName;
        memberModel.Email        = email;
        memberModel.ManageTypeID = "2007";
        //memberModel.RequirInfo = requirInfo;
        memberModel.Tel      = linktel;
        memberModel.Mobile   = linktel;
        memberModel.Birthday = DateTime.Now;

        // -------------专业服务机构
        Tz888.Model.Register.SS_Agency_Services service = new SS_Agency_Services();
        service.LoginName        = loginName;
        service.OrganName        = companyname;
        service.OrganType        = sid;
        service.CountryCode      = country;
        service.ProvinceID       = province;
        service.CityID           = city;
        service.Area             = xian;
        service.ServiceBigtype   = serviesgig;
        service.ServiceSmalltype = serviesmall;
        service.BusinessCount    = scale;
        service.BusinessView     = directions;
        service.Bankroll         = capital;
        service.FoundDate        = createdate;
        service.Turnover         = count;
        service.www      = website;
        service.LinkName = linkman;
        service.Tel      = linktel;
        service.FAX      = fex;
        service.Email    = email;
        service.Regdate  = DateTime.Now;



        LoginInfoBLL loginfo = new LoginInfoBLL();
        Tz888.BLL.Register.SS_Agency_ServicesBLL smode = new SS_Agency_ServicesBLL();
        MemberInfoBLL member = new MemberInfoBLL();
        try
        {
            //机构服务表

            try
            { smode.AgencyAdd(service); }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw (new Exception(ex.Message));
            }
            //向注册表写数据


            try
            { loginfo.LogInfoAdd(model); }
            catch (System.Data.SqlClient.SqlException ex)
            {
                throw (new Exception(ex.Message));
            }


            // 会员信息
            int i = member.MemberMessage_Insert(memberModel);

            string encryEmail   = Server.UrlEncode(DEncrypt.Encrypt(email));
            string encryLogname = Server.UrlEncode(DEncrypt.Encrypt(loginName));
            string act          = Server.UrlEncode(DEncrypt.Encrypt("register"));
            string strPass      = Server.UrlEncode(DEncrypt.Encrypt(passWord));
            string ValidUrl     = "ValidSuccessGov.aspx?email=" + encryEmail + "&logname=" + encryLogname + "&act=" + act + "&PassWord="******"数据提交时出错,注册失败。");
        }
        finally
        {
            string encryEmail   = Server.UrlEncode(DEncrypt.Encrypt(email));
            string encryLogname = Server.UrlEncode(DEncrypt.Encrypt(loginName));
            string act          = Server.UrlEncode(DEncrypt.Encrypt("register"));
            string strPass      = Server.UrlEncode(DEncrypt.Encrypt(passWord));
            string ValidUrl     = "ValidSuccessGov.aspx?email=" + encryEmail + "&logname=" + encryLogname + "&act=" + act + "&PassWord=" + strPass;
            Response.Redirect(ValidUrl, true);
        }
    }
Exemplo n.º 30
0
        protected override void HashCore(byte[] array, int ibStart, int cbSize)
        {
            while (cbSize != 0)
            {
                if (blockLengthTodo > cbSize)
                {
                    blockHasher.TransformBlock(array, ibStart, cbSize, null, 0);

                    blockLengthTodo -= cbSize;
                    ibStart         += cbSize;
                    cbSize           = 0;
                    return;
                }
                else if (blockLengthTodo != 0)
                {
                    blockHasher.TransformFinalBlock(array, ibStart, blockLengthTodo);
                    blockHashes.Add(blockHasher.Hash);
                    blockHasher.Initialize();

                    ibStart        += blockLengthTodo;
                    cbSize         -= blockLengthTodo;
                    blockLengthTodo = 0;
                }

                while (blockHashes.Count < 52 && cbSize >= BLOCKSIZE)
                {
                    blockHashes.Add(blockHasher.ComputeHash(array, ibStart, BLOCKSIZE));
                    ibStart += BLOCKSIZE;
                    cbSize  -= BLOCKSIZE;
                }

                if (blockHashes.Count < 52)
                {
                    blockHasher.TransformBlock(array, ibStart, cbSize, null, 0);
                    blockLengthTodo = BLOCKSIZE - cbSize;
                    ibStart        += cbSize;
                    cbSize          = 0;
                }
                else if (blockHashes.Count == 52)
                {
                    if (cbSize < BLOCKSIZEREMAINDER)
                    {
                        blockHasher.TransformBlock(array, ibStart, cbSize, null, 0);
                        blockLengthTodo = BLOCKSIZEREMAINDER - cbSize;
                        ibStart        += cbSize;
                        cbSize          = 0;
                    }
                    else
                    {
                        blockHashes.Add(blockHasher.ComputeHash(array, ibStart, BLOCKSIZEREMAINDER));
                        ibStart += BLOCKSIZEREMAINDER;
                        cbSize  -= BLOCKSIZEREMAINDER;
                    }
                }

                if (blockHashes.Count == 53)
                {
                    partHashes.Add(CreateRootHash(blockHashes));
                    blockHashes.Clear();
                }
            }
        }