/// <summary>The encryption of a digest it the atomic operation done by the SSCD.</summary>
 /// <remarks>
 /// The encryption of a digest it the atomic operation done by the SSCD. This encryption (RSA, DSA, ...) create the
 /// signature value.
 /// </remarks>
 /// <param name="digest"></param>
 /// <param name="keyEntry"></param>
 /// <returns></returns>
 /// <exception cref="Sharpen.NoSuchAlgorithmException">Sharpen.NoSuchAlgorithmException
 /// 	</exception>
 public virtual byte[] EncryptDigest(Digest digest, IDssPrivateKeyEntry keyEntry)
 {
     return this.EncryptDigest(digest.GetValue(), digest.GetAlgorithm(), keyEntry);
 }
Esempio n. 2
0
    public void TestAddDigestFeatures()
    {
      Sequence seq = new Sequence("Test", "AAANESAARBBBNPSBBKFFFNITFFRGGGNDTGGR");

      Digest digest = new Digest();
      digest.DigestProtease = ProteaseManager.CreateProtease("Trypsin_TestAddDigestFeatures", true, "RK", "P");
      digest.ProteinSequence = seq;

      digest.MaxMissedCleavages = 0;
      digest.AddDigestFeatures();
      List<DigestPeptideInfo> peptides = (List<DigestPeptideInfo>)seq.Annotation[Digest.PEPTIDE_FEATURE_TYPE];
      Assert.AreEqual(4, peptides.Count);

      digest.MaxMissedCleavages = 1;
      digest.AddDigestFeatures();
      List<DigestPeptideInfo> missedPeptides = (List<DigestPeptideInfo>)seq.Annotation[Digest.PEPTIDE_FEATURE_TYPE];
      Assert.AreEqual(7, missedPeptides.Count);

      IRangeLocationFilter nglycanFilter = new NGlycanFilter();
      digest.MaxMissedCleavages = 0;
      digest.Filter = nglycanFilter;
      digest.AddDigestFeatures();
      List<DigestPeptideInfo> nglycanPeptides = (List<DigestPeptideInfo>)seq.Annotation[Digest.PEPTIDE_FEATURE_TYPE];
      Assert.AreEqual(2, nglycanPeptides.Count);
      Assert.AreEqual("AAANESAAR", nglycanPeptides[0].PeptideSeq);
      Assert.AreEqual("FFFNITFFR", nglycanPeptides[1].PeptideSeq);
    }
Esempio n. 3
0
        public static int GetConflictPriority(Digest digest, string EndPoint)
        {
            foreach (DigestEntry entry in digest.Entries)
                if ((entry.EndPoint != null) && (entry.EndPoint.Equals(EndPoint, StringComparison.InvariantCultureIgnoreCase)))
                    return entry.ConflictPriority;

            return 10000;
        }
Esempio n. 4
0
 //запускаем инкременый поиск в папках
 public void gogle()
 {
     string[] PatchDir = Directory.GetDirectories(StartPatch);
     try
     {
         foreach(string MyPatch in PatchDir)
         {
             //создаем задачу
             Potok ForStartTask;
             //создаем новый обьект класса Sercher
             ForStartTask.Sercher = new Searchkliko()
             {
                 //передаем в него путь где нужно искать Kliko
                 StartPatch = MyPatch
             };
             //задаем функцию которую будем выполнять в отдельном потоке
             ForStartTask.PotockSearch = new Thread(ForStartTask.Sercher.GetSearch);
             //добавляем данный поток в список для поиска
             TaskList.Add(ForStartTask);
             //запускаем поиск
             ForStartTask.PotockSearch.Start();
         }
     }
     catch
     {
     }
     //Итак ждем завершения поиска всех данных
     while (Finished())
     {
         //чтобы процесс не вешал систему проверяем действие каждые 50 милисекунд
         Thread.Sleep(50);
     }
     //обьявляем класс вохранения данных в таблицу
     Digest MyDigest = new Digest();
       //  Console.WriteLine(" поиск окончен сохраняем данные ");
     //когда все потоки закончат поиск будем соберать данные в таблицу
     foreach (Potok SelectTask in TaskList)
     {
         //перебираем данные из найденного списка
         foreach (string FindPatch in SelectTask.Sercher.SerchResult)
         {
            // Console.WriteLine("получение данных о "+FindPatch);
             //добавляем данные в таблицу
             MyDigest.Digestpatch = FindPatch;
             //добавляем данные в таблицу
             MyDigest.ADDRowDigest();
            // Console.WriteLine("Время обновления папки " + MyDigest.DateUpdate+"\t Путь к диретории " + MyDigest.Digestpatch+"\t Имя Kliko" + MyDigest.DigestName );
         }
     }
 }
        public void DoWork(IRequest request, IFeed feed, Digest digest)
        {
            //  ReturnSample(request);
               // return;
            // If an asyncState object already exists, an exception is thrown as the performer only accepts
            // one call after each other. The Request receiver has to manage a queued execution.

            // Before calling the performers execution implementation method a new AsyncState object is created
            // and set to an initial tracking state.

            lock (_asyncStateObj)
            {
                if (null != _asyncStateObj.Tracking)
                    throw new InvalidOperationException("The performer cannot be executed because it is already running.");

                ITracking tracking = new Tracking();
                tracking.ElapsedSeconds = 1;
                tracking.Phase = TrackingPhase.INIT;
                tracking.PhaseDetail = "Tracking Id was: " + _requestContext.TrackingId.ToString();
                tracking.PollingMillis = 100;
                tracking.RemainingSeconds = 100;

                _asyncStateObj.Tracking = tracking;
            }

            // *** Initialization for the async execution ***
            // - Read Feed from request stream.
            // - Read trackingId from request URL

            // convert tracking ID from request to type Guid
            string strTrackingId = request.Uri.TrackingID;
            if (String.IsNullOrEmpty(strTrackingId))
                throw new RequestException("TrackingId is missing");

            GuidConverter converter = new GuidConverter();
            this.TrackingId = (Guid)converter.ConvertFrom(strTrackingId);

            // *** Do work asynchronously ***
            _asyncPerformer = new InternalAsyncPerformer(this);
            _asyncPerformer.DoWork(_requestContext.Config, feed, digest);

            // *** set the tracking to the request response ***
            this.GetTrackingState(request);
        }
Esempio n. 6
0
                public static Digest/*!*/ Initialize(Digest/*!*/ self, [NotNull]MutableString/*!*/ algorithmName) {
                    Crypto.HMAC algorithm;

#if SILVERLIGHT
                    switch (algorithmName.ToString()) {
                        case "SHA1": algorithm = new Crypto.HMACSHA1(); break;
                        case "SHA256": algorithm = new Crypto.HMACSHA256(); break;
                        default: algorithm = null; break;
                    }
#else
                    algorithm = Crypto.HMAC.Create("HMAC" + algorithmName.ConvertToString());
#endif

                    if (algorithm == null) {
                        throw RubyExceptions.CreateRuntimeError("Unsupported digest algorithm ({0}).", algorithmName);
                    }

                    self._algorithm = algorithm;
                    return self;
                }
Esempio n. 7
0
        /// <summary>
        /// Adds members to the Membership and multicast the new view.
        /// </summary>
        /// <param name="mbr">New Member requesting join</param>
        /// <returns><c>JoinRsp</c> containing new view and digest</returns>
        public override JoinRsp handleJoin(Address mbr)
        {
            lock(this)
            {
                ArrayList new_mbrs = new ArrayList();
                View v = null;
                Digest d, tmp;

                if (Trace.trace)
                    Trace.info("CoordGmsImpl.handleJoin()", "mbr=" + mbr);

                if (gms.local_addr.Equals(mbr))
                {
                    if(Trace.trace)
                        Trace.error("CoordGmsImpl.handleJoin()", "cannot join myself !");
                    return null;
                }

                if (gms.members.contains(mbr))
                {
                    if (Trace.trace)
                        Trace.error("CoordGmsImpl.handleJoin()","member "+ mbr+ " already present; returning existing view "+ gms.members.getMembers());
                    return new JoinRsp(new View(gms.view_id, gms.members.getMembers()),gms.getDigest());
                    // already joined: return current digest and membership
                }
                new_mbrs.Add(mbr);
                tmp = gms.getDigest(); // get existing digest
                if (Trace.trace)
                    Trace.info("CoordGmsImpl.handleJoin()", "got digest=" + tmp);

                d = new Digest(tmp.size() + 1);
                // create a new digest, which contains 1 more member
                d.add(tmp); // add the existing digest to the new one
                d.add(mbr, 0, 0);
                // ... and add the new member. it's first seqno will be 1
                v = gms.getNextView(new_mbrs, null, null);
                if (Trace.trace)
                    Trace.info("CoordGmsImpl.handleJoin()","joined member " + mbr + ", view is " + v.getMembers());
                return new JoinRsp(v, d);
            }
        }
Esempio n. 8
0
 /// <summary>
 /// All views are ignored while GMS is a client
 /// </summary>
 /// <param name="new_view">Ignored</param>
 /// <param name="digest">Ignored</param>
 public override void handleViewChange(View new_view, Digest digest)
 {
     if(Trace.trace)
             Trace.info("ClientGmsImpl.handleViewChange()", "view " + new_view.getMembers() +
                 " is discarded as we are not a participant");
 }
Esempio n. 9
0
 /// <summary>
 /// Constructor: Deserialises the information and recreates the instance.
 /// </summary>
 /// <param name="info">Standard <c>SerializationInfo</c> object</param>
 /// <param name="ctxt">Standard <c>StreamingContext</c> object</param>
 public GmsHeader(SerializationInfo info, StreamingContext ctxt)
 {
     type = info.GetInt32("type");
     //merge_rejected = info.GetBoolean("merge_rejected");
     view = (View)info.GetValue("view", typeof(object));
     mbr = (Address)info.GetValue("mbr", typeof(object));
     join_rsp = (JoinRsp)info.GetValue("join_rsp", typeof(object));
     digest = (Digest)info.GetValue("digest", typeof(object));
 }
Esempio n. 10
0
        private static void WriteOutputHtml(IEnumerable <KeyValuePair <string, double> > crossCorrelationResults, List <string> crossCorrelationMismatches, Digest againstHash, StreamWriter sw, DirectoryInfo di, FileInfo fi)
        {
            sw.Write("<h2>");
            sw.Write(di.Name);
            sw.Write("/");
            sw.Write(fi.Name);
            sw.WriteLine("</h2>");

            sw.Write("<img src=\"");
            sw.Write(new Uri(fi.FullName));
            sw.WriteLine("\" />");

            sw.Write("<p>");
            sw.Write(againstHash.ToString());
            sw.WriteLine("</p>");

            foreach (var mismatch in crossCorrelationMismatches)
            {
                Console.WriteLine(mismatch);
                sw.Write("<p>");
                sw.Write(mismatch);
                sw.WriteLine("</p>");
            }

            foreach (var result in crossCorrelationResults)
            {
                var key = result.Key;
                var D   = result.Value;
                Console.WriteLine(" - - {0}: {1}", Path.GetFileName(key), D);

                sw.Write("<img width='64' height='64' src=\"");
                sw.Write(new Uri(key));
                sw.WriteLine("\" />");

                sw.WriteLine(D);
            }
        }
Esempio n. 11
0
 /// <summary>
 /// Gets the key hash.
 /// </summary>
 /// <returns></returns>
 public override byte[] GetKeyHash()
 => Utility.HashKey(KeyczarConst.KeyHashLength, HmacKeyBytes, Utility.GetBytes(HashLength), Digest.ToBytes());
Esempio n. 12
0
        /// <summary>
        /// Compare this object instance with another
        /// </summary>
        ///
        /// <param name="Obj">Object to compare</param>
        ///
        /// <returns>True if equal, otherwise false</returns>
        public override bool Equals(Object Obj)
        {
            if (this == Obj)
            {
                return(true);
            }
            if (Obj == null)
            {
                return(false);
            }

            NTRUParameters other = (NTRUParameters)Obj;

            if (N != other.N)
            {
                return(false);
            }
            if (BufferLenBits != other.BufferLenBits)
            {
                return(false);
            }
            if (_bufferLenTrits != other._bufferLenTrits)
            {
                return(false);
            }
            if (CBits != other.CBits)
            {
                return(false);
            }
            if (Db != other.Db)
            {
                return(false);
            }
            if (DF != other.DF)
            {
                return(false);
            }
            if (DF1 != other.DF1)
            {
                return(false);
            }
            if (DF2 != other.DF2)
            {
                return(false);
            }
            if (DF3 != other.DF3)
            {
                return(false);
            }
            if (Dg != other.Dg)
            {
                return(false);
            }
            if (Dm0 != other.Dm0)
            {
                return(false);
            }
            if (MaxM1 != other.MaxM1)
            {
                return(false);
            }
            if (DR != other.DR)
            {
                return(false);
            }
            if (DR1 != other.DR1)
            {
                return(false);
            }
            if (DR2 != other.DR2)
            {
                return(false);
            }
            if (DR3 != other.DR3)
            {
                return(false);
            }
            if (FastFp != other.FastFp)
            {
                return(false);
            }
            if (!Digest.Equals(other.Digest))
            {
                return(false);
            }
            if (!RandomEngine.Equals(other.RandomEngine))
            {
                return(false);
            }
            if (HashSeed != other.HashSeed)
            {
                return(false);
            }
            if (Length != other.Length)
            {
                return(false);
            }
            if (MessageMax != other.MessageMax)
            {
                return(false);
            }
            if (MinMGFHashCalls != other.MinMGFHashCalls)
            {
                return(false);
            }
            if (MinIGFHashCalls != other.MinIGFHashCalls)
            {
                return(false);
            }
            if (!Compare.AreEqual(OId, other.OId))
            {
                return(false);
            }
            if (PkLen != other.PkLen)
            {
                return(false);
            }
            if (!PolyType.Equals(other.PolyType))
            {
                return(false);
            }
            if (Q != other.Q)
            {
                return(false);
            }
            if (Sparse != other.Sparse)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 13
0
                public static MutableString/*!*/ BlankDigest(Digest/*!*/ self) {
#if !SILVERLIGHT
                    // TODO: This support only SHA1, It should use self._algorithm but It is not
                    byte[] blank_data = Encoding.UTF8.GetBytes("");
                    byte[] hash = new SHA1CryptoServiceProvider().ComputeHash(blank_data);
                    return MutableString.CreateBinary(hash);
#else
            throw new NotSupportedException();
#endif
                }
Esempio n. 14
0
 /// <summary>
 /// Returns the address that corresponds to the public part of this ECKey. Note that an address is derived from
 /// the RIPEMD-160 hash of the public key and is not the public key itself (which is too large to be convenient).
 /// </summary>
 public Address ToAddress()
 {
     byte[] hashedPubKey = Digest.Hash <RIPEMD160, SHA256>(PubKey);
     return(new Address(Base58.EncodeWithChecksum(ArrayHelpers.ConcatArrays(new byte[] { 0x00 }, hashedPubKey))));
 }
Esempio n. 15
0
 /// <summary>
 /// Sets the new view and sends a VIEW_CHANGE event up and down the stack.
 /// </summary>
 /// <param name="new_view">New View to install</param>
 /// <param name="digest">Digest associated with View</param>
 public void installView(View new_view, Digest digest)
 {
     if(digest != null)
         mergeDigest(digest);
     installView(new_view);
 }
Esempio n. 16
0
        protected void scanFile_Click(object sender, EventArgs e)
        {
            waiting.Visible        = false;
            addImage.Visible       = false;
            imageTitle.Visible     = false;
            imageAuthor.Visible    = false;
            addImageResult.Visible = false;

            if (uploadedfile.HasFile)
            {
                String fileName = uploadedfile.FileName;
                savePath += fileName;
                uploadedfile.SaveAs(savePath);

                string fileExtension = Path.GetExtension(savePath);

                if (fileExtension.Equals(".jpg") || fileExtension.Equals(".png"))
                {
                    // Retrieve all fingerprint for comparison
                    ImageFingerprint image       = new ImageFingerprint();
                    ArrayList        fingerprint = image.retrieveAllHashes();

                    int pcc = 0;
                    ImageFingerprint matchingPictures = null;
                    int highestPcc = 30;

                    // Retrieve digest of input image for comparison
                    DigestRaw raw = new DigestRaw();
                    ph_image_digest(savePath, 1, 1, ref raw, 180);
                    Digest d = Digest.fromRaw(raw);

                    // Compare fingerprint
                    for (int i = 0; i < fingerprint.Count; i++)
                    {
                        // Generate a struct for comparison from database
                        Digest d2 = new Digest();
                        d2.id     = ((ImageFingerprint)fingerprint[i]).getDigestId();
                        d2.coeffs = ((ImageFingerprint)fingerprint[i]).getDigestCoeffs();
                        d2.size   = 40;

                        // Compare the results
                        pcc = computeSimilarities(d.coeffs, d2.coeffs);

                        if (pcc >= highestPcc)
                        {
                            matchingPictures = (ImageFingerprint)fingerprint[i];
                            highestPcc       = pcc;
                        }
                    }

                    // Compute hash values
                    ulong hasha = 0;
                    ph_dct_imagehash(savePath, ref hasha);

                    if (matchingPictures == null)
                    {
                        int minHammingDistance = 20;
                        for (int i = 0; i < fingerprint.Count; i++)
                        {
                            // Compute Hamming Distance
                            int hammingDistance = computeHammingDistance(hasha, ((ImageFingerprint)fingerprint[i]).getHash());

                            if (hammingDistance < minHammingDistance)
                            {
                                matchingPictures   = (ImageFingerprint)fingerprint[i];
                                minHammingDistance = hammingDistance;
                            }
                        }

                        if (minHammingDistance <= 10)
                        {
                            result.Text = "An image has been identified with the following information:<br/><br/>" +
                                          "Title: <b>" + matchingPictures.getImageTitle() + "</b><br/>" +
                                          "Author: " + matchingPictures.getImageAuthor() + "<br/>" +
                                          "Hamming Distance: " + minHammingDistance + "<br/>";
                        }
                        else
                        {
                            result.Text         = "<b>No pictures has been identified in our database.</b><br/><br/>You can contribute by adding this image into our database.";
                            pathName.Text       = savePath;
                            addImage.Visible    = true;
                            imageAuthor.Visible = true;
                            imageTitle.Visible  = true;

                            imageTitle.Text  = "Enter Title...";
                            imageAuthor.Text = "Enter Author...";

                            imageTitle.Attributes.Add("onfocus", "if(this.value == 'Enter Title...') this.value='';");
                            imageTitle.Attributes.Add("onblur", "if(this.value == '' || this.value == ' ') this.value='Enter Title...'");

                            imageAuthor.Attributes.Add("onfocus", "if(this.value == 'Enter Author...') this.value='';");
                            imageAuthor.Attributes.Add("onblur", "if(this.value == '' || this.value == ' ') this.value='Enter Author...'");
                        }
                    }
                    else
                    {
                        result.Text = "An image has been identified with the following information:<br/><br/>" +
                                      "Title: <b>" + matchingPictures.getImageTitle() + "</b><br/>" +
                                      "Author: " + matchingPictures.getImageAuthor() + "<br/>" +
                                      "Similarities with copyrighted image: " + (highestPcc / 40.0) * 100 + " %<br/>";
                    }

                    result.Visible = true;
                }
                else
                {
                    waiting.Text    = "Incorrect file format has been used. Only jpg and png files will be accepted.";
                    waiting.Visible = true;
                }
            }
            else
            {
                waiting.Text    = "No file has been selected for analysis";
                waiting.Visible = true;
            }
        }
Esempio n. 17
0
        async void AtomicTransfer_Clicked(System.Object sender, System.EventArgs e)
        {
            //var transParams = algodApiInstance.TransactionParams();
            AtomicTransfer.Opacity         = .2;
            StackAtomicTransfers.IsEnabled = false;
            Algorand.V2.Model.TransactionParametersResponse transParams = null;
            AtomicTransfer.IsEnabled = false;

            try
            {
                transParams = algodApiInstance.TransactionParams();
            }
            catch (ApiException err)
            {
                throw new Exception("Could not get params", err);
            }
            // let's create a transaction group
            var amount = Utils.AlgosToMicroalgos(1);
            var tx     = Utils.GetPaymentTransaction(account1.Address, account2.Address, amount, "pay message", transParams);
            var tx2    = Utils.GetPaymentTransaction(account1.Address, account3.Address, amount, "pay message", transParams);
            //SignedTransaction signedTx2 = src.SignTransactionWithFeePerByte(tx2, feePerByte);
            Digest gid = TxGroup.ComputeGroupID(new Algorand.Transaction[] { tx, tx2 });

            tx.AssignGroupID(gid);
            tx2.AssignGroupID(gid);
            // already updated the groupid, sign
            var signedTx  = account1.SignTransaction(tx);
            var signedTx2 = account1.SignTransaction(tx2);

            try
            {
                //contact the signed msgpack
                List <byte> byteList = new List <byte>(Algorand.Encoder.EncodeToMsgPack(signedTx));
                byteList.AddRange(Algorand.Encoder.EncodeToMsgPack(signedTx2));
                var act = await algodApiInstance.AccountInformationAsync(account1.Address.ToString());

                var before = "Account 1 balance before: " + act.Amount.ToString();
                var id     = algodApiInstance.RawTransaction(byteList.ToArray());
                var wait   = Utils.WaitTransactionToComplete(algodApiInstance, id.TxId);
                Console.WriteLine(wait);

                // Console.WriteLine("Successfully sent tx group with first tx id: " + id);

                act = await algodApiInstance.AccountInformationAsync(account1.Address.ToString());

                await SecureStorage.SetAsync(helper.StorageAtomicTransaction, wait.ToString());

                var htmlSource = new HtmlWebViewSource();
                htmlSource.Html = @"<html><body><h3>" + before + " </h3>" +
                                  "<h3>" + wait + "</h3>" + "<h3> Account 1 balance after: " + act.Amount.ToString() + "</h3></body></html>";

                myWebView.Source         = htmlSource;
                AtomicTransfer.IsEnabled = true;
            }
            catch (ApiException err)
            {
                // This is generally expected, but should give us an informative error message.
                Console.WriteLine("Exception when calling algod#rawTransaction: " + err.Message);
                AtomicTransfer.IsEnabled = true;
            }
            AtomicTransfer.Opacity         = 1;
            StackAtomicTransfers.IsEnabled = true;
            AtomicTransferInfo.IsEnabled   = true;
            buttonstate();
        }
Esempio n. 18
0
 public static extern int ph_crosscorr(ref Digest digesta, ref Digest digestb, ref double pcc, double threshold);
Esempio n. 19
0
        private void SendHeaders(BinaryWriter stream)
        {
            if (!this.HasHeader("Host"))
            {
                this.SetHeader("Host", this.CurrentUri.Authority);
            }
            if (this.IsRedirected && !this.HasHeader("Referer"))
            {
                this.AddHeader("Referer", this.Uri.ToString());
            }
            if (!this.HasHeader("Accept-Encoding"))
            {
                this.AddHeader("Accept-Encoding", "gzip, identity");
            }
            if (this.HasProxy && !this.HasHeader("Proxy-Connection"))
            {
                this.AddHeader("Proxy-Connection", (!this.IsKeepAlive) ? "Close" : "Keep-Alive");
            }
            if (!this.HasHeader("Connection"))
            {
                this.AddHeader("Connection", (!this.IsKeepAlive) ? "Close, TE" : "Keep-Alive, TE");
            }
            if (!this.HasHeader("TE"))
            {
                this.AddHeader("TE", "identity");
            }
            if (!this.HasHeader("User-Agent"))
            {
                this.AddHeader("User-Agent", "BestHTTP");
            }
            long num;

            if (this.UploadStream == null)
            {
                byte[] entityBody = this.GetEntityBody();
                num = (long)((entityBody == null) ? 0 : entityBody.Length);
                if (this.RawData == null && (this.FormImpl != null || (this.FieldCollector != null && !this.FieldCollector.IsEmpty)))
                {
                    this.SelectFormImplementation();
                    if (this.FormImpl != null)
                    {
                        this.FormImpl.PrepareRequest(this);
                    }
                }
            }
            else
            {
                num = this.UploadStreamLength;
                if (num == -1L)
                {
                    this.SetHeader("Transfer-Encoding", "Chunked");
                }
                if (!this.HasHeader("Content-Type"))
                {
                    this.SetHeader("Content-Type", "application/octet-stream");
                }
            }
            if (num != -1L && !this.HasHeader("Content-Length"))
            {
                this.SetHeader("Content-Length", num.ToString());
            }
            if (this.HasProxy && this.Proxy.Credentials != null)
            {
                switch (this.Proxy.Credentials.Type)
                {
                case AuthenticationTypes.Unknown:
                case AuthenticationTypes.Digest:
                {
                    Digest digest = DigestStore.Get(this.Proxy.Address);
                    if (digest != null)
                    {
                        string value = digest.GenerateResponseHeader(this, this.Proxy.Credentials);
                        if (!string.IsNullOrEmpty(value))
                        {
                            this.SetHeader("Proxy-Authorization", value);
                        }
                    }
                    break;
                }

                case AuthenticationTypes.Basic:
                    this.SetHeader("Proxy-Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(this.Credentials.UserName + ":" + this.Credentials.Password)));
                    break;
                }
            }
            if (this.Credentials != null)
            {
                switch (this.Credentials.Type)
                {
                case AuthenticationTypes.Unknown:
                case AuthenticationTypes.Digest:
                {
                    Digest digest2 = DigestStore.Get(this.CurrentUri);
                    if (digest2 != null)
                    {
                        string value2 = digest2.GenerateResponseHeader(this, this.Credentials);
                        if (!string.IsNullOrEmpty(value2))
                        {
                            this.SetHeader("Authorization", value2);
                        }
                    }
                    break;
                }

                case AuthenticationTypes.Basic:
                    this.SetHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(this.Credentials.UserName + ":" + this.Credentials.Password)));
                    break;
                }
            }
            List <Cookie> list = (!this.IsCookiesEnabled) ? null : CookieJar.Get(this.CurrentUri);

            if (list == null)
            {
                list = this.customCookies;
            }
            else if (this.customCookies != null)
            {
                list.AddRange(this.customCookies);
            }
            if (list != null && list.Count > 0)
            {
                bool               flag            = true;
                string             text            = string.Empty;
                bool               flag2           = HTTPProtocolFactory.IsSecureProtocol(this.CurrentUri);
                SupportedProtocols protocolFromUri = HTTPProtocolFactory.GetProtocolFromUri(this.CurrentUri);
                foreach (Cookie current in list)
                {
                    if ((!current.IsSecure || (current.IsSecure && flag2)) && (!current.IsHttpOnly || (current.IsHttpOnly && protocolFromUri == SupportedProtocols.HTTP)))
                    {
                        if (!flag)
                        {
                            text += "; ";
                        }
                        else
                        {
                            flag = false;
                        }
                        text += current.ToString();
                        current.LastAccess = DateTime.UtcNow;
                    }
                }
                this.SetHeader("Cookie", text);
            }
            foreach (KeyValuePair <string, List <string> > current2 in this.Headers)
            {
                byte[] aSCIIBytes = (current2.Key + ": ").GetASCIIBytes();
                for (int i = 0; i < current2.Value.Count; i++)
                {
                    stream.Write(aSCIIBytes);
                    stream.Write(current2.Value[i].GetASCIIBytes());
                    stream.Write(HTTPRequest.EOL);
                }
            }
        }
Esempio n. 20
0
 private static List <KeyValuePair <string, double> > CrossCorrelateDigests(Dictionary <string, Digest> hashes, Digest againstHash)
 {
     return(hashes
            .Select(kv => new KeyValuePair <string, double>(kv.Key, ImagePhash.GetCrossCorrelation(againstHash, kv.Value)))
            .OrderBy(_ => _.Value)
            .ToList());
 }
Esempio n. 21
0
 /// <summary>
 /// Constructor: Deserialises the information and recreates the instance.
 /// </summary>
 /// <param name="info">Standard <c>SerializationInfo</c> object</param>
 /// <param name="ctxt">Standard <c>StreamingContext</c> object</param>
 public StableHeader(SerializationInfo info, StreamingContext ctxt)
 {
     type = info.GetInt32("type");
     digest = (Digest)info.GetValue("digest", typeof(object));
 }
Esempio n. 22
0
        private void ThreadFunc(object param)
        {
            bool flag  = false;
            bool flag2 = false;

            HTTPConnection.RetryCauses retryCauses = HTTPConnection.RetryCauses.None;
            try
            {
                if (!this.HasProxy && this.CurrentRequest.HasProxy)
                {
                    this.Proxy = this.CurrentRequest.Proxy;
                }
                if (!this.TryLoadAllFromCache())
                {
                    if (this.Client != null && !this.Client.IsConnected())
                    {
                        this.Close();
                    }
                    while (true)
                    {
                        if (retryCauses == HTTPConnection.RetryCauses.Reconnect)
                        {
                            this.Close();
                            Thread.Sleep(100);
                        }
                        this.LastProcessedUri = this.CurrentRequest.CurrentUri;
                        retryCauses           = HTTPConnection.RetryCauses.None;
                        this.Connect();
                        if (this.State == HTTPConnectionStates.AbortRequested)
                        {
                            break;
                        }
                        if (!this.CurrentRequest.DisableCache)
                        {
                            HTTPCacheService.SetHeaders(this.CurrentRequest);
                        }
                        bool flag3 = this.CurrentRequest.SendOutTo(this.Stream);
                        if (!flag3)
                        {
                            this.Close();
                            if (this.State == HTTPConnectionStates.TimedOut)
                            {
                                goto Block_13;
                            }
                            if (!flag)
                            {
                                flag        = true;
                                retryCauses = HTTPConnection.RetryCauses.Reconnect;
                            }
                        }
                        if (flag3)
                        {
                            bool flag4 = this.Receive();
                            if (this.State == HTTPConnectionStates.TimedOut)
                            {
                                goto Block_16;
                            }
                            if (!flag4 && !flag)
                            {
                                flag        = true;
                                retryCauses = HTTPConnection.RetryCauses.Reconnect;
                            }
                            if (this.CurrentRequest.Response != null)
                            {
                                int statusCode = this.CurrentRequest.Response.StatusCode;
                                switch (statusCode)
                                {
                                case 301:
                                case 302:
                                case 307:
                                case 308:
                                {
                                    if (this.CurrentRequest.RedirectCount >= this.CurrentRequest.MaxRedirects)
                                    {
                                        goto IL_3F7;
                                    }
                                    this.CurrentRequest.RedirectCount++;
                                    string firstHeaderValue = this.CurrentRequest.Response.GetFirstHeaderValue("location");
                                    if (string.IsNullOrEmpty(firstHeaderValue))
                                    {
                                        goto IL_3C9;
                                    }
                                    Uri redirectUri = this.GetRedirectUri(firstHeaderValue);
                                    if (!this.CurrentRequest.CallOnBeforeRedirection(redirectUri))
                                    {
                                        HTTPManager.Logger.Information("HTTPConnection", "OnBeforeRedirection returned False");
                                        goto IL_3F7;
                                    }
                                    this.CurrentRequest.RemoveHeader("Host");
                                    this.CurrentRequest.SetHeader("Referer", this.CurrentRequest.CurrentUri.ToString());
                                    this.CurrentRequest.RedirectUri = redirectUri;
                                    this.CurrentRequest.Response    = null;
                                    bool flag5 = true;
                                    this.CurrentRequest.IsRedirected = flag5;
                                    flag2 = flag5;
                                    goto IL_3F7;
                                }

                                case 303:
                                case 304:
                                case 305:
                                case 306:
IL_186:
                                    if (statusCode == 401)
                                    {
                                        string firstHeaderValue2 = this.CurrentRequest.Response.GetFirstHeaderValue("www-authenticate");
                                        if (!string.IsNullOrEmpty(firstHeaderValue2))
                                        {
                                            Digest orCreate = DigestStore.GetOrCreate(this.CurrentRequest.CurrentUri);
                                            orCreate.ParseChallange(firstHeaderValue2);
                                            if (this.CurrentRequest.Credentials != null && orCreate.IsUriProtected(this.CurrentRequest.CurrentUri) && (!this.CurrentRequest.HasHeader("Authorization") || orCreate.Stale))
                                            {
                                                retryCauses = HTTPConnection.RetryCauses.Authenticate;
                                            }
                                        }
                                        goto IL_3F7;
                                    }
                                    if (statusCode != 407)
                                    {
                                        goto IL_3F7;
                                    }
                                    if (this.CurrentRequest.HasProxy)
                                    {
                                        string firstHeaderValue3 = this.CurrentRequest.Response.GetFirstHeaderValue("proxy-authenticate");
                                        if (!string.IsNullOrEmpty(firstHeaderValue3))
                                        {
                                            Digest orCreate2 = DigestStore.GetOrCreate(this.CurrentRequest.Proxy.Address);
                                            orCreate2.ParseChallange(firstHeaderValue3);
                                            if (this.CurrentRequest.Proxy.Credentials != null && orCreate2.IsUriProtected(this.CurrentRequest.Proxy.Address) && (!this.CurrentRequest.HasHeader("Proxy-Authorization") || orCreate2.Stale))
                                            {
                                                retryCauses = HTTPConnection.RetryCauses.ProxyAuthenticate;
                                            }
                                        }
                                    }
                                    goto IL_3F7;
                                }
                                goto IL_186;
IL_3F7:
                                if (this.CurrentRequest.IsCookiesEnabled)
                                {
                                    CookieJar.Set(this.CurrentRequest.Response);
                                }
                                this.TryStoreInCache();
                                if (this.CurrentRequest.Response == null || this.CurrentRequest.Response.HasHeaderWithValue("connection", "close") || this.CurrentRequest.UseAlternateSSL)
                                {
                                    this.Close();
                                }
                            }
                        }
                        if (retryCauses == HTTPConnection.RetryCauses.None)
                        {
                            goto Block_37;
                        }
                    }
                    throw new Exception("AbortRequested");
Block_13:
                    throw new Exception("AbortRequested");
Block_16:
                    throw new Exception("AbortRequested");
IL_3C9:
                    throw new MissingFieldException(string.Format("Got redirect status({0}) without 'location' header!", this.CurrentRequest.Response.StatusCode.ToString()));
                    Block_37 :;
                }
            }
            catch (TimeoutException exception)
            {
                this.CurrentRequest.Response  = null;
                this.CurrentRequest.Exception = exception;
                this.CurrentRequest.State     = HTTPRequestStates.ConnectionTimedOut;
                this.Close();
            }
            catch (Exception exception2)
            {
                if (this.CurrentRequest != null)
                {
                    if (this.CurrentRequest.UseStreaming)
                    {
                        HTTPCacheService.DeleteEntity(this.CurrentRequest.CurrentUri, true);
                    }
                    this.CurrentRequest.Response = null;
                    HTTPConnectionStates state = this.State;
                    if (state != HTTPConnectionStates.AbortRequested)
                    {
                        if (state != HTTPConnectionStates.TimedOut)
                        {
                            this.CurrentRequest.Exception = exception2;
                            this.CurrentRequest.State     = HTTPRequestStates.Error;
                        }
                        else
                        {
                            this.CurrentRequest.State = HTTPRequestStates.TimedOut;
                        }
                    }
                    else
                    {
                        this.CurrentRequest.State = HTTPRequestStates.Aborted;
                    }
                }
                this.Close();
            }
            finally
            {
                if (this.CurrentRequest != null)
                {
                    object locker = HTTPManager.Locker;
                    lock (locker)
                    {
                        if (this.CurrentRequest != null && this.CurrentRequest.Response != null && this.CurrentRequest.Response.IsUpgraded)
                        {
                            this.State = HTTPConnectionStates.Upgraded;
                        }
                        else
                        {
                            this.State = ((!flag2) ? ((this.Client != null) ? HTTPConnectionStates.WaitForRecycle : HTTPConnectionStates.Closed) : HTTPConnectionStates.Redirected);
                        }
                        if (this.CurrentRequest.State == HTTPRequestStates.Processing && (this.State == HTTPConnectionStates.Closed || this.State == HTTPConnectionStates.WaitForRecycle))
                        {
                            this.CurrentRequest.State = HTTPRequestStates.Finished;
                        }
                        if (this.CurrentRequest.State == HTTPRequestStates.ConnectionTimedOut)
                        {
                            this.State = HTTPConnectionStates.Closed;
                        }
                        this.LastProcessTime = DateTime.UtcNow;
                    }
                    HTTPCacheService.SaveLibrary();
                    CookieJar.Persist();
                }
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Multicasts a new view.
        /// </summary>
        /// <param name="new_view">New View to send</param>
        /// <param name="digest">Digest associated with View</param>
        public void castViewChange(View new_view, Digest digest)
        {
            Message   view_change_msg;
            GmsHeader hdr;

            if(Trace.trace)
                Trace.info("GMS.castViewChange()", "mcasting view {" + new_view + "} (" + new_view.size() + " mbrs)\n");
            view_change_msg=new Message(null,null,null); // bcast to all members
            hdr=new GmsHeader(GmsHeader.VIEW, new_view);
            hdr.digest=digest;
            view_change_msg.putHeader(getName(), hdr);
            passDown(new Event(Event.MSG, view_change_msg));
        }
Esempio n. 24
0
 /// <summary>The encryption of a digest it the atomic operation done by the SSCD.</summary>
 /// <remarks>
 /// The encryption of a digest it the atomic operation done by the SSCD. This encryption (RSA, DSA, ...) create the
 /// signature value.
 /// </remarks>
 /// <param name="digest"></param>
 /// <param name="keyEntry"></param>
 /// <returns></returns>
 /// <exception cref="Sharpen.NoSuchAlgorithmException">Sharpen.NoSuchAlgorithmException
 ///     </exception>
 public virtual byte[] EncryptDigest(Digest digest, IDssPrivateKeyEntry keyEntry)
 {
     return(this.EncryptDigest(digest.GetValue(), digest.GetAlgorithm(), keyEntry));
 }
Esempio n. 25
0
 /// <summary>
 /// Send down a SET_DIGEST event 
 /// </summary>
 /// <param name="d">Digest to install</param>
 public void setDigest(Digest d)
 {
     passDown(new Event(Event.SET_DIGEST, d));
 }
Esempio n. 26
0
 public static Digest /*!*/ Reset(Digest /*!*/ self)
 {
     self._algorithm.Clear();
     return(self);
 }
Esempio n. 27
0
 public void SetUp()
 {
     PayLoad = string.Empty;
     HttpTransportMock = new Mock<IHttpTransport>();
     ResourceMock = new Mock<IResource>();
     Digest = new Digest();
     ResponseMock = new Mock<IHttpResponse>();
     ResponseMock.SetupGet(r => r.StatusCode).Returns(HttpStatusCode.OK);
     ResponseMock.Setup(r => r.Header("Location")).Returns(Url.OriginalString);
 }
Esempio n. 28
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="view">Current view of the group</param>
 /// <param name="digest">Current digest of the group</param>
 public JoinRsp(View view, Digest digest)
 {
     this.view=view;
     this.digest=digest;
 }
Esempio n. 29
0
        public void EnumerateHeaders(OnHeaderEnumerationDelegate callback)
        {
            if (!HasHeader("Host"))
            {
                SetHeader("Host", CurrentUri.Authority);
            }
            if (IsRedirected && !HasHeader("Referer"))
            {
                AddHeader("Referer", Uri.ToString());
            }
            if (!HasHeader("Accept-Encoding"))
            {
                AddHeader("Accept-Encoding", "gzip, identity");
            }
            if (HasProxy && !HasHeader("Proxy-Connection"))
            {
                AddHeader("Proxy-Connection", (!IsKeepAlive) ? "Close" : "Keep-Alive");
            }
            if (!HasHeader("Connection"))
            {
                AddHeader("Connection", (!IsKeepAlive) ? "Close, TE" : "Keep-Alive, TE");
            }
            if (!HasHeader("TE"))
            {
                AddHeader("TE", "identity");
            }
            if (!HasHeader("User-Agent"))
            {
                AddHeader("User-Agent", "VRC.Core.BestHTTP");
            }
            long num = -1L;

            if (UploadStream == null)
            {
                byte[] entityBody = GetEntityBody();
                num = ((entityBody != null) ? entityBody.Length : 0);
                if (RawData == null && (FormImpl != null || (FieldCollector != null && !FieldCollector.IsEmpty)))
                {
                    SelectFormImplementation();
                    if (FormImpl != null)
                    {
                        FormImpl.PrepareRequest(this);
                    }
                }
            }
            else
            {
                num = UploadStreamLength;
                if (num == -1)
                {
                    SetHeader("Transfer-Encoding", "Chunked");
                }
                if (!HasHeader("Content-Type"))
                {
                    SetHeader("Content-Type", "application/octet-stream");
                }
            }
            if (num != -1 && !HasHeader("Content-Length"))
            {
                SetHeader("Content-Length", num.ToString());
            }
            if (HasProxy && Proxy.Credentials != null)
            {
                switch (Proxy.Credentials.Type)
                {
                case AuthenticationTypes.Basic:
                    SetHeader("Proxy-Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Proxy.Credentials.UserName + ":" + Proxy.Credentials.Password)));
                    break;

                case AuthenticationTypes.Unknown:
                case AuthenticationTypes.Digest:
                {
                    Digest digest = DigestStore.Get(Proxy.Address);
                    if (digest != null)
                    {
                        string value = digest.GenerateResponseHeader(this, Proxy.Credentials);
                        if (!string.IsNullOrEmpty(value))
                        {
                            SetHeader("Proxy-Authorization", value);
                        }
                    }
                    break;
                }
                }
            }
            if (Credentials != null)
            {
                switch (Credentials.Type)
                {
                case AuthenticationTypes.Basic:
                    SetHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Credentials.UserName + ":" + Credentials.Password)));
                    break;

                case AuthenticationTypes.Unknown:
                case AuthenticationTypes.Digest:
                {
                    Digest digest2 = DigestStore.Get(CurrentUri);
                    if (digest2 != null)
                    {
                        string value2 = digest2.GenerateResponseHeader(this, Credentials);
                        if (!string.IsNullOrEmpty(value2))
                        {
                            SetHeader("Authorization", value2);
                        }
                    }
                    break;
                }
                }
            }
            List <Cookie> list = (!IsCookiesEnabled) ? null : CookieJar.Get(CurrentUri);

            if (list == null || list.Count == 0)
            {
                list = customCookies;
            }
            else if (customCookies != null)
            {
                for (int i = 0; i < customCookies.Count; i++)
                {
                    Cookie customCookie = customCookies[i];
                    int    num2         = list.FindIndex((Cookie c) => c.Name.Equals(customCookie.Name));
                    if (num2 >= 0)
                    {
                        list[num2] = customCookie;
                    }
                    else
                    {
                        list.Add(customCookie);
                    }
                }
            }
            if (list != null && list.Count > 0)
            {
                bool               flag            = true;
                string             text            = string.Empty;
                bool               flag2           = HTTPProtocolFactory.IsSecureProtocol(CurrentUri);
                SupportedProtocols protocolFromUri = HTTPProtocolFactory.GetProtocolFromUri(CurrentUri);
                foreach (Cookie item in list)
                {
                    if ((!item.IsSecure || (item.IsSecure && flag2)) && (!item.IsHttpOnly || (item.IsHttpOnly && protocolFromUri == SupportedProtocols.HTTP)))
                    {
                        if (!flag)
                        {
                            text += "; ";
                        }
                        else
                        {
                            flag = false;
                        }
                        text           += item.ToString();
                        item.LastAccess = DateTime.UtcNow;
                    }
                }
                SetHeader("Cookie", text);
            }
            if (callback != null)
            {
                foreach (KeyValuePair <string, List <string> > header in Headers)
                {
                    callback(header.Key, header.Value);
                }
            }
        }
Esempio n. 30
0
        public JMMUser AuthenticateUser(string userName, string password)
        {
            string hashedPassword = Digest.Hash(password);

            return(Cache.Values.FirstOrDefault(a => a.Username == userName && a.Password == hashedPassword));
        }
Esempio n. 31
0
 public static int Seed(Digest /*!*/ self)
 {
     return(self._algorithm.OutputBlockSize);
 }
Esempio n. 32
0
        public override IEnumerable <string> Process(string filename)
        {
            FastaFormat ff     = new FastaFormat();
            Digest      digest = new Digest();

            digest.DigestProtease     = ProteaseManager.FindOrCreateProtease("Trypsin", true, "RK", "P");
            digest.MaxMissedCleavages = 1;

            NGlycanFilter filter = new NGlycanFilter();

            digest.Filter = filter;

            string resultFile = filename + ".nglycan";
            Dictionary <string, NGlycanValue> peptideProteinMap = new Dictionary <string, NGlycanValue>();

            using (StreamReader sr = new StreamReader(filename))
            {
                Sequence seq;
                while ((seq = ff.ReadSequence(sr)) != null)
                {
                    digest.ProteinSequence = seq;
                    digest.AddDigestFeatures();

                    if (seq.Annotation.ContainsKey(Digest.PEPTIDE_FEATURE_TYPE))
                    {
                        bool[] isGlycans = filter.IsNglycan;

                        List <DigestPeptideInfo> nglycanPeptides = (List <DigestPeptideInfo>)seq.Annotation[Digest.PEPTIDE_FEATURE_TYPE];
                        foreach (DigestPeptideInfo dpi in nglycanPeptides)
                        {
                            if (!peptideProteinMap.ContainsKey(dpi.PeptideSeq))
                            {
                                StringBuilder sb = new StringBuilder();
                                for (int i = 0; i < dpi.PeptideSeq.Length; i++)
                                {
                                    if (isGlycans[dpi.PeptideLoc.Min - 1 + i])
                                    {
                                        sb.Append(1);
                                    }
                                    else
                                    {
                                        sb.Append(0);
                                    }
                                }

                                NGlycanValue value = new NGlycanValue();
                                value.NGlycanSites = sb.ToString();

                                peptideProteinMap[dpi.PeptideSeq] = value;
                            }

                            peptideProteinMap[dpi.PeptideSeq].Proteins.Add(parser.GetValue(dpi.ProteinName));
                        }
                    }
                }
            }

            List <string> peptides = new List <string>(peptideProteinMap.Keys);

            peptides.Sort();

            using (StreamWriter sw = new StreamWriter(resultFile))
            {
                foreach (string pep in peptides)
                {
                    NGlycanValue value = peptideProteinMap[pep];
                    sw.Write(pep + "\t" + value.NGlycanSites + "\t");
                    bool bFirst = true;
                    foreach (string protein in value.Proteins)
                    {
                        if (bFirst)
                        {
                            bFirst = false;
                            sw.Write(protein);
                        }
                        else
                        {
                            sw.Write(" ! " + protein);
                        }
                    }
                    sw.WriteLine();
                }
            }

            return(new[] { resultFile });
        }
Esempio n. 33
0
        static void Main()
        {
            string rootFolder = Directory.GetCurrentDirectory();

            Directory.SetCurrentDirectory(coreFolder);

            Console.WriteLine("Refreshing inputs");
            Modules plugins = new Modules();

            plugins.Add(new ModuleVox2Gly(coreFolder));
            plugins.Add(new ModuleDigest(digestOutputPath, DownSolver.enables.DoRects));
            //plugins.Add(new ModuleGenesis("megagrid.json"));

            plugins.Run();

            Directory.SetCurrentDirectory(rootFolder);

            Console.WriteLine("Restful Glyphic Server");
            Console.WriteLine("Enabling file change tracking");
            FileChangeTracker.Run(coreFolder, "*.glyc");

            string webfolder = @"C:\Github\Glyphics2\Site\";

            WebResponder.responseHandlers.Add("ping", new WebHandler_ping());
            WebResponder.responseHandlers.Add("api/id2name", new WebHandler_id2name());
            WebResponder.responseHandlers.Add("api/code2srects", new WebHandler_code2srects());
            WebResponder.responseHandlers.Add("api/simulation", new WebHandler_simulation());
            WebResponder.responseHandlers.Add("api/digest", new WebHandler_digest());
            WebResponder.responseHandlers.Add("api/srects", new WebHandler_srects());
            WebResponder.responseHandlers.Add("api/megagrid", new WebHandler_megagrid());
            WebResponder.responseHandlers.Add("api/code", new WebHandler_code());
            WebResponder.responseHandlers.Add("api/user", new WebHandler_user());
            WebResponder.responseHandlers.Add("api/users", new WebHandler_users());
            WebResponder.responseHandlers.Add("api/useradd", new WebHandler_useradd());
            WebResponder.responseHandlers.Add("api/userdel", new WebHandler_userdel());
            WebResponder.responseHandlers.Add("api/grid", new WebHandler_grid());
            //WebResponder.responseHandlers.Add("/api/srects2html", new WebHandler_srects2html());
            //WebResponder.responseHandlers.Add("/api/srects2json", new WebHandler_srects2json());

            //Only have to simulate one thing at a time?
            var file = new StreamReader(webfolder + "\\Digest\\digest.json");

            digest = JsonConvert.DeserializeObject <Digest>(file.ReadToEnd());

            /*file = new StreamReader(megagrid_name);
             * gridspace.grids = JsonConvert.DeserializeObject<Dictionary<string, string>>(file.ReadToEnd());
             * file.Close();
             * simulations = new Simulations(gridspace.grids, digest);
             */
            users.ReadFromFile(webfolder + "users.json");

            //create server with auto assigned port
            SimpleHttpServer myServer = new SimpleHttpServer(webfolder, 3838);

            if (myServer != null)
            {
                while (true)
                {
                    //simulations.Simulate();
                    Thread.Sleep(500);
                }
            }
        }
Esempio n. 34
0
 private void SendHeaders(BinaryWriter stream)
 {
     SetHeader("Host", CurrentUri.Host);
     if (IsRedirected && !HasHeader("Referer"))
     {
         AddHeader("Referer", Uri.ToString());
     }
     if (!HasHeader("Accept-Encoding"))
     {
         AddHeader("Accept-Encoding", "gzip, deflate, identity");
     }
     if (!HasHeader("Connection"))
     {
         AddHeader("Connection", (!IsKeepAlive) ? "Close, TE" : "Keep-Alive, TE");
     }
     if (!HasHeader("TE"))
     {
         AddHeader("TE", "chunked, identity");
     }
     byte[] entityBody = GetEntityBody();
     int num = (entityBody != null) ? entityBody.Length : 0;
     if (RawData == null)
     {
         byte[] array = ((object)FieldsImpl == null) ? null : FieldsImpl.get_data();
         if (array != null && array.Length > 0 && !HasHeader("Content-Type"))
         {
             AddHeader("Content-Type", "application/x-www-form-urlencoded");
         }
     }
     if (!HasHeader("Content-Length") && num != 0)
     {
         AddHeader("Content-Length", num.ToString());
     }
     if (Credentials != null)
     {
         switch (Credentials.Type)
         {
         case AuthenticationTypes.Basic:
             SetHeader("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Credentials.UserName + ":" + Credentials.Password)));
             break;
         case AuthenticationTypes.Unknown:
         case AuthenticationTypes.Digest:
         {
             Digest digest = DigestStore.Get(CurrentUri);
             if (digest != null)
             {
                 string value = digest.GenerateResponseHeader(this);
                 if (!string.IsNullOrEmpty(value))
                 {
                     SetHeader("Authorization", value);
                 }
             }
             break;
         }
         }
     }
     foreach (KeyValuePair<string, List<string>> header in Headers)
     {
         byte[] aSCIIBytes = (header.Key + ": ").GetASCIIBytes();
         for (int i = 0; i < header.Value.Count; i++)
         {
             stream.Write(aSCIIBytes);
             stream.Write(header.Value[i].GetASCIIBytes());
             stream.Write(EOL);
         }
     }
 }
Esempio n. 35
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            StringBuilder log = new StringBuilder();

            log.Append(DateTime.Now.ToString() + "\n");
            log.Append("测试功能:" + theme.InnerText + "\n");


            //***********************修改内容****************************

            string requestUrl = APIURLConfig.QueryableOrder;

            string[] list          = { "p0_Cmd", "p1_MerId", "pb_TrxId", "pv_Ver" };
            string[] list_response = { "r0_Cmd",
                                       "r1_Code" };

            //***********************************************************


            log.Append("请求地址:" + requestUrl + "\n");
            log.Append("商户编号:" + p1_MerId.Value + "\n");
            log.Append("商户密钥:" + CustomerConfig.merchantKey + "\n");

            //存储前台数据
            string data_hmac = "";

            //循环生成
            foreach (string listname in list)
            {
                if (Request[listname] != "")
                {
                    data_hmac = data_hmac + Request[listname];
                }
            }

            //生成hmac签名
            string hmac = Digest.CreateHmac(data_hmac);

            log.Append("请求加密的字符串:" + data_hmac + "\n");
            log.Append("请求hmac:" + hmac + "\n");

            //循环生成要请求链接的数据
            string data_request = "";

            foreach (string listname in list)
            {
                data_request = data_request + listname + "=" + Request[listname] + "&";
            }
            //最终字符串
            data_request = data_request + "hmac=" + hmac;

            log.Append("请求链接:" + requestUrl + "?" + data_request + "\n");

            //发出请求
            string reqResult = YJPayUtil.payAPIRequestOnlince(requestUrl, data_request, true);

            log.Append("返回的原始信息:" + reqResult + "\n");

            //存储响应信息
            SortedDictionary <string, string> sd = new SortedDictionary <string, string>();

            //循环存储response
            foreach (string listname in list_response)
            {
                sd.Add(listname, FormatQueryString.GetQueryString(listname, reqResult, '\n'));
            }
            sd.Add("hmac", FormatQueryString.GetQueryString("hmac", reqResult, '\n'));


            string response_json = Newtonsoft.Json.JsonConvert.SerializeObject(sd);

            string type = "";

            if (sd["r1_Code"] == "1")
            {
                //回调验证签名
                string response_data = "";

                //循环生成
                foreach (string listname in list_response)
                {
                    response_data = response_data + sd[listname];
                }

                //回调信息生成HMAC
                string hmac_location = Digest.CreateHmac(response_data);


                //验证签名
                StringComparer comparer = StringComparer.OrdinalIgnoreCase;
                if (0 == comparer.Compare(hmac_location, sd["hmac"]))
                {
                    type = "验证签名成功";
                }
                else
                {
                    type = "验证签名失败";
                }
            }
            else
            {
                type = "请检查数据";
            }

            //返回数据data
            string data = response_json.ToString();



            SoftLog.LogStr(log.ToString(), theme.InnerText);

            //跳转页面
            Response.Redirect("http://localhost:58903/CallBack.aspx?data=" + data + "&type=" + type);
        }
Esempio n. 36
0
 public string GetDigestedPassword(string plain, string salt)
 {
     return(Digest.SHA256Of(plain + salt));
 }
Esempio n. 37
0
        /**
         * fill len bytes of the output buffer with bytes generated from the
         * derivation function.
         *
         * @throws IllegalArgumentException
         *             if the size of the request will cause an overflow.
         * @throws DataLengthException
         *             if the out buffer is too small.
         */
        public int GenerateBytes(byte[] output, int outOff, int length)
        {
            if (output.Length - length < outOff)
            {
                throw new DataLengthException("output buffer too small");
            }

            long oBytes = length;
            int  outLen = Digest.GetDigestSize();

            //
            // this is at odds with the standard implementation, the
            // maximum value should be hBits * (2^32 - 1) where hBits
            // is the digest output size in bits. We can't have an
            // array with a long index at the moment...
            //
            if (oBytes > (2L << 32) - 1)
            {
                throw new ArgumentException("Output length too large");
            }

            int cThreshold = (int)((oBytes + outLen - 1) / outLen);

            byte[] digest = new byte[Digest.GetDigestSize()];

//            byte[] C = new byte[4];
//            Pack.intToBigEndian(counterStart, C, 0);
            byte[] c = _counterStart.ToBigEndianByteArray();
            Debug.Assert(c.Length == 4, "need to be 4 bytes long");

            int counterBase = _counterStart & ~0xFF;

            for (int i = 0; i < cThreshold; i++)
            {
                Digest.BlockUpdate(c, 0, c.Length);
                Digest.BlockUpdate(_shared, 0, _shared.Length);

                if (_iv != null)
                {
                    Digest.BlockUpdate(_iv, 0, _iv.Length);
                }

                Digest.DoFinal(digest, 0);

                if (length > outLen)
                {
                    Array.Copy(digest, 0, output, outOff, outLen);
                    outOff += outLen;
                    length -= outLen;
                }
                else
                {
                    Array.Copy(digest, 0, output, outOff, length);
                }

                if (++c[3] == 0)
                {
                    counterBase += 0x100;
//                    Pack.intToBigEndian(counterBase, C, 0);
                    c = counterBase.ToBigEndianByteArray();
                    Debug.Assert(c.Length == 4, "need to be 4 bytes long");
                }
            }

            Digest.Reset();

            return((int)oBytes);
        }
Esempio n. 38
0
        /// <summary>
        /// 海关支付报关查询
        /// </summary>
        /// <param name="orderId">订单编号</param>
        /// <returns></returns>
        /// <remarks>2015-12-31 杨浩 创建</remarks
        public override Result CustomsQuery(int orderId)
        {
            Result result = new Result()
            {
                Status = false
            };

            var order = BLL.Order.SoOrderBo.Instance.GetEntity(orderId);

            var ehkingMerchantId = config.EhkingMerhantId;
            var ehkingKey        = config.EhkingKey;

            var warehouse = BLL.Warehouse.WhWarehouseBo.Instance.GetWarehouse(order.DefaultWarehouseSysNo);

            if (warehouse != null && warehouse.WarehouseType == (int)Model.WorkflowStatus.WarehouseStatus.仓库类型.门店)
            {
                var dealer = BLL.Stores.StoresBo.Instance.GetStoreByWarehouseId(warehouse.SysNo);
                if (dealer != null)
                {
                    var dealerPayType = BLL.Stores.StoresBo.Instance.GetStorePayType(dealer.SysNo);
                    if (!string.IsNullOrWhiteSpace(dealerPayType.AppKey) && !string.IsNullOrWhiteSpace(dealerPayType.AppSecret) && dealerPayType.PaymentTypeSysNo == (int)Model.CommonEnum.PayCode.易宝)
                    {
                        ehkingMerchantId = dealerPayType.AppKey;
                        ehkingKey        = dealerPayType.AppSecret;
                    }
                }
            }

            var onlinePaymentFilter = new ParaOnlinePaymentFilter()
            {
                OrderSysNo = orderId,
                Id         = 1
            };
            var onlinePayments = Hyt.BLL.Finance.FinanceBo.Instance.GetOnlinePayments(onlinePaymentFilter).Rows;

            if (onlinePayments.Count() <= 0)
            {
                result.Status  = false;
                result.Message = "订单没有支付信息!";
            }
            else
            {
                string responsestr = "";
                string data        = "";
                try
                {
                    string     serialNumber = onlinePayments.First().VoucherNo;
                    string     url          = "https://api.ehking.com/customs/query";//查询网关
                    string     hmac         = Digest.HmacSign(ehkingMerchantId + serialNumber, ehkingKey);
                    HttpClient client       = new HttpClient(url);
                    data        = "{\"merchantId\":\"" + ehkingMerchantId + "\",\"paySerialNumber\":\"" + serialNumber + "\",\"hmac\":\"" + hmac + "\"}";
                    responsestr = client.Post(data);

                    var back                  = JObject.Parse(responsestr);
                    var customsInfos          = back.Property("customsInfos") != null ? back["customsInfos"][0] : back;
                    OrderStatus.支付报关状态 status = OrderStatus.支付报关状态.失败;
                    if (customsInfos["status"].ToString() == "SUCCESS")
                    {
                        result.Message = "SUCCESS";
                        result.Status  = true;
                        status         = OrderStatus.支付报关状态.成功;
                    }
                    else if ("PROCESSING" == customsInfos["status"].ToString())
                    {
                        result.Message = "海关正在审核...,稍后再查询!";
                        status         = OrderStatus.支付报关状态.处理中;
                    }
                    else
                    {
                        //BLL.Log.LocalLogBo.Instance.Write("失败!" + responsestr, "CustomsQueryLog");
                        result.Message = "易宝返回状态:" + customsInfos["status"].ToString() + "(" + (back.Property("customsInfos") == null?customsInfos["error"].ToString():"") + ")";
                    }


                    Hyt.BLL.Order.SoOrderBo.Instance.UpdateOrderApiStatus((int)status, 0, orderId);
                }
                catch (Exception ex)
                {
                    result.Status  = false;
                    result.Message = "系统异常!";
                    BLL.Log.LocalLogBo.Instance.Write("\r\n报错!" + ex.Message + ";responsestr=" + responsestr + ";data=" + data, "CustomsQuery");
                }
            }

            return(result);
        }
Esempio n. 39
0
        /// <remarks>
        /// Called by <c>Join()</c> when no initial members can be detected
        /// </remarks>
        /// <summary>
        /// Changes the GMS to a Coord implementation
        /// </summary>
        /// <param name="mbr">Local Address representing this Channel</param>
        private void becomeSingletonMember(Address mbr)
        {
            Digest		initial_digest;
            ViewId		view_id=null;
            ArrayList   mbrs=new ArrayList();

            // set the initial digest (since I'm the first member)
            initial_digest = new Digest(1);             // 1 member (it's only me)
            initial_digest.add(gms.local_addr, 0, 0); // initial seqno mcast by me will be 1 (highest seen +1)
            gms.setDigest(initial_digest);

            view_id=new ViewId(mbr);       // create singleton view with mbr as only member
            mbrs.Add(mbr);
            gms.installView(new View(view_id, mbrs));
            gms.becomeCoordinator();

            gms.passUp(new Event(Event.BECOME_SERVER));
            gms.passDown(new Event(Event.BECOME_SERVER));
            if(Trace.trace) Trace.info("ClientGmsImpl.becomeSingletonMember()",
                                "created group (first member). My view is " + gms.view_id +
                                ", impl is " + gms.getImpl().getName());
        }
Esempio n. 40
0
        /// <summary>
        /// 广州电子口岸海关申报
        /// </summary>
        /// <returns></returns>
        public override Result ApplyToCustomsDZ30(SoOrder order)
        {
            var result = base.ApplyToCustomsDZ30(order);

            try
            {
                if (order != null)
                {
                    var    ehkingMerchantId           = config.EhkingMerhantId;
                    var    ehkingKey                  = config.EhkingKey;
                    string EhkingNodeAuthorizationUrl = "https://api.ehking.com/customs/order";
                    string EhkingCustomsAsyncUrl      = "http://admin.gaopin999.com/Account/NotifyReceiptDZ30";

                    var warehouse = BLL.Warehouse.WhWarehouseBo.Instance.GetWarehouse(order.DefaultWarehouseSysNo);
                    if (warehouse != null && warehouse.WarehouseType == (int)Model.WorkflowStatus.WarehouseStatus.仓库类型.门店)
                    {
                        var dealer = BLL.Stores.StoresBo.Instance.GetStoreByWarehouseId(warehouse.SysNo);
                        if (dealer != null)
                        {
                            var dealerPayType = BLL.Stores.StoresBo.Instance.GetStorePayType(dealer.SysNo);
                            if (!string.IsNullOrWhiteSpace(dealerPayType.AppKey) && !string.IsNullOrWhiteSpace(dealerPayType.AppSecret) && dealerPayType.PaymentTypeSysNo == (int)Model.CommonEnum.PayCode.易宝)
                            {
                                ehkingMerchantId = dealerPayType.AppKey;
                                ehkingKey        = dealerPayType.AppSecret;
                            }
                        }
                    }

                    var onlinePaymentFilter = new ParaOnlinePaymentFilter()
                    {
                        OrderSysNo = order.SysNo,
                        Id         = 1
                    };

                    var onlinePayments = Hyt.BLL.Finance.FinanceBo.Instance.GetOnlinePayments(onlinePaymentFilter).Rows;

                    var receiveAddress = Hyt.BLL.Order.SoOrderBo.Instance.GetOrderReceiveAddress(order.ReceiveAddressSysNo);

                    string nodeAuthorizationURL = EhkingNodeAuthorizationUrl;       //请求地址
                    string merchantId           = ehkingMerchantId;                 //商户编号
                    string keyValue             = ehkingKey;                        //商户密钥
                    string customsChannels      = "GUANGZHOUSP";                    //报关通道:GUANGZHOUSP(广州公共服务)
                    string serialNumber         = onlinePayments.First().VoucherNo; //支付流水号
                    string notifyUrl            = EhkingCustomsAsyncUrl;            //异步回调
                    string amount               = "0";                              //报关金额
                    string Freight              = "0";                              //运费
                    string GoodsAmount          = "0";                              //支付货款
                    string Tax                  = "0";                              //税费
                    string insuredAmount        = "0";                              //保费
                    string merchantCommerceName = "广州鼎球生物科技有限公司";                   //企业备案名称
                    string merchantCommerceCode = "C011111100393744";               //企业在海关的备案号
                    string storeHouse           = "";                               //商品所在仓
                    string customsCode          = "5141";                           //广州机场    5141;南沙旅检    5165;南沙货港    5167;番禺东发    5169;广州邮办    5145;黄埔开发区  5208;太平海关驻沙田办事处  5216;广州萝岗    5130;佛山海关快件监管现场  5185
                    string ciqCode              = "442300";                         //机场的国检组织机构代码是:000067;黄埔开发区的组织机构代码:000077,黄埔状元谷组织机构代码:443433
                    string functionCode         = "BC";                             //单向海关-CUS,单向国检-CIQ,同时发送-BC
                    string businessType         = "B2C";                            //B2B2C,B2C

                    StringBuilder sbHmac = new StringBuilder();

                    sbHmac.Append(merchantId);
                    sbHmac.Append(serialNumber);
                    sbHmac.Append(notifyUrl);

                    amount      = (order.CashPay * 100).ToString("F0");
                    Freight     = (order.FreightAmount * 100).ToString("F0");
                    GoodsAmount = (order.ProductAmount * 100).ToString("F0");
                    Tax         = (order.TaxFee * 100).ToString("F0");

                    sbHmac.Append(receiveAddress.Name);
                    sbHmac.Append(receiveAddress.IDCardNo);
                    sbHmac.Append(receiveAddress.MobilePhoneNumber);

                    sbHmac.Append(customsChannels);
                    sbHmac.Append(amount);
                    sbHmac.Append(Freight);
                    sbHmac.Append(GoodsAmount);
                    sbHmac.Append(Tax);
                    sbHmac.Append(insuredAmount);
                    sbHmac.Append(merchantCommerceName);
                    sbHmac.Append(merchantCommerceCode);
                    sbHmac.Append(storeHouse);
                    sbHmac.Append(customsCode);
                    sbHmac.Append(ciqCode);
                    sbHmac.Append(functionCode);
                    sbHmac.Append(businessType);


                    string hmac = Digest.HmacSign(sbHmac.ToString(), keyValue);

                    HttpClient client = new HttpClient(nodeAuthorizationURL);

                    string data = "{\"merchantId\":\"" + merchantId +
                                  "\",\"paySerialNumber\":\"" + serialNumber +
                                  "\",\"notifyUrl\":\"" + notifyUrl + "\"" +
                                  ",\"payer\": {" +
                                  "\"payerName\": \"" + receiveAddress.Name + "\"," +
                                  "\"idNum\": \"" + receiveAddress.IDCardNo + "\"," +
                                  "\"phoneNum\": \"" + receiveAddress.MobilePhoneNumber + "\"" +
                                  "}" +
                                  ",\"customsInfos\":[{\"customsChannel\":\"" + customsChannels +
                                  "\",\"amount\":\"" + amount +
                                  "\",\"freight\":\"" + Freight +
                                  "\",\"goodsAmount\":\"" + GoodsAmount +
                                  "\",\"tax\":\"" + Tax +
                                  "\",\"insuredAmount\":\"" + insuredAmount +
                                  "\",\"merchantCommerceName\":\"" + merchantCommerceName +
                                  "\",\"merchantCommerceCode\":\"" + merchantCommerceCode +
                                  "\",\"storeHouse\":\"" + storeHouse +
                                  "\",\"customsCode\":\"" + customsCode +
                                  "\",\"ciqCode\":\"" + ciqCode +
                                  "\",\"functionCode\":\"" + functionCode +
                                  "\",\"businessType\":\"" + businessType +
                                  "\"}],\"hmac\":\"" + hmac + "\"}";



                    string responsestr = client.Post(data);

                    BLL.Log.LocalLogBo.Instance.Write("提交的数据:" + data + ",------返回数据:" + responsestr, "EhkingCustomsDZ30Log");

                    var back = JObject.Parse(responsestr);

                    if (back["status"].ToString() == "SUCCESS")
                    {
                        result.Message = "提交成功!";
                        result.Status  = true;
                        //更新订单支付报关状态为处理中
                        Hyt.BLL.Order.SoOrderBo.Instance.UpdateOrderApiStatus((int)OrderStatus.支付报关状态.处理中, 0, order.SysNo);
                        BLL.Log.SysLog.Instance.Info(LogStatus.系统日志来源.前台, "订单编号:" + order.SysNo + ",支付信息报关提交成功!", LogStatus.系统日志目标类型.订单支付报关, order.SysNo, 0);
                    }
                    else if (back["status"].ToString() == "FAILED")
                    {
                        result.Message = "提交失败!";
                        result.Status  = false;
                        BLL.Log.LocalLogBo.Instance.Write("提交失败!" + responsestr, "EhkingCustomsDZ30Log");
                    }
                    else if (back["status"].ToString() == "ERROR")
                    {
                        if (back["error"].ToString() == "exception.record.exists.customsOrder")//已提交则设置状态为待处理
                        {
                            //result.Message = "此订单已提交,请查询!";
                            //Hyt.BLL.Order.SoOrderBo.Instance.UpdateOrderApiStatus((int)OrderStatus.支付报关状态.处理中, 0, order.SysNo);
                            result = CustomsQuery(order.SysNo);
                            return(result);
                        }
                        else
                        {
                            result.Message = "提交失败,错误代码:" + back["error"].ToString();
                        }

                        BLL.Log.LocalLogBo.Instance.Write("提交失败!" + responsestr, "EhkingCustomsDZ30ERRORLog");
                        result.Status = false;
                    }
                    else
                    {
                        result.Message = "其他异常!";
                        result.Status  = false;
                        BLL.Log.LocalLogBo.Instance.Write("其他异常!" + responsestr, "EhkingCustomsDZ30Log");
                    }
                }
            }
            catch (Exception ex)
            {
                result.Message = "报错!";
                result.Status  = false;
                BLL.Log.LocalLogBo.Instance.Write("报错!" + ex.Message, "EhkingCustomsDZ30Log");
            }
            return(result);
        }
Esempio n. 41
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="type">Header type</param>
 /// <param name="digest">Stable or unstable digest</param>
 public StableHeader(int type, Digest digest)
 {
     this.type=type;
     this.digest=digest;
 }
Esempio n. 42
0
        /// <summary>
        /// 海关报关
        /// </summary>
        /// <returns></returns>
        /// <remarks>2015-10-12 杨浩 创建</remarks>
        public override Result ApplyToCustoms(SoOrder order)
        {
            Result result = new Result()
            {
                Status = false
            };

            try
            {
                if (order != null)
                {
                    var ehkingMerchantId = config.EhkingMerhantId;
                    var ehkingKey        = config.EhkingKey;

                    var warehouse = BLL.Warehouse.WhWarehouseBo.Instance.GetWarehouse(order.DefaultWarehouseSysNo);
                    if (warehouse != null && warehouse.WarehouseType == (int)Model.WorkflowStatus.WarehouseStatus.仓库类型.门店)
                    {
                        var dealer = BLL.Stores.StoresBo.Instance.GetStoreByWarehouseId(warehouse.SysNo);
                        if (dealer != null)
                        {
                            var dealerPayType = BLL.Stores.StoresBo.Instance.GetStorePayType(dealer.SysNo);
                            if (!string.IsNullOrWhiteSpace(dealerPayType.AppKey) && !string.IsNullOrWhiteSpace(dealerPayType.AppSecret) && dealerPayType.PaymentTypeSysNo == (int)Model.CommonEnum.PayCode.易宝)
                            {
                                ehkingMerchantId = dealerPayType.AppKey;
                                ehkingKey        = dealerPayType.AppSecret;
                            }
                        }
                    }

                    var onlinePaymentFilter = new ParaOnlinePaymentFilter()
                    {
                        OrderSysNo = order.SysNo,
                        Id         = 1
                    };

                    var onlinePayments = Hyt.BLL.Finance.FinanceBo.Instance.GetOnlinePayments(onlinePaymentFilter).Rows;

                    var receiveAddress = Hyt.BLL.Order.SoOrderBo.Instance.GetOrderReceiveAddress(order.ReceiveAddressSysNo);

                    string nodeAuthorizationURL = config.EhkingNodeAuthorizationUrl;
                    string merchantId           = ehkingMerchantId;
                    string keyValue             = ehkingKey;
                    string serialNumber         = onlinePayments.First().VoucherNo;
                    string notifyUrl            = "http://admin.singingwhale.cn/ajax/notifyReceipt";// config.EhkingCustomsAsyncUrl;
                    string amount      = "0";
                    string Freight     = "0";
                    string GoodsAmount = "0";
                    string Tax         = "0";
                    //var customsConfig = Hyt.BLL.Config.Config.Instance.GetCustomsConfig();
                    string dxpid = "DXPENT0000012770";

                    //if(!string.IsNullOrEmpty(customsConfig.DxpId))
                    //    dxpid = customsConfig.DxpId;


                    StringBuilder sbHmac = new StringBuilder();

                    sbHmac.Append(merchantId);
                    sbHmac.Append(serialNumber);
                    sbHmac.Append(notifyUrl);

                    amount      = (order.CashPay * 100).ToString("F0");
                    Freight     = (order.FreightAmount * 100).ToString("F0");
                    GoodsAmount = (order.ProductAmount * 100).ToString("F0");
                    Tax         = (order.TaxFee * 100).ToString("F0");

                    sbHmac.Append(receiveAddress.Name);
                    sbHmac.Append(receiveAddress.IDCardNo);
                    sbHmac.Append(receiveAddress.MobilePhoneNumber);

                    sbHmac.Append(CustomsChannel);
                    sbHmac.Append(amount);
                    sbHmac.Append(Freight);
                    sbHmac.Append(GoodsAmount);
                    sbHmac.Append(Tax);
                    sbHmac.Append(dxpid);


                    string hmac = Digest.HmacSign(sbHmac.ToString(), keyValue);

                    HttpClient client = new HttpClient(nodeAuthorizationURL);

                    string data = "{\"merchantId\":\"" + merchantId +
                                  "\",\"paySerialNumber\":\"" + serialNumber +
                                  "\",\"notifyUrl\":\"" + notifyUrl + "\"" +
                                  ",\"payer\": {" +
                                  "\"payerName\": \"" + receiveAddress.Name + "\"," +
                                  "\"idNum\": \"" + receiveAddress.IDCardNo + "\"," +
                                  "\"phoneNum\": \"" + receiveAddress.MobilePhoneNumber + "\"" +
                                  "}" +
                                  ",\"customsInfos\":[{\"customsChannel\":\"" + CustomsChannel +
                                  "\",\"amount\":\"" + amount +
                                  "\",\"freight\":\"" + Freight +
                                  "\",\"goodsAmount\":\"" + GoodsAmount +
                                  "\",\"tax\":\"" + Tax + "\",\"dxpid\":\"" + dxpid + "\"}],\"hmac\":\"" + hmac + "\"}";


                    BLL.Log.LocalLogBo.Instance.Write("提交的数据:" + data, "EhkingCustomsLog");

                    string responsestr = client.Post(data);

                    var back = JObject.Parse(responsestr);

                    if (back["status"].ToString() == "SUCCESS")
                    {
                        result.Message = "提交成功!";
                        result.Status  = true;
                        //更新订单支付报关状态为处理中
                        Hyt.BLL.Order.SoOrderBo.Instance.UpdateOrderApiStatus((int)OrderStatus.支付报关状态.处理中, 0, order.SysNo);
                        BLL.Log.SysLog.Instance.Info(LogStatus.系统日志来源.前台, "订单编号:" + order.SysNo + ",支付信息报关提交成功!", LogStatus.系统日志目标类型.订单支付报关, order.SysNo, 0);
                    }
                    else if (back["status"].ToString() == "FAILED")
                    {
                        result.Message = "提交失败!";
                        result.Status  = false;
                        BLL.Log.LocalLogBo.Instance.Write("提交失败!" + responsestr, "EhkingCustomsLog");
                    }
                    else if (back["status"].ToString() == "ERROR")
                    {
                        if (back["error"].ToString() == "exception.record.exists.customsOrder")//已提交则设置状态为待处理
                        {
                            result.Message = "此订单已提交,请查询!";
                            Hyt.BLL.Order.SoOrderBo.Instance.UpdateOrderApiStatus((int)OrderStatus.支付报关状态.处理中, 0, order.SysNo);
                        }
                        else
                        {
                            result.Message = "提交失败,错误代码:" + back["error"].ToString();
                        }

                        BLL.Log.LocalLogBo.Instance.Write("提交失败!" + responsestr, "EhkingCustomsERRORLog");
                        result.Status = false;
                    }
                    else
                    {
                        result.Message = "其他异常!";
                        result.Status  = false;
                        BLL.Log.LocalLogBo.Instance.Write("其他异常!" + responsestr, "EhkingCustomsLog");
                    }
                    //推送国检
                    //Hyt.BLL.ApiPay.EhkingCip.PayProvider.ApplyToCustoms(order);
                }
            }
            catch (Exception ex)
            {
                result.Message = "报错!";
                result.Status  = false;
                BLL.Log.LocalLogBo.Instance.Write("报错!" + ex.Message, "EhkingCustomsLog");
            }
            return(result);
        }
    /******************************************************************************/
    /*********************METHODS**************************/
    /// <summary>
    /// calculat md5 signature of the string in Input
    /// </summary>
    /// <returns> Digest: the finger print of msg</returns>
    protected Digest CalculateMD5Value()
    {
        /***********vairable declaration**************/
            byte [] bMsg;	//buffer to hold bits
            uint N;			//N is the size of msg as  word (32 bit)
            Digest dg =new Digest();			//  the value to be returned

            // create a buffer with bits padded and length is alos padded
            bMsg=CreatePaddedBuffer();

            N=(uint)(bMsg.Length*8)/32;		//no of 32 bit blocks

            for (uint  i=0; i<N/16;i++)
            {
                CopyBlock(bMsg,i);
                PerformTransformation(ref dg.A,ref dg.B,ref dg.C,ref dg.D);
            }
            return dg;
    }
Esempio n. 44
0
 public Mic(Digest digest) : this(new Base64Encoding().ToString(digest.Value),
                                  SMimeDigestMethod.FindByDigestMethod(digest.Method))
 {
 }
Esempio n. 45
0
        /// <summary>
        /// Send down a GET_DIGEST event, and wait for a response (GET_DIGEST_OK)
        /// </summary>
        /// <returns></returns>
        public Digest getDigest()
        {
            Digest ret=null;

            lock(digest_mutex)
            {
                digest=null;
                passDown(new Event(Event.GET_DIGEST));
                try
                {
                    Monitor.Wait(digest_mutex, (int)digest_timeout, true);
                }
                catch(Exception ex) {}
                if(digest != null)
                {
                    ret=digest;
                    digest=null;
                    return ret;
                }
                else
                {
                    if(Trace.trace)
                        Trace.error("GMS.getDigest()", "digest could not be fetched from PBCAST layer");
                    return null;
                }
            }
        }
Esempio n. 46
0
        public string returnResult(string actionType, NameValueCollection nvc, string httpFlag)
        {
            string hmacResource = "";
            string postParams   = "";
            string postUrl      = "";
            // 从Web.config文件里读取商户密钥
            string keyvalue = ConfigurationSettings.AppSettings["KeyValue"];

            if (actionType == "RefundExt")
            {
                // 从Web.config文件里读取通讯地址
                postUrl = ConfigurationSettings.AppSettings["distributeRefundUrl"];
            }
            else if (actionType == "IndirectRegister")
            {
                // 从Web.config文件里读取网关地址
                postUrl = ConfigurationSettings.AppSettings["distributeRegisterUrl"];
            }
            else
            {
                // 从Web.config文件里读取网关地址
                postUrl = ConfigurationSettings.AppSettings["distributeUrl"];
            }

            switch (actionType)
            {
            case "Buy":
                hmacArray = buyHmacArray;
                msgTitle  = "分账支付";
                break;

            case "QueryBalance":
                hmacArray = queryHmacArray;
                msgTitle  = "余额查询";
                break;

            case "RefundExt":
                hmacArray = refundHmacArray;
                msgTitle  = "分账退款";
                break;

            case "IndirectRegister":
                hmacArray = regMerchantHmacArray;
                msgTitle  = "子商户注册";
                break;

            case "PaymentConfirm":
                hmacArray = payConfirmHmacArray;
                msgTitle  = "分账解冻";
                break;
            }



            for (int i = 0; i < hmacArray.Length; i++)
            {
                hmacResource = hmacResource + nvc[hmacArray[i]];
                postParams   = postParams + hmacArray[i] + "=" + nvc[hmacArray[i]] + "&";
            }
            log.createLog(actionType, "sbold:" + hmacResource, "");
            string hmac = Digest.HmacSign(hmacResource, keyvalue);

            log.createLog(actionType, "keyvalue" + ":" + keyvalue, "hmac" + ":" + hmac);

            postParams = postParams + "hmac=" + hmac;

            if (httpFlag == "1")
            {
                // 记录重定向请求的url
                log.createLog(actionType, "requestUrl:" + postUrl + "?" + postParams, "");
                return(postUrl + "?" + postParams);
            }
            // 服务器点对点通讯
            else
            {
                StringBuilder strResult = new StringBuilder();
                WebRequest    req       = WebRequest.Create(postUrl);
                // 记录通讯请求的url
                log.createLog(actionType, "requestUrl:" + postUrl + "?" + postParams, "");
                req.Method      = "POST";
                req.ContentType = "application/x-www-form-urlencoded";

                byte[] tempBytes = Encoding.Default.GetBytes(postParams);

                req.ContentLength = tempBytes.Length;
                Stream newStream = req.GetRequestStream();
                newStream.Write(tempBytes, 0, tempBytes.Length);
                newStream.Close();
                WebResponse result        = req.GetResponse();
                Stream      ReceiveStream = result.GetResponseStream();
                Byte[]      read          = new Byte[512];
                int         bytes         = ReceiveStream.Read(read, 0, 512);
                while (bytes > 0)
                {
                    // 注意:
                    // 下面假定响应使用 UTF-8 作为编码方式。
                    // 如果内容以 ANSI 代码页形式(例如,932)发送,则使用类似下面的语句:
                    //  Encoding encode = System.Text.Encoding.GetEncoding("shift-jis");
                    Encoding encode = System.Text.Encoding.Default;//.GetEncoding(encodingName);
                    strResult.Append(encode.GetString(read, 0, bytes));
                    bytes = ReceiveStream.Read(read, 0, 512);
                }

                string resultStr = strResult.ToString();

                // 记录通讯返回信息

                log.createLog(actionType, "returnMsg:" + resultStr, "");

                NameValueCollection reParams = new NameValueCollection();

                string[] aryStr = resultStr.Split('\n');

                foreach (string i in aryStr)
                {
                    string[] aryParams = i.Split('=');
                    reParams.Add(aryParams[0], aryParams[1]);
                }

                if (reParams["r1_Code"] == "1")
                {
                    string returnStr = msgTitle + "成功!<br>" + resultStr;
                    return(returnStr);
                }
                else
                {
                    string returnStr = msgTitle + "失败!<br>" + resultStr + "<br>失败原因:<font color=red>" + showErrorCode(reParams["r1_Code"]) + "</font>";
                    return(returnStr);
                }
            }
        }
Esempio n. 47
0
 /// <summary>
 /// Send down a MERGE_DIGEST event
 /// </summary>
 /// <param name="d">Digest to merge</param>
 public void mergeDigest(Digest d)
 {
     passDown(new Event(Event.MERGE_DIGEST, d));
 }
Esempio n. 48
0
 public static SyncState GetSyncState(Digest digest, string EndPoint)
 {
     if (digest.Entries != null)
     {
         foreach (DigestEntry entry in digest.Entries)
         {
             if ((entry.EndPoint != null) && (entry.EndPoint.Equals(EndPoint, StringComparison.InvariantCultureIgnoreCase)))
             {
                 SyncState result = new SyncState();
                 result.EndPoint = entry.EndPoint;
                 result.Stamp = entry.Stamp;
                 result.Tick = (entry.Tick > 0) ?(int)entry.Tick : 1;
                 return result;
             }
         }
     }
     return null;
 }
Esempio n. 49
0
 /// <remarks>
 /// This method is overridden to avoid hanging on getDigest(): when a JOIN is received, the coordinator needs
 /// to retrieve the digest from the PBCAST layer. It therefore sends down a GET_DIGEST event, to which the PBCAST layer
 /// responds with a GET_DIGEST_OK event.<p>
 /// However, the GET_DIGEST_OK event will not be processed because the thread handling the JOIN request won't process
 /// the GET_DIGEST_OK event until the JOIN event returns. The receiveUpEvent() method is executed by the up-handler
 /// thread of the lower protocol and therefore can handle the event. All we do here is unblock the mutex on which
 /// JOIN is waiting, allowing JOIN to return with a valid digest. The GET_DIGEST_OK event is then discarded, because
 /// it won't be processed twice.</p>
 /// </remarks>
 /// <summary>
 /// Intercepts GET_DIGEST_OK Events
 /// </summary>
 /// <param name="evt"></param>
 protected override void receiveUpEvent(Event evt)
 {
     if(evt.Type == Event.GET_DIGEST_OK)
     {
         lock(digest_mutex)
         {
             digest=(Digest)evt.Arg;
             Monitor.PulseAll(digest_mutex);
         }
         return;
     }
     base.receiveUpEvent(evt);
 }
Esempio n. 50
0
 public static MutableString/*!*/ Name(Digest/*!*/ self) {
     return MutableString.CreateAscii(self._algorithm.HashName);
 }
Esempio n. 51
0
 /// <summary>
 /// Installs a new view within the process
 /// </summary>
 /// <param name="new_view">The new view to be installed</param>
 /// <param name="digest">The digest associated with the new view</param>
 public override void handleViewChange(View new_view, Digest digest)
 {
     ArrayList mbrs = new_view.getMembers();
     if (Trace.trace)
     {
         if (digest != null)
             Trace.info(
                 "CoordGmsImpl.handleViewChange()",
                 "view=" + new_view + ", digest=" + digest);
         else
             Trace.info(
                 "CoordGmsImpl.handleViewChange()",
                 "view=" + new_view);
     }
     if (leaving && !mbrs.Contains(gms.local_addr))
     {
         return;
     }
     gms.installView(new_view, digest);
 }
Esempio n. 52
0
 /// <summary>
 /// Process change to current view
 /// </summary>
 /// <param name="new_view">New View</param>
 /// <param name="digest">Digest associated with the view</param>
 public abstract void handleViewChange(View new_view, Digest digest);
        public void DoWork(IRequest request)
        {
            // ReturnSample(request);
            //return;
            // DECLARATIONS
            string resourceKindName;
            string EndPoint;
            SdataContext sdataContext;

            ISyncSyncDigestInfoStore syncDigestStore;
            SyncDigestInfo syncDigestInfo;

            // INITIALIZATIONS
            sdataContext = _requestContext.SdataContext;
            resourceKindName = _requestContext.ResourceKind.ToString();
            EndPoint = _requestContext.DatasetLink + resourceKindName;
            syncDigestStore = NorthwindAdapter.StoreLocator.GetSyncDigestStore(sdataContext);

            // Get the digest info from store
            syncDigestInfo = syncDigestStore.Get(resourceKindName);

            /* Create a digest payload and fill it with values retrived from digest store */
            //DigestPayload digestPayload = new DigestPayload();
            Digest digest = new Digest();

            digest.Origin = EndPoint;

            // set digest entries
            if ((null == syncDigestInfo) || (syncDigestInfo.Count == 0))
            {
                DigestEntry entry = new DigestEntry();
                entry.ConflictPriority = 1;
                entry.EndPoint = EndPoint;
                entry.Stamp = DateTime.Now;
                entry.Tick = 1;
                digest.Entries = new DigestEntry[] { entry };
            }
            else
            {
                digest.Entries = new DigestEntry[syncDigestInfo.Count];
                for (int i = 0; i < syncDigestInfo.Count; i++)
                {
                    DigestEntry entry = new DigestEntry();

                    entry.ConflictPriority = syncDigestInfo[i].ConflictPriority;
                    entry.EndPoint = syncDigestInfo[i].EndPoint;
                    entry.Stamp = syncDigestInfo[i].Stamp;
                    entry.Tick = (int)syncDigestInfo[i].Tick;
                    digest.Entries[i] = entry;
                }
            }

            // The url to this request
            string url = EndPoint + "/$syncDigest";

            // Create self link
            FeedLink link = new FeedLink(url, LinkType.Self, MediaType.AtomEntry);

            // Create FeedEntry
            // Set Response

            DigestFeedEntry digestFeedEntry = new DigestFeedEntry();
            digestFeedEntry.Digest = digest;
            digestFeedEntry.Title = "Synchronization digest";
            //digestFeedEntry.Id = url;
            digestFeedEntry.Links.Add(link);

            request.Response.FeedEntry = digestFeedEntry;
            request.Response.ContentType = MediaType.AtomEntry;
        }
        public List <Link> GetDigestLinks(Digest digest)
        {
            List <Link> links = new();
            //this provider has many different sections with different content, so it should be processed separately
            //Initial link leading to a decorated page with iframe, let's get actual link
            string       stubContent  = htmlContentGetter.GetContent(digest.DigestURL);
            HtmlDocument stubDocument = new();

            stubDocument.LoadHtml(stubContent);
            HtmlNode iframeNode = stubDocument.DocumentNode.SelectSingleNode("//iframe[@id='iframe']");
            string   realLink   = iframeNode.GetAttributeValue("src", "not found");
            var      baseUri    = new Uri(realLink);

            //getting real content
            string       digestContent  = htmlContentGetter.GetContent(realLink);
            HtmlDocument digestDocument = new();

            digestDocument.LoadHtml(digestContent);

            //Apps & Sites
            var appsSitesLinks = digestDocument.DocumentNode.SelectNodes("//tr[preceding-sibling::comment()[contains(.,'DIGITAL Start')]][following-sibling::comment()[contains(.,'DIGITAL End')]]/td[not(contains(@class,'spacer') or contains(@class,'headline'))]");
            int linkPosition   = 0;

            for (int i = 0; i < appsSitesLinks.Count; i++)
            {
                HtmlNode link            = appsSitesLinks[i];
                HtmlNode hrefNode        = link.SelectSingleNode(".//h2/a");
                string   href            = hrefNode.GetAttributeValue("href", "not found");
                string   title           = hrefNode.InnerText;
                HtmlNode descriptionNode = link.SelectSingleNode(".//p");
                descriptionNode = contentNormalizer.NormalizeDom(descriptionNode);
                string descriptionText = textSanitizer.Sanitize(descriptionNode.InnerHtml.Trim());

                links.Add(new Link
                {
                    URL         = href,
                    Title       = title,
                    Description = descriptionText,
                    LinkOrder   = linkPosition,
                    Digest      = digest
                });
                linkPosition++;
            }
            //Worthy Five
            HtmlNode worthyFiveNode     = digestDocument.DocumentNode.SelectSingleNode("//tr[preceding-sibling::comment()[contains(.,'BOX WORTHY Start')]][following-sibling::comment()[contains(.,'BOX WORTHY End')]]/td[not(contains(@class,'spacer') or contains(@class,'headline'))]");
            string   worthyFiveTitle    = worthyFiveNode.SelectSingleNode(".//table[1]//p[2]").InnerText;
            HtmlNode worthyFiveDescNode = worthyFiveNode.SelectSingleNode(".//table[2]");

            worthyFiveDescNode = contentNormalizer.NormalizeDom(worthyFiveDescNode);
            var    worthyFiveImageLink = new Uri(baseUri, "worthy-five.jpg").AbsoluteUri;
            string worthyFiveDescText  = worthyFiveImageLink + "\n" + textSanitizer.Sanitize(worthyFiveDescNode.InnerHtml.Trim());

            links.Add(new Link
            {
                URL         = worthyFiveImageLink,
                Title       = worthyFiveTitle,
                Description = worthyFiveDescText,
                LinkOrder   = linkPosition,
                Digest      = digest
            });
            linkPosition++;

            //Books & Accessories
            HtmlNodeCollection bookNodes = digestDocument.DocumentNode.SelectNodes("//tr[preceding-sibling::comment()[contains(.,'ACCESSORIES Start')]][following-sibling::comment()[contains(.,'ACCESSORIES End')]]/td[not(contains(@class,'spacer') or contains(@class,'headline'))]");

            for (int i = 0; i < bookNodes.Count; i++)
            {
                HtmlNode link            = bookNodes[i];
                HtmlNode hrefNode        = link.SelectSingleNode(".//h2/a");
                string   href            = hrefNode.GetAttributeValue("href", "not found");
                string   title           = hrefNode.InnerText;
                HtmlNode descriptionNode = link.SelectSingleNode("./table[2]//p");
                descriptionNode = contentNormalizer.NormalizeDom(descriptionNode);
                string descriptionText = textSanitizer.Sanitize(descriptionNode.InnerHtml.Trim());

                links.Add(new Link
                {
                    URL         = href,
                    Title       = title,
                    Description = descriptionText,
                    LinkOrder   = linkPosition,
                    Digest      = digest
                });
                linkPosition++;
            }

            //Overheard on Twitter + Food For Thought
            HtmlNodeCollection foodNodes = digestDocument.DocumentNode.SelectNodes("//tr[preceding-sibling::comment()[contains(.,'BOX TWEET Start')]][following-sibling::comment()[contains(.,'FOOD FOR THOUGHT End')]]/td[not(contains(@class,'spacer') or contains(@class,'headline'))]");

            for (int i = 0; i < foodNodes.Count; i++)
            {
                HtmlNode link            = foodNodes[i];
                HtmlNode hrefNode        = link.SelectSingleNode(".//h2/a");
                string   href            = hrefNode.GetAttributeValue("href", "not found");
                string   title           = hrefNode.InnerText;
                HtmlNode descriptionNode = link.SelectSingleNode(".//p");
                descriptionNode = contentNormalizer.NormalizeDom(descriptionNode);
                string descriptionText = textSanitizer.Sanitize(descriptionNode.InnerHtml.Trim());

                links.Add(new Link
                {
                    URL         = href,
                    Title       = title,
                    Description = descriptionText,
                    LinkOrder   = linkPosition,
                    Digest      = digest
                });
                linkPosition++;
            }

            //Aesthetically Pleasing
            HtmlNodeCollection aestheticNodes = digestDocument.DocumentNode.SelectNodes("//tr[preceding-sibling::comment()[contains(.,'BOX VISUAL INSP Start')]][following-sibling::comment()[contains(.,'BOX VISUAL INSP End')]]/td[not(contains(@class,'spacer') or contains(@class,'headline'))]");

            for (int i = 0; i < aestheticNodes.Count; i++)
            {
                HtmlNode link            = aestheticNodes[i];
                HtmlNode hrefNode        = link.SelectSingleNode("./table[2]//p//b/..");
                string   href            = hrefNode.GetAttributeValue("href", "not found");
                string   title           = hrefNode.InnerText;
                HtmlNode descriptionNode = link.SelectSingleNode("./table[2]//p");
                descriptionNode = contentNormalizer.NormalizeDom(descriptionNode);
                string descriptionText = textSanitizer.Sanitize(descriptionNode.InnerHtml.Trim());
                links.Add(new Link
                {
                    URL         = href,
                    Title       = title,
                    Description = descriptionText,
                    LinkOrder   = linkPosition,
                    Digest      = digest
                });
                linkPosition++;

                //images for this link
                HtmlNodeCollection images = link.SelectNodes(".//img");
                for (int j = 0; j < images.Count; j++)
                {
                    HtmlNode img     = images[j];
                    string   imgHref = img.GetAttributeValue("src", "not found");
                    imgHref = new Uri(new Uri(realLink), imgHref).AbsoluteUri;
                    links.Add(new Link
                    {
                        URL         = imgHref,
                        Title       = "",
                        Description = "",
                        LinkOrder   = linkPosition,
                        Digest      = digest
                    });
                    linkPosition++;
                }
            }
            //The Week in a GIF

            var gifImageLink = new Uri(baseUri, "gif.gif").AbsoluteUri;

            links.Add(new Link
            {
                URL         = gifImageLink,
                Title       = "The Week in a GIF",
                Description = "",
                LinkOrder   = linkPosition,
                Digest      = digest
            });
            return(links);
        }
Esempio n. 55
0
 public static int Seed(Digest/*!*/ self) {
     return self._algorithm.OutputBlockSize;
 }
 public string FormatDigestPost(Digest digest)
 {
     return(string.Format("<b>{0} - {1}</b>\n{2}\n{3}", digest.DigestName, digest.DigestDay.ToString("yyyy-MM-dd"), digest.DigestDescription, digest.DigestURL));
 }
Esempio n. 57
0
                public static MutableString/*!*/ BlankHexDigest(Digest/*!*/ self) {
#if !SILVERLIGHT
                    byte[] blank_data = Encoding.UTF8.GetBytes("");
                    byte[] hash = new SHA1CryptoServiceProvider().ComputeHash(blank_data);
                    return MutableString.CreateAscii(BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant());
#else
            throw new NotSupportedException();
#endif
                }
 public Otp(string secret, Digest digest = DEFAULT_DIGEST, int digits = DEFAULT_DIGITS)
 {
     this.secret = secret;
     this.digest = digest;
     this.digits = digits;
 }
Esempio n. 59
0
 public static Digest/*!*/ Reset(Digest/*!*/ self) {
     self._algorithm.Clear();
     return self;
 }
Esempio n. 60
0
 public static MutableString /*!*/ Name(Digest /*!*/ self)
 {
     return(MutableString.CreateAscii(self._algorithm.HashName));
 }