public Hasher()
 {
     sha = new SHA1CryptoServiceProvider();
 }
Exemple #2
0
 /// <summary>
 /// 验证 SHA1 值
 /// </summary>
 /// <param name="input"> 未加密的字符串 </param>
 /// <param name="encoding"> 字符编码 </param>
 /// <returns></returns>
 public static bool VerifySha1Value(string input, Encoding encoding)
 {
     return(VerifyHashValue(SHA1.Create(), input, Sha1Encrypt(input, encoding), encoding));
 }
        /// <summary> 获得指定文件的Hash值 </summary>
        /// <param name="filePath" type="string">文件路径</param>
        /// <param name="isMd5">是否是md5</param>
        /// <returns></returns>
        public static string GetFileHash(string filePath, bool isMd5 = false)
        {
            var hasher = isMd5 ? (HashAlgorithm)MD5.Create() : SHA1.Create();

            return(BitConverter.ToString(hasher.ComputeHash(System.IO.File.ReadAllBytes(filePath))).Replace("-", "").ToUpper());
        }
Exemple #4
0
        public bool HandleRecvParseMsg()
        {
            do
            {
                if (cacheRecvData.Length < 1)
                {
                    return(true);
                }
                //FFLog.Trace(string.Format("HandleRecv cacheRecvData!!! {0}", cacheRecvData.Length));
                if (dictParams.Count == 0)
                {
                    string strRecvData = Byte2String(cacheRecvData);
                    if (strRecvData.Length < 3)
                    {
                        return(true);
                    }
                    if (strRecvData.Length >= 3 && strRecvData.StartsWith("GET") == false)
                    {
                        statusWebSocketConnection = -1;
                        return(false);
                    }
                    if (strRecvData.Contains("\r\n\r\n") == false)//!header data not end
                    {
                        return(true);
                    }
                    if (strRecvData.Contains("Upgrade: websocket") == false)
                    {
                        statusWebSocketConnection = -1;
                        return(false);
                    }
                    string[] strLines = strRecvData.Split("\r\n");
                    foreach (var line in strLines)
                    {
                        string[] strParams = line.Split(": ");
                        if (strParams.Length == 2)
                        {
                            dictParams[strParams[0]] = strParams[1];
                        }
                        else if (strParams.Length == 1 && strParams[0].Contains("GET"))
                        {
                            dictParams["PATH"] = strParams[0];
                        }
                    }
                    if (true == dictParams.ContainsKey("Sec-WebSocket-Key"))
                    {
                        string Sec_WebSocket_Key = dictParams["Sec-WebSocket-Key"];
                        string strGUID           = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
                        byte[] dataToHash        = System.Text.Encoding.UTF8.GetBytes(Sec_WebSocket_Key + strGUID);
                        byte[] dataHashed        = SHA1.Create().ComputeHash(dataToHash);
                        string strHashBase64     = Convert.ToBase64String(dataHashed);

                        string strSendData = string.Format("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {0}\r\n\r\n", strHashBase64);
                        AddSendPkg(String2Byte(strSendData));
                        strRecvData               = "";
                        cacheRecvData             = new byte[0];
                        statusWebSocketConnection = 1;

                        return(true);
                    }
                    else if (true == dictParams.ContainsKey("Sec-WebSocket-Key1"))
                    {
                        string handshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\n";

                        string str_origin = dictParams["Origin"];
                        if (str_origin.Length == 0)
                        {
                            str_origin = "null";
                        }
                        handshake += "Sec-WebSocket-Origin: " + str_origin + "\r\n";

                        string str_host = dictParams["Host"];
                        if (str_host.Length > 0)
                        {
                            string[] tmp_path_arg = strLines[0].Split(" ");
                            string   tmp_path     = "/";
                            if (tmp_path_arg.Length >= 2)
                            {
                                tmp_path = tmp_path_arg[1];
                            }

                            handshake += "Sec-WebSocket-Location: ws://" + dictParams["Host"] + tmp_path + "\r\n\r\n";
                        }

                        UInt32 key1 = ComputeWebsokcetKeyVal(dictParams["Sec-WebSocket-Key1"]);
                        UInt32 key2 = ComputeWebsokcetKeyVal(dictParams["Sec-WebSocket-Key2"]);

                        string keyExt = strLines[strLines.Length - 1];
                        if (keyExt.Length < 8)
                        {
                            statusWebSocketConnection = -1;
                            return(false);
                        }

                        byte[] tmpBuff     = new byte[16];
                        byte[] key1Bytes   = BitConverter.GetBytes(key1);
                        byte[] key2Bytes   = BitConverter.GetBytes(key2);
                        byte[] keyExtBytes = String2Byte(keyExt);
                        Array.Copy(key1Bytes, 0, tmpBuff, 0, key1Bytes.Length);
                        Array.Copy(key2Bytes, 0, tmpBuff, key1Bytes.Length, key2Bytes.Length);
                        Array.Copy(keyExtBytes, 0, tmpBuff, key1Bytes.Length + key2Bytes.Length, keyExtBytes.Length);
                        handshake += ComputeMd5(tmpBuff);
                        AddSendPkg(String2Byte(handshake));
                    }
                    else
                    {
                        statusWebSocketConnection = -1;
                        return(false);
                    }
                }
                int nFIN    = ((cacheRecvData[0] & 0x80) == 0x80)? 1: 0;
                int nOpcode = cacheRecvData[0] & 0x0F;
                //int nMask = ((cacheRecvData[1] & 0x80) == 0x80) ? 1 : 0;
                int nPayload_length     = cacheRecvData[1] & 0x7F;
                int nPlayLoadLenByteNum = 1;
                int nMaskingKeyByteNum  = 4;
                if (nPayload_length == 126)
                {
                    nPlayLoadLenByteNum = 3;
                }
                else if (nPayload_length == 127)
                {
                    nPlayLoadLenByteNum = 9;
                }
                if (cacheRecvData.Length < (1 + nPlayLoadLenByteNum + nMaskingKeyByteNum))
                {
                    return(true);
                }
                if (nPayload_length == 126)
                {
                    byte[] nPayload_length_Bytes = new byte[2];
                    Array.Copy(cacheRecvData, 2, nPayload_length_Bytes, 0, nPayload_length_Bytes.Length);
                    nPayload_length = System.Net.IPAddress.NetworkToHostOrder(BitConverter.ToInt16(nPayload_length_Bytes, 0));
                }
                else if (nPayload_length == 127)
                {
                    byte[] nPayload_length_Bytes = new byte[8];
                    Array.Copy(cacheRecvData, 2, nPayload_length_Bytes, 0, nPayload_length_Bytes.Length);
                    nPayload_length = (int)System.Net.IPAddress.NetworkToHostOrder((long)BitConverter.ToInt64(nPayload_length_Bytes, 0));
                }
                if (cacheRecvData.Length < (1 + nPlayLoadLenByteNum + nMaskingKeyByteNum + nPayload_length))
                {
                    return(true);
                }

                byte[] aMasking_key = new byte[nMaskingKeyByteNum];
                Array.Copy(cacheRecvData, 1 + nPlayLoadLenByteNum, aMasking_key, 0, nMaskingKeyByteNum);
                byte[] aPayload_data = new byte[nPayload_length];
                Array.Copy(cacheRecvData, 1 + nPlayLoadLenByteNum + nMaskingKeyByteNum, aPayload_data, 0, nPayload_length);
                int    nLeftSize = cacheRecvData.Length - (1 + nPlayLoadLenByteNum + nMaskingKeyByteNum + nPayload_length);
                byte[] leftBytes = new byte[nLeftSize];
                if (nLeftSize > 0)
                {
                    Array.Copy(cacheRecvData, 1 + nPlayLoadLenByteNum + nMaskingKeyByteNum + nPayload_length, leftBytes, 0, nLeftSize);
                }
                cacheRecvData = leftBytes;
                for (int i = 0; i < nPayload_length; i++)
                {
                    aPayload_data[i] = (byte)(aPayload_data[i] ^ aMasking_key[i % 4]);
                }

                if (8 == nOpcode)
                {
                    AddSendPkg(BuildPkg(new byte[0], nOpcode));// close
                    bIsClose = true;
                }
                else if (2 == nOpcode || 1 == nOpcode || 0 == nOpcode || 9 == nOpcode)
                {
                    if (9 == nOpcode)                           //!ping
                    {
                        AddSendPkg(BuildPkg(new byte[0], 0xA)); // pong
                    }

                    if (nFIN == 1)
                    {
                        if (dataFragmentation.Length == 0)
                        {
                            AddRecvPkg(aPayload_data);
                        }
                        else
                        {
                            dataFragmentation = MergeArray(dataFragmentation, aPayload_data);
                            AddRecvPkg(dataFragmentation);
                            dataFragmentation = new byte[0];
                        }
                    }
                    else
                    {
                        dataFragmentation = MergeArray(dataFragmentation, aPayload_data);
                    }
                }
                else
                {
                    FFLog.Trace(string.Format("nOpcode={0},data={1}", nOpcode, aPayload_data.Length));
                }
            } while(cacheRecvData.Length > 0);
            return(true);
        }
Exemple #5
0
 public static byte[] GetPakFileHash(string fileName)
 {
     // base64(sha1(file))
     return(Encoding.ASCII.GetBytes(Convert.ToBase64String(SHA1.Create().ComputeHash(File.ReadAllBytes(fileName)))));
 }
        protected override void HandleLtMetadataMessage(PeerId id, LTMetadata message)
        {
            base.HandleLtMetadataMessage(id, message);

            switch (message.MetadataMessageType)
            {
            case LTMetadata.MessageType.Data:
                if (Stream is null || bitField is null)
                {
                    throw new Exception("Need extention handshake before ut_metadata message.");
                }

                // If we've already received everything successfully, do nothing!
                if (bitField.AllTrue)
                {
                    return;
                }

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

                    if (!Manager.InfoHashes.Contains(hash))
                    {
                        bitField.SetAll(false);
                    }
                    else
                    {
                        Stream.Position = 0;
                        BEncodedDictionary dict = new BEncodedDictionary();
                        dict.Add("info", BEncodedValue.Decode(Stream));

                        if (Manager.TrackerManager.Tiers != null && Manager.TrackerManager.Tiers.Count > 0)
                        {
                            BEncodedList announceTrackers = new BEncodedList();
                            foreach (var tier in Manager.TrackerManager.Tiers)
                            {
                                BEncodedList announceUrls = new BEncodedList();

                                foreach (var tracker in tier.Trackers)
                                {
                                    announceUrls.Add(new BEncodedString(tracker.Uri.OriginalString));
                                }

                                announceTrackers.Add(announceUrls);
                            }

                            dict.Add("announce-list", announceTrackers);
                        }
                        var rawData = dict.Encode();
                        if (Torrent.TryLoad(rawData, out Torrent? t))
                        {
                            if (stopWhenDone)
                            {
                                Manager.RaiseMetadataReceived(rawData);
                                return;
                            }

                            try {
                                if (this.Settings.AutoSaveLoadMagnetLinkMetadata)
                                {
                                    if (Path.GetDirectoryName(savePath) is string parentDir && !Directory.Exists(parentDir))
                                    {
                                        Directory.CreateDirectory(parentDir);
                                    }
                                    File.Delete(savePath);
                                    File.WriteAllBytes(savePath, dict.Encode());
                                }
                            } catch (Exception ex) {
                                logger.ExceptionFormated(ex, "Cannot write metadata to path '{0}'", savePath);
                                Manager.TrySetError(Reason.WriteFailure, ex);
                                return;
                            }
                            Manager.SetMetadata(t);
                            _ = Manager.StartAsync();
                            Manager.RaiseMetadataReceived(rawData);
                        }
                        else
                        {
                            bitField.SetAll(false);
                        }
                    }
                }
                RequestNextNeededPiece(id);
                break;

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

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

            default:
                throw new MessageException($"Invalid messagetype in LTMetadata: {message.MetadataMessageType}");
            }
        }
        string CalculateShaPassHash(string name, string password)
        {
            SHA1 sha = SHA1.Create();

            return(sha.ComputeHash(Encoding.UTF8.GetBytes(name + ":" + password)).ToHexString());
        }
 public static string ToSha1(this string text) => SHA1.Create().ComputeHash(text.ToBytes()).ToHex();
Exemple #9
0
 public static byte[] Hash(byte[] data)
 {
     using var h = SHA1.Create();
     return(h.ComputeHash(data));
 }
Exemple #10
0
 /// <summary>
 /// 验证 SHA1 值
 /// </summary>
 /// <param name="input"> 未加密的字符串 </param>
 /// <param name="encoding"> 字符编码 </param>
 /// <returns></returns>
 public static async Task <bool> VerifySha1Value(string input, Encoding encoding)
 {
     return(await VerifyHashValue(SHA1.Create(), input, Sha1Encrypt(input, encoding).Result, encoding));
 }
 public SaviorClient()
 {
     context  = new Context();
     hashFunc = SHA1Managed.Create();
 }
Exemple #12
0
 /// <summary>
 /// SHA1 加密
 /// </summary>
 /// <param name="input"> 要加密的字符串 </param>
 /// <param name="encoding"> 字符编码 </param>
 /// <returns></returns>
 public static async Task <string> Sha1Encrypt(string input, Encoding encoding)
 {
     return(await HashEncrypt(SHA1.Create(), input, encoding));
 }
Exemple #13
0
 string HashString(string input)
 {
     using (SHA1 sha = SHA1.Create())
         return(string.Join(string.Empty, sha.ComputeHash(Encoding.UTF8.GetBytes(input))));
 }
Exemple #14
0
 /// <summary>
 /// Encode to Base 64
 /// </summary>
 /// <param name="input">input as string</param>
 /// <returns>output as base 64 encoded string</returns>
 public static string ToBase64EncodedSha1String(this string input)
 {
     return(Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(input))));
 }
Exemple #15
0
 static Extensions( )
 {
     defaultCompression = CompressionLevel.Optimal;
     defaultEncoding    = Encoding.UTF8;
     hashProvider       = SHA1.Create( );
 }
Exemple #16
0
 public static byte[] Hash(Stream s)
 {
     using var h = SHA1.Create();
     return(h.ComputeHash(s));
 }
Exemple #17
0
        public static bool TryParse(ReadOnlySpan <byte> bytes, out TorrentInfo torrent, bool strictComplianceParsing = false)
        {
            torrent = null;

            if (!BEncodingSerializer.TryParse(bytes, out BDictionary dictionary, strictDictionaryOrder: strictComplianceParsing))
            {
                return(false);
            }

            if (dictionary.Count > 50)
            {
                return(false);
            }

            if (!dictionary.TryGet("info", out BDictionary info))
            {
                return(false);
            }

            if (info.Count < 3 || info.Count > 50)
            {
                return(false);
            }

            torrent = new TorrentInfo();

            if (!info.TryGet("name", out BString name) || !name.IsString)
            {
                return(false);
            }

            torrent.DisplayName = name.String;

            if (!info.TryGet("piece length", out BInteger bpieceLength) || !bpieceLength.TryAs(out uint pieceLength))
            {
                return(false);
            }

            torrent.PieceLength = (PieceLength)pieceLength;
            if (pieceLength == 0 || !torrent.PieceLength.IsValid())
            {
                return(false);
            }

            if (info.TryGet("pieces", out BString pieces))
            {
                if (pieces.Binary.Length % 20 != 0)
                {
                    return(false);
                }

                torrent._pieces  = pieces.Binary;
                torrent.Version |= BitTorrentVersion.V1;

                if (info.TryGet("length", out BInteger bLength))
                {
                    if (!bLength.TryAs(out long length) || length < 0)
                    {
                        return(false);
                    }

                    torrent.Files      = new[] { new FileDescriptor(torrent.DisplayName, length, offset: 0) };
                    torrent.TotalBytes = length;
                }
                else
                {
                    if (!info.TryGet("files", out BList fileList))
                    {
                        return(false);
                    }

                    if (fileList.Count < (strictComplianceParsing ? 2 : 1))
                    {
                        return(false);
                    }

                    var files = new FileDescriptor[fileList.Count];

                    long offset = 0;

                    for (int i = 0; i < fileList.Count; i++)
                    {
                        if (!(fileList[i] is BDictionary fileEntry))
                        {
                            return(false);
                        }

                        if (!fileEntry.TryGet("length", out BInteger fileBLength) || !fileBLength.TryAs(out long fileLength))
                        {
                            return(false);
                        }

                        if (fileLength < 0 || fileLength + offset < 0)
                        {
                            return(false);
                        }

                        if (!fileEntry.TryGet("path", out BList pathList))
                        {
                            return(false);
                        }

                        if (pathList.Count == 0 || pathList.Count > Constants.MaxFileDirectoryDepth)
                        {
                            return(false);
                        }

                        int      totalPathLength = pathList.Count;
                        string[] path            = new string[pathList.Count];
                        for (int j = 0; j < pathList.Count; j++)
                        {
                            if (!(pathList[j] is BString pathBPart) || !pathBPart.IsString)
                            {
                                return(false);
                            }

                            string pathPart = pathBPart.String;

                            if (pathPart.Length == 0)
                            {
                                return(false);
                            }

                            if (!PathHelpers.IsSafeFilePathPart(pathPart))
                            {
                                return(false);
                            }

                            totalPathLength += pathPart.Length;

                            if ((uint)totalPathLength > Constants.MaxFilePathLength)
                            {
                                return(false);
                            }

                            path[j] = pathPart;
                        }

                        files[i] = new FileDescriptor(path, fileLength, offset);

                        offset += fileLength;
                    }

                    torrent.Files      = files;
                    torrent.TotalBytes = offset;
                }

                long pieceCount = (torrent.TotalBytes + pieceLength - 1) / pieceLength;

                // Sanity check on the piece count
                if (pieceLength < (int)PieceLength.MB_8 && pieceCount > 250000)
                {
                    return(false);
                }

                if (pieceCount * 20 != pieces.Binary.Length)
                {
                    return(false);
                }
            }

            if (info.TryGet("meta version", out BInteger version))
            {
                if (version.Value == 2)
                {
                    torrent.Version |= BitTorrentVersion.V2;
                }
                else if (torrent.Version != BitTorrentVersion.V1 || !version.Value.IsOne)
                {
                    return(false);
                }
            }
            else if (torrent.Version == default)
            {
                return(false);
            }

            if (torrent.Version.HasFlag(BitTorrentVersion.V2))
            {
                if (!info.TryGet("file tree", out BDictionary fileTree))
                {
                    return(false);
                }

                if (!dictionary.TryGet("piece layers", out BDictionary pieceLayers))
                {
                    return(false);
                }

                // file tree
                //throw new NotImplementedException();
            }

            if (info.TryGet("private", out BInteger isPrivate) && isPrivate.Value.IsOne)
            {
                torrent.IsPrivate = true;
            }

            if (dictionary.TryGet("announce", out BString announce) && announce.IsString)
            {
                if (StringHelpers.LooksLikeValidAnnounceURL(announce.String))
                {
                    torrent.Trackers.Add(announce.String);
                }
            }

            if (dictionary.TryGet("announce-list", out BList announceList))
            {
                foreach (var announceEntry in announceList)
                {
                    if (announceEntry is BList announceStringList)
                    {
                        if (announceStringList.Count == 1 && announceStringList[0] is BString announceString)
                        {
                            if (announceString.IsString)
                            {
                                if (StringHelpers.LooksLikeValidAnnounceURL(announceString.String))
                                {
                                    torrent.Trackers.Add(announceString.String);
                                }
                            }
                        }
                    }
                }
            }

            if (dictionary.TryGet("comment", out BString comment) && comment.IsString)
            {
                torrent.Comment = comment.String;
            }

            if (dictionary.TryGet("created by", out BString createdBy) && createdBy.IsString)
            {
                torrent.CreatedBy = createdBy.String;
            }

            if (dictionary.TryGet("creation date", out BInteger bcreationDate) && bcreationDate.TryAs(out long creationDate))
            {
                if (creationDate >= 0)
                {
                    torrent.CreationTimeStamp = creationDate;
                    torrent.CreationDate      = DateTime.UnixEpoch.AddSeconds(creationDate);
                }
            }

            if (dictionary.TryGet("encoding", out BString encoding) && encoding.IsString)
            {
                torrent.Encoding = encoding.String;
            }


            ReadOnlySpan <byte> infoSpan = bytes.Slice(info.SpanStart, info.SpanEnd - info.SpanStart);

            Debug.Assert(infoSpan[0] == 'd' && infoSpan[infoSpan.Length - 1] == 'e');
            if (torrent.Version.HasFlag(BitTorrentVersion.V1))
            {
                torrent.InfoHashV1 = new byte[20];
                using SHA1 sha1    = SHA1.Create();
                if (!sha1.TryComputeHash(infoSpan, torrent.InfoHashV1, out int written) || written != 20)
                {
                    return(false);
                }
            }
            if (torrent.Version.HasFlag(BitTorrentVersion.V2))
            {
                torrent.InfoHashV2  = new byte[32];
                using SHA256 sha256 = SHA256.Create();
                if (!sha256.TryComputeHash(infoSpan, torrent.InfoHashV2, out int written) || written != 32)
                {
                    return(false);
                }
            }

            return(true);
        }
        /// <summary>
        /// Returns a X509Certificate2Collection for the given thumbprint.
        /// The collection should contain exactly one certificate.
        /// If the call fails the function return null.
        /// If no certificate was found, the Collection contains a zero count
        /// </summary>
        /// <param name="pThumbPrint"></param>
        /// <returns></returns>
        internal static X509Certificate2Collection GetClientCertificatesByThumbprint(string pThumbPrint)
        {
            if (string.IsNullOrEmpty(pThumbPrint))
            {
                // TODO Load .pfx given file name and password from config? Might be required on Linux to avoid unencrypted .pfx's in the dotNet Core User Cert store (current dotNet Core behavior).
                // Best practice with k8s seems to be to place .pfx and password into separate secrets and load in code
                return(null);
            }

            X509Certificate2Collection certs;

            try
            {
                try
                {
                    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                    // OK to accept invalid certs here, as the thumbprint prevents use of certs that may have been tampered with etc. This allows
                    // - Use of certs without a matching root cert / intermediate certs on the client
                    // - Use of expired certs (the server may still chose to reject)
                    certs = store.Certificates.Find(X509FindType.FindByThumbprint, pThumbPrint, false);
                }
                catch (System.Security.Cryptography.CryptographicException ex) when(ex.InnerException is PlatformNotSupportedException)
                {
                    certs = null;
                    #region Linux experiments
                    ////X509Store caStore = new X509Store(StoreName.CertificateAuthority, StoreLocation.CurrentUser);
                    ////caStore.Open(OpenFlags.ReadWrite);

                    ////var fileName4 = "/usr/local/share/ca-certificates/MyTestCARoot04.crt";
                    ////var newCert = new X509Certificate2(fileName4);
                    ////caStore.Add(newCert);
                    ////caStore.Close();

                    // This populates the .Net Core cert store with a preinstalled PFX from the image (useful for local testing)
                    //X509Store userStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    //userStore.Open(OpenFlags.ReadWrite);
                    //var fileName5 = Path.Combine("/etc/ssl/certs/private", $"TestClient05_02.pfx");
                    //var password5 = "supersecret";
                    //var newCert2 = new X509Certificate2(fileName5, password5);
                    //userStore.Add(newCert2);
                    //userStore.Close();

                    //X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    ////X509Store store = new X509Store(StoreName.CertificateAuthority, StoreLocation.LocalMachine);
                    //store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                    //var certs = store.Certificates.Find(X509FindType.FindByThumbprint, pThumbPrint, true);
                    //var firstCert = certs?.Count > 0 ? certs[0] : null;
                    //if (firstCert?.HasPrivateKey == false)
                    //{
                    //    var cert1 = certs[0];
                    //    var cert = new X509Certificate2(cert1.RawData, "clabs1234", X509KeyStorageFlags.DefaultKeySet);
                    //    var fileName2 = Path.Combine("/etc/ssl/certs/private", $"{cert1.Subject.Substring(3)}.pem");
                    //    var password2 = "supersecret";
                    //    var cert2 = new X509Certificate2(fileName2, password2, X509KeyStorageFlags.DefaultKeySet);
                    //    var fileName3 = Path.Combine("/etc/ssl/certs/private", $"{cert1.Subject.Substring(3)}.pfx");
                    //    var password3 = "supersecret";
                    //    var cert3 = new X509Certificate2(fileName3, password3);
                    //    //var cert4 = cert1.CopyWithPrivateKey(); // NetStandard 2.1 only (or NetCoreApp 2.x)
                    //    certs = new X509Certificate2Collection(cert);
                    //}
                    #endregion
                }
                if (certs == null || certs.Count == 0)
                {
                    // Look for cert in user store:
                    // - On Linux/dotNet Core (as of V2.2 and v3.0), only certs (*.pfx's) in the dotNet Core "user" store are loaded with private keys. For global certs, dotNet Core only loads the public key.
                    //   https://github.com/dotnet/corefx/blob/master/Documentation/architecture/cross-platform-cryptography.md
                    // - Useful on Windows for developer scenarios or advanced scenarios where a service runs with a specific user account
                    X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                    certs = store.Certificates.Find(X509FindType.FindByThumbprint, pThumbPrint, false);
                }
                TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.VERBOSE) ? null : new TSM("TheCommonUtils", $"Found {certs?.Count} certificate with Thumbprint {pThumbPrint} found", eMsgLevel.l4_Message));
            }
            catch (Exception e)
            {
                TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", $"Error during retreival of Certificate with Thumbprint {pThumbPrint} not found", eMsgLevel.l1_Error, e.ToString()));
                certs = null;
            }
            if (certs != null)
            {
                foreach (var cert in certs)
                {
                    try
                    {
                        if (cert.PrivateKey == null)
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", $"Certificate with Thumbprint {cert.Thumbprint} has no PrivateKey", eMsgLevel.l1_Error));
                            continue;
                        }
#if !CDE_STANDARD
                        var rsa = cert.PrivateKey as RSACryptoServiceProvider;
                        if (rsa != null)
                        {
                            var signed = rsa.SignData(System.Text.Encoding.UTF8.GetBytes("Hello World"), SHA1.Create());
                        }
#else
                        var rsa = cert.PrivateKey as RSA;
                        if (rsa != null)
                        {
                            var signed = rsa.SignData(System.Text.Encoding.UTF8.GetBytes("Hello World"), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
                        }
#endif
                        else
                        {
                            TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", $"Certificate with Thumbprint {cert.Thumbprint}: unable to verify if private key is usable", eMsgLevel.l1_Error));
                            continue;
                        }
                        TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.ESSENTIALS) ? null : new TSM("TheCommonUtils", $"Certificate with Thumbprint {cert.Thumbprint} has usable private key: (HasPrivateKey: {cert.HasPrivateKey})", eMsgLevel.l3_ImportantMessage));
                    }
                    catch (Exception e)
                    {
                        TheBaseAssets.MySYSLOG.WriteToLog(4365, TSM.L(eDEBUG_LEVELS.OFF) ? null : new TSM("TheCommonUtils", $"Certificate with Thumbprint {cert.Thumbprint} error using private key (HasPrivateKey: {cert.HasPrivateKey}) ", eMsgLevel.l1_Error, e.ToString()));
                    }
                }
            }
            return(certs);
        }
 /// <summary>
 /// Формування сигнатури
 /// </summary>
 /// <param name="data">Json string з параметрами для LiqPay</param>
 /// <returns></returns>
 static public string GetLiqPaySignature(string data)
 {
     return(Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(_private_key + data + _private_key))));
 }
Exemple #20
0
 public static byte[] Sha1Sum(byte[] data) => SHA1.Create().ComputeHash(data);
        /// <summary>
        /// Creates a name-based UUID using the algorithm from RFC 4122 §4.3.
        /// </summary>
        /// <param name="namespaceId">The ID of the namespace.</param>
        /// <param name="name">The name (within that namespace).</param>
        /// <param name="version">The version number of the UUID to create; this value must be either
        /// 3 (for MD5 hashing) or 5 (for SHA-1 hashing).</param>
        /// <returns>A UUID derived from the namespace and name.</returns>
        /// <remarks>See <a href="http://code.logos.com/blog/2011/04/generating_a_deterministic_guid.html">Generating a deterministic GUID</a>.</remarks>
        public static Guid Create(Guid namespaceId, byte[] nameBytes, int version)
        {
            if (nameBytes == null || nameBytes.Length < 1)
            {
                throw new ArgumentNullException("name");
            }
            if (version != 3 && version != 5)
            {
                throw new ArgumentOutOfRangeException("version", "version must be either 3 or 5.");
            }

            // convert the name to a sequence of octets (as defined by the standard or conventions of its namespace) (step 3)
            // ASSUME: UTF-8 encoding is always appropriate
            //byte[] nameBytes = Encoding.UTF8.GetBytes(name);

            // convert the namespace UUID to network order (step 3)
            byte[] namespaceBytes = namespaceId.ToByteArray();
            SwapByteOrder(namespaceBytes);

            // comput the hash of the name space ID concatenated with the name (step 4)
            byte[] hash;
            using (HashAlgorithm algorithm = version == 3 ? (HashAlgorithm)MD5.Create() : SHA1.Create())
            {
                algorithm.TransformBlock(namespaceBytes, 0, namespaceBytes.Length, null, 0);
                algorithm.TransformFinalBlock(nameBytes, 0, nameBytes.Length);
                hash = algorithm.Hash;
            }

            // most bytes from the hash are copied straight to the bytes of the new GUID (steps 5-7, 9, 11-12)
            byte[] newGuid = new byte[16];
            Array.Copy(hash, 0, newGuid, 0, 16);

            // set the four most significant bits (bits 12 through 15) of the time_hi_and_version field to the appropriate 4-bit version number from Section 4.1.3 (step 8)
            newGuid[6] = (byte)((newGuid[6] & 0x0F) | (version << 4));

            // set the two most significant bits (bits 6 and 7) of the clock_seq_hi_and_reserved to zero and one, respectively (step 10)
            newGuid[8] = (byte)((newGuid[8] & 0x3F) | 0x80);

            // convert the resulting UUID to local byte order (step 13)
            SwapByteOrder(newGuid);
            return(new Guid(newGuid));
        }
Exemple #22
0
        internal static async Task CheckAsync(List <FileInfo> pkgList, int fnameWidth, int sigWidth, int csumWidth, int allCsumsWidth, CancellationToken cancellationToken)
        {
            TotalFileSize = pkgList.Sum(i => i.Length);

            var buf = new byte[1024 * 1024]; // 1 MB

            foreach (var item in pkgList)
            {
                Write($"{item.Name.Trim(fnameWidth).PadRight(fnameWidth)} ");
                try
                {
                    CurrentPadding  = sigWidth;
                    CurrentFileSize = item.Length;
                    if (item.Length < 0xC0 + 0x20) // header + csum at the end
                    {
                        Write("invalid pkg".PadLeft(allCsumsWidth) + Environment.NewLine, ConsoleColor.Red);
                        continue;
                    }

                    using var file = File.Open(item.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                    var header = new byte[0xc0];
                    file.ReadExact(header);
                    byte[] sha1Sum = null;
                    using (var sha1 = SHA1.Create())
                        sha1Sum = sha1.ComputeHash(header, 0, 0x80);
                    if (!ValidateCmac(header))
                    {
                        Write("cmac".PadLeft(sigWidth) + " ", ConsoleColor.Red);
                    }
                    else if (!ValidateHash(header, sha1Sum))
                    {
                        Write("sha1".PadLeft(sigWidth) + " ", ConsoleColor.Yellow);
                    }
                    else if (!ValidateSigNew(header, sha1Sum))
                    {
                        if (!ValidateSigOld(header, sha1Sum))
                        {
                            Write("ecdsa".PadLeft(sigWidth) + " ", ConsoleColor.Red);
                        }
                        else
                        {
                            Write("ok (old)".PadLeft(sigWidth) + " ", ConsoleColor.Yellow);
                        }
                    }
                    else
                    {
                        Write("ok".PadLeft(sigWidth) + " ", ConsoleColor.Green);
                    }

                    CurrentPadding = csumWidth;
                    file.Seek(0, SeekOrigin.Begin);
                    byte[] hash;
                    using (var sha1 = SHA1.Create())
                    {
                        var dataLengthToHash = CurrentFileSize - 0x20;
                        int read;
                        do
                        {
                            read = await file.ReadAsync(buf, 0, (int)Math.Min(buf.Length, dataLengthToHash - CurrentFileProcessedBytes), cancellationToken).ConfigureAwait(false);

                            CurrentFileProcessedBytes += read;
                            sha1.TransformBlock(buf, 0, read, null, 0);
                        } while (read > 0 && CurrentFileProcessedBytes < dataLengthToHash && !cancellationToken.IsCancellationRequested);
                        sha1.TransformFinalBlock(buf, 0, 0);
                        hash = sha1.Hash;
                    }
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var expectedHash = new byte[0x14];
                    file.ReadExact(expectedHash);
                    CurrentFileProcessedBytes += 0x20;
                    if (!expectedHash.SequenceEqual(hash))
                    {
                        Write("fail".PadLeft(csumWidth) + Environment.NewLine, ConsoleColor.Red);
                    }
                    else
                    {
                        Write("ok".PadLeft(csumWidth) + Environment.NewLine, ConsoleColor.Green);
                    }
                }
                catch (Exception e)
                {
                    Write("Error" + Environment.NewLine + e.Message + Environment.NewLine, ConsoleColor.Red);
                }
                finally
                {
                    ProcessedBytes           += CurrentFileSize;
                    CurrentFileProcessedBytes = 0;
                    CurrentPadding            = 0;
                }
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }
            }
        }
Exemple #23
0
    //protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    private void Click()
    {
        string loginName;
        string passWord;
        string nikeName;
        string email;
        string phone;
        string zone;
        string country;
        string mobile;
        string company;
        string contactname;
        string contacttitle;
        string propertyid;
        string invite;      //邀请人

        //string intent;//意向
        //string question;
        //string answer;



        loginName    = this.usrname.Value;
        passWord     = Request.Form["repwd"];
        nikeName     = Request.Form["nikename"];
        email        = Request.Form["email"];
        phone        = Request.Form["phone"];
        zone         = Request.Form["zone"];
        country      = Request.Form["country"];
        mobile       = Request.Form["mobile"];
        company      = Request.Form["company"];
        contactname  = Request.Form["contactname"];
        contacttitle = Request.Form["contacttitle"];
        propertyid   = Request.Form["propertyid"];



        invite = Request.Form["invite"];
        //intent = Request.Form["intent"];
        //question = Request.Form["question"];
        //answer = Request.Form["answer"];

        phone = country + "-" + zone + "-" + phone;

        //注册信息
        SHA1 sha1 = SHA1.Create();

        byte[] passWord2 = sha1.ComputeHash(Encoding.Unicode.GetBytes(passWord.Trim()));

        LoginInfoModel model = new LoginInfoModel();

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

            model.autoReg = 2;
        }

        model.LoginName = loginName;
        model.Password  = passWord2;
        model.NickName  = nikeName;
        //model.PWDAnswere = answer;
        //model.PWDQuestion = question;
        model.RoleName      = "0";//会员
        model.ManageTypeID  = "2003";
        model.MemberGradeID = "1001";
        model.IsCheckUp     = false;
        model.Email         = email;
        model.Tel           = phone;
        model.CompanyName   = company;
        model.ContactName   = contactname;
        model.ContactTitle  = contacttitle;
        model.PropertyID    = Int32.Parse(propertyid);
        //model.RequirInfo = intent;

        //--------会员信息
        MemberInfoModel memberModel = new MemberInfoModel();

        memberModel.LoginName    = loginName;
        memberModel.ManageTypeID = "2003";
        memberModel.NickName     = nikeName;
        memberModel.Email        = email;
        memberModel.Tel          = phone;
        //memberModel.RequirInfo = intent;
        memberModel.Mobile   = mobile;
        memberModel.Birthday = DateTime.Now;

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


        LoginInfoBLL loginfo = new LoginInfoBLL();

        MemberInfoBLL member = new MemberInfoBLL();
        try
        {
            //向注册表写数据

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

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

            //论坛会员注册
            if (i > 0)
            {
                BBS_Reg.Reg(nikeName, passWord, email);
            }
            //邀请注册

            //if (invite.Trim().Length > 0)
            //{
            //    loginfo.InviterRegiste(Request.UserHostAddress, email, invite);
            //}
            //添加邀请人
            //if (loginName.Trim() != "" && invite.Trim() != "")
            //{
            //   // AdSystem.Introducer ad = new AdSystem.Introducer();
            //  //  ad.AddIntroducer(loginName, invite);
            //}

            string encryEmail   = Server.UrlEncode(DEncrypt.Encrypt(email));
            string encryLogname = Server.UrlEncode(DEncrypt.Encrypt(loginName));
            string act          = Server.UrlEncode(DEncrypt.Encrypt("register"));
            string strPass      = Server.UrlEncode(DEncrypt.Encrypt(passWord));
            string ValidUrl     = "RegisterSuccessProject.aspx?email=" + encryEmail + "&logname=" + encryLogname + "&act=" + act + "&PassWord="******"register"));
            string strPass      = Server.UrlEncode(DEncrypt.Encrypt(passWord));
            string ValidUrl     = "RegisterSuccessProject.aspx?email=" + encryEmail + "&logname=" + encryLogname + "&act=" + act + "&PassWord=" + strPass;
            Response.Redirect(ValidUrl, true);
        }
    }
Exemple #24
0
        /// <summary>
        /// 获取Hash后的字节数组
        /// </summary>
        /// <param name="type">哈希类型</param>
        /// <param name="key">key</param>
        /// <param name="bytes">原字节数组</param>
        /// <returns></returns>
        public static byte[] GetHashedBytes(HashType type, byte[] bytes, byte[] key)
        {
            if (null == bytes)
            {
                return(bytes);
            }

            HashAlgorithm algorithm = null;

            try
            {
                if (key == null)
                {
                    switch (type)
                    {
                    case HashType.MD5:
                        algorithm = MD5.Create();
                        break;

                    case HashType.SHA1:
                        algorithm = SHA1.Create();
                        break;

                    case HashType.SHA256:
                        algorithm = SHA256.Create();
                        break;

                    case HashType.SHA384:
                        algorithm = SHA384.Create();
                        break;

                    case HashType.SHA512:
                        algorithm = SHA512.Create();
                        break;

                    default:
                        algorithm = MD5.Create();
                        break;
                    }
                }
                else
                {
                    switch (type)
                    {
                    case HashType.MD5:
                        algorithm = new HMACMD5(key);
                        break;

                    case HashType.SHA1:
                        algorithm = new HMACSHA1(key);
                        break;

                    case HashType.SHA256:
                        algorithm = new HMACSHA256(key);
                        break;

                    case HashType.SHA384:
                        algorithm = new HMACSHA384(key);
                        break;

                    case HashType.SHA512:
                        algorithm = new HMACSHA512(key);
                        break;

                    default:
                        algorithm = new HMACMD5(key);
                        break;
                    }
                }
                return(algorithm.ComputeHash(bytes));
            }
            finally
            {
                algorithm?.Dispose();
            }
        }
Exemple #25
0
 /// <summary>
 /// SHA1 加密
 /// </summary>
 /// <param name="input"> 要加密的字符串 </param>
 /// <param name="encoding"> 字符编码 </param>
 /// <returns></returns>
 public static string Sha1Encrypt(string input, Encoding encoding)
 {
     return(HashEncrypt(SHA1.Create(), input, encoding));
 }
Exemple #26
0
        private void ExecuteOp(OpCode opcode, ExecutionContext context)
        {
            lastOpcode = opcode;

            if (opcode > OpCode.PUSH16 && opcode != OpCode.RET && context.PushOnly)
            {
                State |= VMState.FAULT;
                return;
            }
            if (opcode >= OpCode.PUSHBYTES1 && opcode <= OpCode.PUSHBYTES75)
            {
                EvaluationStack.Push(context.OpReader.ReadBytes((byte)opcode));
            }
            else
            {
                switch (opcode)
                {
                // Push value
                case OpCode.PUSH0:
                    EvaluationStack.Push(new byte[0]);
                    break;

                case OpCode.PUSHDATA1:
                    EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadByte()));
                    break;

                case OpCode.PUSHDATA2:
                    EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadUInt16()));
                    break;

                case OpCode.PUSHDATA4:
                    EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadInt32()));
                    break;

                case OpCode.PUSHM1:
                case OpCode.PUSH1:
                case OpCode.PUSH2:
                case OpCode.PUSH3:
                case OpCode.PUSH4:
                case OpCode.PUSH5:
                case OpCode.PUSH6:
                case OpCode.PUSH7:
                case OpCode.PUSH8:
                case OpCode.PUSH9:
                case OpCode.PUSH10:
                case OpCode.PUSH11:
                case OpCode.PUSH12:
                case OpCode.PUSH13:
                case OpCode.PUSH14:
                case OpCode.PUSH15:
                case OpCode.PUSH16:
                    EvaluationStack.Push((int)opcode - (int)OpCode.PUSH1 + 1);
                    break;

                // Control
                case OpCode.NOP:
                    break;

                case OpCode.JMP:
                case OpCode.JMPIF:
                case OpCode.JMPIFNOT:
                {
                    int offset = context.OpReader.ReadInt16();
                    offset = context.InstructionPointer + offset - 3;
                    if (offset < 0 || offset > context.Script.Length)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    bool fValue = true;
                    if (opcode > OpCode.JMP)
                    {
                        fValue = EvaluationStack.Pop().GetBoolean();
                        if (opcode == OpCode.JMPIFNOT)
                        {
                            fValue = !fValue;
                        }
                    }
                    if (fValue)
                    {
                        context.InstructionPointer = offset;
                    }
                }
                break;

                case OpCode.CALL:
                    InvocationStack.Push(context.Clone());
                    context.InstructionPointer += 2;
                    ExecuteOp(OpCode.JMP, CurrentContext);
                    break;

                case OpCode.RET:
                    InvocationStack.Pop().Dispose();
                    if (InvocationStack.Count == 0)
                    {
                        State |= VMState.HALT;
                    }
                    break;

                case OpCode.APPCALL:
                case OpCode.TAILCALL:
                {
                    if (table == null)
                    {
                        State |= VMState.FAULT;
                        return;
                    }

                    byte[] script_hash = context.OpReader.ReadBytes(20);
                    if (script_hash.All(p => p == 0))
                    {
                        script_hash = EvaluationStack.Pop().GetByteArray();
                    }

                    byte[] script = table.GetScript(script_hash);
                    if (script == null)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    if (opcode == OpCode.TAILCALL)
                    {
                        InvocationStack.Pop().Dispose();
                    }
                    LoadScript(script);
                }
                break;

                case OpCode.SYSCALL:

                    lastSysCall = Encoding.ASCII.GetString(context.OpReader.ReadVarBytes(252));
                    if (!service.Invoke(lastSysCall, this))
                    {
                        State |= VMState.FAULT;
                    }
                    break;

                // Stack ops
                case OpCode.DUPFROMALTSTACK:
                    EvaluationStack.Push(AltStack.Peek());
                    break;

                case OpCode.TOALTSTACK:
                    AltStack.Push(EvaluationStack.Pop());
                    break;

                case OpCode.FROMALTSTACK:
                    EvaluationStack.Push(AltStack.Pop());
                    break;

                case OpCode.XDROP:
                {
                    int n = (int)EvaluationStack.Pop().GetBigInteger();
                    if (n < 0)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    EvaluationStack.Remove(n);
                }
                break;

                case OpCode.XSWAP:
                {
                    int n = (int)EvaluationStack.Pop().GetBigInteger();
                    if (n < 0)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    if (n == 0)
                    {
                        break;
                    }
                    StackItem xn = EvaluationStack.Peek(n);
                    EvaluationStack.Set(n, EvaluationStack.Peek());
                    EvaluationStack.Set(0, xn);
                }
                break;

                case OpCode.XTUCK:
                {
                    int n = (int)EvaluationStack.Pop().GetBigInteger();
                    if (n <= 0)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    EvaluationStack.Insert(n, EvaluationStack.Peek());
                }
                break;

                case OpCode.DEPTH:
                    EvaluationStack.Push(EvaluationStack.Count);
                    break;

                case OpCode.DROP:
                    EvaluationStack.Pop();
                    break;

                case OpCode.DUP:
                    EvaluationStack.Push(EvaluationStack.Peek());
                    break;

                case OpCode.NIP:
                {
                    StackItem x2 = EvaluationStack.Pop();
                    EvaluationStack.Pop();
                    EvaluationStack.Push(x2);
                }
                break;

                case OpCode.OVER:
                {
                    StackItem x2 = EvaluationStack.Pop();
                    StackItem x1 = EvaluationStack.Peek();
                    EvaluationStack.Push(x2);
                    EvaluationStack.Push(x1);
                }
                break;

                case OpCode.PICK:
                {
                    int n = (int)EvaluationStack.Pop().GetBigInteger();
                    if (n < 0)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    EvaluationStack.Push(EvaluationStack.Peek(n));
                }
                break;

                case OpCode.ROLL:
                {
                    int n = (int)EvaluationStack.Pop().GetBigInteger();
                    if (n < 0)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    if (n == 0)
                    {
                        break;
                    }
                    EvaluationStack.Push(EvaluationStack.Remove(n));
                }
                break;

                case OpCode.ROT:
                {
                    StackItem x3 = EvaluationStack.Pop();
                    StackItem x2 = EvaluationStack.Pop();
                    StackItem x1 = EvaluationStack.Pop();
                    EvaluationStack.Push(x2);
                    EvaluationStack.Push(x3);
                    EvaluationStack.Push(x1);
                }
                break;

                case OpCode.SWAP:
                {
                    StackItem x2 = EvaluationStack.Pop();
                    StackItem x1 = EvaluationStack.Pop();
                    EvaluationStack.Push(x2);
                    EvaluationStack.Push(x1);
                }
                break;

                case OpCode.TUCK:
                {
                    StackItem x2 = EvaluationStack.Pop();
                    StackItem x1 = EvaluationStack.Pop();
                    EvaluationStack.Push(x2);
                    EvaluationStack.Push(x1);
                    EvaluationStack.Push(x2);
                }
                break;

                case OpCode.CAT:
                {
                    byte[] x2 = EvaluationStack.Pop().GetByteArray();
                    byte[] x1 = EvaluationStack.Pop().GetByteArray();
                    EvaluationStack.Push(x1.Concat(x2).ToArray());
                }
                break;

                case OpCode.SUBSTR:
                {
                    int count = (int)EvaluationStack.Pop().GetBigInteger();
                    if (count < 0)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    int index = (int)EvaluationStack.Pop().GetBigInteger();
                    if (index < 0)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    byte[] x = EvaluationStack.Pop().GetByteArray();
                    EvaluationStack.Push(x.Skip(index).Take(count).ToArray());
                }
                break;

                case OpCode.LEFT:
                {
                    int count = (int)EvaluationStack.Pop().GetBigInteger();
                    if (count < 0)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    byte[] x = EvaluationStack.Pop().GetByteArray();
                    EvaluationStack.Push(x.Take(count).ToArray());
                }
                break;

                case OpCode.RIGHT:
                {
                    int count = (int)EvaluationStack.Pop().GetBigInteger();
                    if (count < 0)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    byte[] x = EvaluationStack.Pop().GetByteArray();
                    if (x.Length < count)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    EvaluationStack.Push(x.Skip(x.Length - count).ToArray());
                }
                break;

                case OpCode.SIZE:
                {
                    byte[] x = EvaluationStack.Pop().GetByteArray();
                    EvaluationStack.Push(x.Length);
                }
                break;

                // Bitwise logic
                case OpCode.INVERT:
                {
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(~x);
                }
                break;

                case OpCode.AND:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 & x2);
                }
                break;

                case OpCode.OR:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 | x2);
                }
                break;

                case OpCode.XOR:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 ^ x2);
                }
                break;

                case OpCode.EQUAL:
                {
                    StackItem x2 = EvaluationStack.Pop();
                    StackItem x1 = EvaluationStack.Pop();
                    EvaluationStack.Push(x1.Equals(x2));
                }
                break;

                // Numeric
                case OpCode.INC:
                {
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x + 1);
                }
                break;

                case OpCode.DEC:
                {
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x - 1);
                }
                break;

                case OpCode.SIGN:
                {
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x.Sign);
                }
                break;

                case OpCode.NEGATE:
                {
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(-x);
                }
                break;

                case OpCode.ABS:
                {
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(BigInteger.Abs(x));
                }
                break;

                case OpCode.NOT:
                {
                    bool x = EvaluationStack.Pop().GetBoolean();
                    EvaluationStack.Push(!x);
                }
                break;

                case OpCode.NZ:
                {
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x != BigInteger.Zero);
                }
                break;

                case OpCode.ADD:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 + x2);
                }
                break;

                case OpCode.SUB:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 - x2);
                }
                break;

                case OpCode.MUL:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 * x2);
                }
                break;

                case OpCode.DIV:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 / x2);
                }
                break;

                case OpCode.MOD:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 % x2);
                }
                break;

                case OpCode.SHL:
                {
                    int        n = (int)EvaluationStack.Pop().GetBigInteger();
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x << n);
                }
                break;

                case OpCode.SHR:
                {
                    int        n = (int)EvaluationStack.Pop().GetBigInteger();
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x >> n);
                }
                break;

                case OpCode.BOOLAND:
                {
                    bool x2 = EvaluationStack.Pop().GetBoolean();
                    bool x1 = EvaluationStack.Pop().GetBoolean();
                    EvaluationStack.Push(x1 && x2);
                }
                break;

                case OpCode.BOOLOR:
                {
                    bool x2 = EvaluationStack.Pop().GetBoolean();
                    bool x1 = EvaluationStack.Pop().GetBoolean();
                    EvaluationStack.Push(x1 || x2);
                }
                break;

                case OpCode.NUMEQUAL:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 == x2);
                }
                break;

                case OpCode.NUMNOTEQUAL:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 != x2);
                }
                break;

                case OpCode.LT:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 < x2);
                }
                break;

                case OpCode.GT:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 > x2);
                }
                break;

                case OpCode.LTE:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 <= x2);
                }
                break;

                case OpCode.GTE:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(x1 >= x2);
                }
                break;

                case OpCode.MIN:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(BigInteger.Min(x1, x2));
                }
                break;

                case OpCode.MAX:
                {
                    BigInteger x2 = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x1 = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(BigInteger.Max(x1, x2));
                }
                break;

                case OpCode.WITHIN:
                {
                    BigInteger b = EvaluationStack.Pop().GetBigInteger();
                    BigInteger a = EvaluationStack.Pop().GetBigInteger();
                    BigInteger x = EvaluationStack.Pop().GetBigInteger();
                    EvaluationStack.Push(a <= x && x < b);
                }
                break;

                // Crypto
                case OpCode.SHA1:
                    using (SHA1 sha = SHA1.Create())
                    {
                        byte[] x = EvaluationStack.Pop().GetByteArray();
                        EvaluationStack.Push(sha.ComputeHash(x));
                    }
                    break;

                case OpCode.SHA256:
                    using (SHA256 sha = SHA256.Create())
                    {
                        byte[] x = EvaluationStack.Pop().GetByteArray();
                        EvaluationStack.Push(sha.ComputeHash(x));
                    }
                    break;

                case OpCode.HASH160:
                {
                    byte[] x = EvaluationStack.Pop().GetByteArray();
                    EvaluationStack.Push(CryptoUtils.Hash160(x));
                }
                break;

                case OpCode.HASH256:
                {
                    byte[] x = EvaluationStack.Pop().GetByteArray();
                    EvaluationStack.Push(CryptoUtils.Hash256(x));
                }
                break;

                case OpCode.CHECKSIG:
                {
                    byte[] pubkey    = EvaluationStack.Pop().GetByteArray();
                    byte[] signature = EvaluationStack.Pop().GetByteArray();
                    try
                    {
                        EvaluationStack.Push(CryptoUtils.VerifySignature(ScriptContainer.GetMessage(), signature, pubkey));
                    }
                    catch (ArgumentException)
                    {
                        EvaluationStack.Push(false);
                    }
                }
                break;

                case OpCode.CHECKMULTISIG:
                {
                    int       n;
                    byte[][]  pubkeys;
                    StackItem item = EvaluationStack.Pop();
                    if (item is VMArray array1)
                    {
                        pubkeys = array1.Select(p => p.GetByteArray()).ToArray();
                        n       = pubkeys.Length;
                        if (n == 0)
                        {
                            State |= VMState.FAULT;
                            return;
                        }
                    }
                    else
                    {
                        n = (int)item.GetBigInteger();
                        if (n < 1 || n > EvaluationStack.Count)
                        {
                            State |= VMState.FAULT;
                            return;
                        }
                        pubkeys = new byte[n][];
                        for (int i = 0; i < n; i++)
                        {
                            pubkeys[i] = EvaluationStack.Pop().GetByteArray();
                        }
                    }
                    int      m;
                    byte[][] signatures;
                    item = EvaluationStack.Pop();
                    if (item is VMArray array2)
                    {
                        signatures = array2.Select(p => p.GetByteArray()).ToArray();
                        m          = signatures.Length;
                        if (m == 0 || m > n)
                        {
                            State |= VMState.FAULT;
                            return;
                        }
                    }
                    else
                    {
                        m = (int)item.GetBigInteger();
                        if (m < 1 || m > n || m > EvaluationStack.Count)
                        {
                            State |= VMState.FAULT;
                            return;
                        }
                        signatures = new byte[m][];
                        for (int i = 0; i < m; i++)
                        {
                            signatures[i] = EvaluationStack.Pop().GetByteArray();
                        }
                    }
                    byte[] message  = ScriptContainer.GetMessage();
                    bool   fSuccess = true;
                    try
                    {
                        for (int i = 0, j = 0; fSuccess && i < m && j < n;)
                        {
                            if (CryptoUtils.VerifySignature(message, signatures[i], pubkeys[j]))
                            {
                                i++;
                            }
                            j++;
                            if (m - i > n - j)
                            {
                                fSuccess = false;
                            }
                        }
                    }
                    catch (ArgumentException)
                    {
                        fSuccess = false;
                    }
                    EvaluationStack.Push(fSuccess);
                }
                break;

                // Array
                case OpCode.ARRAYSIZE:
                {
                    StackItem item = EvaluationStack.Pop();
                    if (item is ICollection collection)
                    {
                        EvaluationStack.Push(collection.Count);
                    }
                    else
                    {
                        EvaluationStack.Push(item.GetByteArray().Length);
                    }
                }
                break;

                case OpCode.PACK:
                {
                    int size = (int)EvaluationStack.Pop().GetBigInteger();
                    if (size < 0 || size > EvaluationStack.Count)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    List <StackItem> items = new List <StackItem>(size);
                    for (int i = 0; i < size; i++)
                    {
                        items.Add(EvaluationStack.Pop());
                    }
                    EvaluationStack.Push(items);
                }
                break;

                case OpCode.UNPACK:
                {
                    StackItem item = EvaluationStack.Pop();
                    if (item is VMArray array)
                    {
                        for (int i = array.Count - 1; i >= 0; i--)
                        {
                            EvaluationStack.Push(array[i]);
                        }
                        EvaluationStack.Push(array.Count);
                    }
                    else
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                }
                break;

                case OpCode.PICKITEM:
                {
                    StackItem key = EvaluationStack.Pop();
                    if (key is ICollection)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    switch (EvaluationStack.Pop())
                    {
                    case VMArray array:
                        int index = (int)key.GetBigInteger();
                        if (index < 0 || index >= array.Count)
                        {
                            State |= VMState.FAULT;
                            return;
                        }
                        EvaluationStack.Push(array[index]);
                        break;

                    case Map map:
                        if (map.TryGetValue(key, out StackItem value))
                        {
                            EvaluationStack.Push(value);
                        }
                        else
                        {
                            State |= VMState.FAULT;
                            return;
                        }
                        break;

                    default:
                        State |= VMState.FAULT;
                        return;
                    }
                }
                break;

                case OpCode.SETITEM:
                {
                    StackItem value = EvaluationStack.Pop();
                    if (value is Struct s)
                    {
                        value = s.Clone();
                    }
                    StackItem key = EvaluationStack.Pop();
                    if (key is ICollection)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    switch (EvaluationStack.Pop())
                    {
                    case VMArray array:
                        int index = (int)key.GetBigInteger();
                        if (index < 0 || index >= array.Count)
                        {
                            State |= VMState.FAULT;
                            return;
                        }
                        array[index] = value;
                        break;

                    case Map map:
                        map[key] = value;
                        break;

                    default:
                        State |= VMState.FAULT;
                        return;
                    }
                }
                break;

                case OpCode.NEWARRAY:
                {
                    int count = (int)EvaluationStack.Pop().GetBigInteger();
                    List <StackItem> items = new List <StackItem>(count);
                    for (var i = 0; i < count; i++)
                    {
                        items.Add(false);
                    }
                    EvaluationStack.Push(new Types.Array(items));
                }
                break;

                case OpCode.NEWSTRUCT:
                {
                    int count = (int)EvaluationStack.Pop().GetBigInteger();
                    List <StackItem> items = new List <StackItem>(count);
                    for (var i = 0; i < count; i++)
                    {
                        items.Add(false);
                    }
                    EvaluationStack.Push(new VM.Types.Struct(items));
                }
                break;

                case OpCode.NEWMAP:
                    EvaluationStack.Push(new Map());
                    break;

                case OpCode.APPEND:
                {
                    StackItem newItem = EvaluationStack.Pop();
                    if (newItem is Types.Struct s)
                    {
                        newItem = s.Clone();
                    }
                    StackItem arrItem = EvaluationStack.Pop();
                    if (arrItem is VMArray array)
                    {
                        array.Add(newItem);
                    }
                    else
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                }
                break;

                case OpCode.REVERSE:
                {
                    StackItem arrItem = EvaluationStack.Pop();
                    if (arrItem is VMArray array)
                    {
                        array.Reverse();
                    }
                    else
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                }
                break;

                case OpCode.REMOVE:
                {
                    StackItem key = EvaluationStack.Pop();
                    if (key is ICollection)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    switch (EvaluationStack.Pop())
                    {
                    case VMArray array:
                        int index = (int)key.GetBigInteger();
                        if (index < 0 || index >= array.Count)
                        {
                            State |= VMState.FAULT;
                            return;
                        }
                        array.RemoveAt(index);
                        break;

                    case Map map:
                        map.Remove(key);
                        break;

                    default:
                        State |= VMState.FAULT;
                        return;
                    }
                }
                break;

                case OpCode.HASKEY:
                {
                    StackItem key = EvaluationStack.Pop();
                    if (key is ICollection)
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    switch (EvaluationStack.Pop())
                    {
                    case VMArray array:
                        int index = (int)key.GetBigInteger();
                        if (index < 0)
                        {
                            State |= VMState.FAULT;
                            return;
                        }
                        EvaluationStack.Push(index < array.Count);
                        break;

                    case Map map:
                        EvaluationStack.Push(map.ContainsKey(key));
                        break;

                    default:
                        State |= VMState.FAULT;
                        return;
                    }
                }
                break;

                case OpCode.KEYS:
                    switch (EvaluationStack.Pop())
                    {
                    case Map map:
                        EvaluationStack.Push(new VMArray(map.Keys));
                        break;

                    default:
                        State |= VMState.FAULT;
                        return;
                    }
                    break;

                case OpCode.VALUES:
                {
                    ICollection <StackItem> values;
                    switch (EvaluationStack.Pop())
                    {
                    case VMArray array:
                        values = array;
                        break;

                    case Map map:
                        values = map.Values;
                        break;

                    default:
                        State |= VMState.FAULT;
                        return;
                    }
                    List <StackItem> newArray = new List <StackItem>(values.Count);
                    foreach (StackItem item in values)
                    {
                        if (item is Struct s)
                        {
                            newArray.Add(s.Clone());
                        }
                        else
                        {
                            newArray.Add(item);
                        }
                    }
                    EvaluationStack.Push(new VMArray(newArray));
                }
                break;

                // Exceptions
                case OpCode.THROW:
                    State |= VMState.FAULT;
                    return;

                case OpCode.THROWIFNOT:
                    if (!EvaluationStack.Pop().GetBoolean())
                    {
                        State |= VMState.FAULT;
                        return;
                    }
                    break;

                default:
                    State |= VMState.FAULT;
                    return;
                }
            }
            if (!State.HasFlag(VMState.FAULT) && InvocationStack.Count > 0)
            {
                if (CurrentContext.BreakPoints.Contains((uint)CurrentContext.InstructionPointer))
                {
                    State |= VMState.BREAK;
                }
            }
        }
Exemple #27
0
        public static object CreateFromName(string name)
        {
            switch (name)
            {
            case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315":
                return(new XmlDsigC14NTransform());

            case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments":
                return(new XmlDsigC14NWithCommentsTransform());

            case "http://www.w3.org/2001/10/xml-exc-c14n#":
                return(new XmlDsigExcC14NTransform());

            case "http://www.w3.org/2001/10/xml-exc-c14n#WithComments":
                return(new XmlDsigExcC14NWithCommentsTransform());

            case "http://www.w3.org/2000/09/xmldsig#base64":
                return(new XmlDsigBase64Transform());

            case "http://www.w3.org/TR/1999/REC-xpath-19991116":
                return(new XmlDsigXPathTransform());

            case "http://www.w3.org/TR/1999/REC-xslt-19991116":
                return(new XmlDsigXsltTransform());

            case "http://www.w3.org/2000/09/xmldsig#enveloped-signature":
                return(new XmlDsigEnvelopedSignatureTransform());

            case "http://www.w3.org/2002/07/decrypt#XML":
                return(new XmlDecryptionTransform());

            case "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform":
                return(new XmlLicenseTransform());

            case "http://www.w3.org/2000/09/xmldsig# X509Data":
                return(new KeyInfoX509Data());

            case "http://www.w3.org/2000/09/xmldsig# KeyName":
                return(new KeyInfoName());

            case "http://www.w3.org/2000/09/xmldsig# KeyValue/DSAKeyValue":
                return(new DSAKeyValue());

            case "http://www.w3.org/2000/09/xmldsig# KeyValue/RSAKeyValue":
                return(new RSAKeyValue());

            case "http://www.w3.org/2000/09/xmldsig# RetrievalMethod":
                return(new KeyInfoRetrievalMethod());

            case "http://www.w3.org/2001/04/xmlenc# EncryptedKey":
                return(new KeyInfoEncryptedKey());

            case "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160":
                throw new NotImplementedException(name);

            //return new System.Security.Cryptography.HMACRIPEMD160();
            case "http://www.w3.org/2000/09/xmldsig#dsa-sha1":
                return(new DSASignatureDescription());

            case "System.Security.Cryptography.DSASignatureDescription":
                throw new NotImplementedException(name);

            //return new DSASignatureDescription();
            case "http://www.w3.org/2000/09/xmldsig#rsa-sha1":
                return(new RSAPKCS1SHA1SignatureDescription());

            case "System.Security.Cryptography.RSASignatureDescription":
                return(new RSAPKCS1SHA1SignatureDescription());

            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256":
                return(new RSAPKCS1SHA256SignatureDescription());

            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384":
                return(new RSAPKCS1SHA384SignatureDescription());

            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512":
                return(new RSAPKCS1SHA512SignatureDescription());

            // workarounds for issue https://github.com/dotnet/corefx/issues/16563
            // remove attribute from this method when removing them
            case "http://www.w3.org/2000/09/xmldsig#sha1":
                return(SHA1.Create());
            }

            return(CryptoConfig.CreateFromName(name));
        }
Exemple #28
0
        private HttpResponse pdf(HttpRequest req)
        {
            ensureModuleInfoCache();

            string lastExaminedPdfFile = "<none>";

            try
            {
                if (!_pdfEnabled)
                {
                    return(HttpResponse.PlainText("This feature is temporarily disabled because it didn’t work for most people."));
                }

                if (req.Method != HttpMethod.Post)
                {
                    return(HttpResponse.Redirect(req.Url.WithPathParent().WithPath("")));
                }

                var json                   = JsonValue.Parse(req.Post["json"].Value);
                var pdfs                   = new List <string>();
                var keywords               = json["search"].GetString().Length == 0 ? null : json["search"].GetString().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                var searchOptions          = json["searchOptions"].GetList().Select(j => j.GetString()).ToArray();
                var filterEnabledByProfile = json["filterEnabledByProfile"].GetBool();
                var filterVetoedByProfile  = json["filterVetoedByProfile"].GetBool();
                var profileVetoList        = (filterEnabledByProfile == filterVetoedByProfile) ? null : json["profileVetoList"]?.GetList().Select(j => j.GetString()).ToArray();

                // Filter
                var matchingModules = _moduleInfoCache.Modules.Where(m =>
                {
                    if (profileVetoList != null && !(profileVetoList.Contains(m.ModuleID) ? filterVetoedByProfile : filterEnabledByProfile))
                    {
                        return(false);
                    }

                    foreach (var filter in _filters)
                    {
                        if (!filter.Matches(m, json["filter"].Safe[filter.PropName].GetDictSafe()))
                        {
                            return(false);
                        }
                    }

                    return(keywords == null ||
                           (searchOptions.Contains("names") && keywords.All(k => m.Name.ContainsNoCase(k))) ||
                           (searchOptions.Contains("authors") && keywords.All(k => m.Author.ContainsNoCase(k))) ||
                           (searchOptions.Contains("descriptions") && keywords.All(k => m.Description.ContainsNoCase(k))));
                });

                // Sort
                switch (json["sort"].GetString())
                {
                case "name": matchingModules = matchingModules.OrderBy(m => m.SortKey); break;

                case "defdiff": matchingModules = matchingModules.OrderBy(m => m.DefuserDifficulty); break;

                case "expdiff": matchingModules = matchingModules.OrderBy(m => m.ExpertDifficulty); break;

                case "published": matchingModules = matchingModules.OrderByDescending(m => m.Published); break;
                }

                var pdfFiles = new List <string>();

                foreach (var module in matchingModules)
                {
                    var filename = $"{module.Name}.pdf";
                    var fullPath = Path.Combine(_config.BaseDir, _config.PdfDir, filename);
                    if (json["preferredManuals"].ContainsKey(module.Name))
                    {
                        var pref = json["preferredManuals"][module.Name].GetString();
                        var preferredFilename = Regex.Replace(pref, @" \((?:PDF|HTML)\)$", ".pdf");
                        var preferredFullPath = Path.Combine(_config.BaseDir, _config.PdfDir, preferredFilename);
                        if (File.Exists(preferredFullPath))
                        {
                            fullPath = preferredFullPath;
                            filename = preferredFilename;
                        }
                    }
                    if (File.Exists(fullPath))
                    {
                        pdfFiles.Add(filename);
                    }
                }

                if (pdfFiles.Count == 0)
                {
                    return(HttpResponse.PlainText("Error: no matching PDF files found.", HttpStatusCode._500_InternalServerError));
                }

                var list = pdfFiles.JoinString("\n");
                using (var mem = new MemoryStream(list.ToUtf8()))
                {
                    var sha1    = SHA1.Create().ComputeHash(mem).ToHex();
                    var pdfPath = Path.Combine(_config.BaseDir, _config.MergedPdfsDir, $"{sha1}.pdf");
                    if (!File.Exists(pdfPath))
                    {
                        lock (this)
                            if (!File.Exists(pdfPath))
                            {
                                var mergedPdf = new PdfDocument();
                                foreach (var pdfFile in pdfFiles)
                                {
                                    lastExaminedPdfFile = pdfFile;
                                    var pdf   = PdfReader.Open(Path.Combine(_config.BaseDir, _config.PdfDir, pdfFile), PdfDocumentOpenMode.Import);
                                    int count = pdf.PageCount;
                                    for (int idx = 0; idx < count; idx++)
                                    {
                                        mergedPdf.AddPage(pdf.Pages[idx]);
                                    }
                                }
                                using (var f = File.OpenWrite(pdfPath))
                                    mergedPdf.Save(f);
                            }
                    }
                    return(HttpResponse.Redirect(req.Url.WithPathParent().WithPathOnly($"/MergedPdfs/{sha1}.pdf")));
                }
            }
            catch (Exception e)
            {
                var exc = e;
                var sb  = new StringBuilder();
                while (exc != null)
                {
                    sb.AppendLine($"Error processing PDFs:\r\n{e.GetType().FullName}\r\n{e.Message}\r\nPossible culprit: {lastExaminedPdfFile}\r\n\r\n{e.StackTrace}\r\n\r\n");
                    exc = exc.InnerException;
                }
                return(HttpResponse.PlainText(sb.ToString(), HttpStatusCode._500_InternalServerError));
            }
        }
Exemple #29
0
        public static Mzml LoadAllStaticData(string filePath, FilteringParams filterParams = null, int maxThreads = -1)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException();
            }

            Loaders.LoadElements();

            Generated.mzMLType _mzMLConnection;

            try
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    var _indexedmzMLConnection = (Generated.indexedmzML)MzmlMethods.indexedSerializer.Deserialize(fs);
                    _mzMLConnection = _indexedmzMLConnection.mzML;
                }
            }
            catch
            {
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                    _mzMLConnection = (Generated.mzMLType)MzmlMethods.mzmlSerializer.Deserialize(fs);
            }

            SourceFile sourceFile;

            if (_mzMLConnection.fileDescription.sourceFileList != null && _mzMLConnection.fileDescription.sourceFileList.sourceFile != null && _mzMLConnection.fileDescription.sourceFileList.sourceFile[0] != null && _mzMLConnection.fileDescription.sourceFileList.sourceFile[0].cvParam != null)
            {
                var    simpler        = _mzMLConnection.fileDescription.sourceFileList.sourceFile[0];
                string nativeIdFormat = null;
                string fileFormat     = null;
                string checkSum       = null;
                string checkSumType   = null;
                foreach (var cv in simpler.cvParam)
                {
                    if (cv.accession.Equals(@"MS:1000563"))
                    {
                        fileFormat = "Thermo RAW format";
                    }
                    if (cv.accession.Equals(@"MS:1000584"))
                    {
                        fileFormat = "mzML format";
                    }

                    if (cv.accession.Equals(@"MS:1000768"))
                    {
                        nativeIdFormat = "Thermo nativeID format";
                    }
                    if (cv.accession.Equals(@"MS:1000776"))
                    {
                        nativeIdFormat = "scan number only nativeID format";
                    }
                    if (cv.accession.Equals(@"MS:1000824"))
                    {
                        nativeIdFormat = "no nativeID format";
                    }

                    if (cv.accession.Equals(@"MS:1000568"))
                    {
                        checkSum     = cv.value;
                        checkSumType = "MD5";
                    }
                    if (cv.accession.Equals(@"MS:1000569"))
                    {
                        checkSum     = cv.value;
                        checkSumType = "SHA-1";
                    }
                }

                sourceFile = new SourceFile(
                    nativeIdFormat,
                    fileFormat,
                    checkSum,
                    checkSumType,
                    new Uri(simpler.location),
                    simpler.id,
                    simpler.name);
            }
            else
            {
                string sendCheckSum;
                using (FileStream stream = File.OpenRead(filePath))
                {
                    SHA1   sha      = SHA1.Create();
                    byte[] checksum = sha.ComputeHash(stream);
                    sendCheckSum = BitConverter.ToString(checksum)
                                   .Replace("-", string.Empty);
                }
                sourceFile = new SourceFile(
                    @"no nativeID format",
                    @"mzML format",
                    sendCheckSum,
                    @"SHA-1",
                    Path.GetFullPath(filePath),
                    Path.GetFileNameWithoutExtension(filePath));
            }

            var numSpecta = _mzMLConnection.run.spectrumList.spectrum.Length;

            MsDataScan[] scans = new MsDataScan[numSpecta];

            Parallel.ForEach(Partitioner.Create(0, numSpecta), new ParallelOptions {
                MaxDegreeOfParallelism = maxThreads
            }, fff =>
            {
                for (int i = fff.Item1; i < fff.Item2; i++)
                {
                    scans[i] = GetMsDataOneBasedScanFromConnection(_mzMLConnection, i + 1, filterParams);
                }
            });

            scans = scans.Where(s => s.MassSpectrum != null).ToArray();

            //Mzml sometimes have scan numbers specified, but usually not.
            //In the event that they do, the iterator above unintentionally assigned them to an incorrect index.
            //Check to make sure that the scans are in order and that there are no duplicate scans
            HashSet <int> checkForDuplicateScans = new HashSet <int>();
            bool          ordered            = true;
            int           previousScanNumber = -1;

            foreach (MsDataScan scan in scans)
            {
                //check if no duplicates
                if (!checkForDuplicateScans.Add(scan.OneBasedScanNumber)) //returns false if the scan already exists
                {
                    throw new MzLibException("Scan number " + scan.OneBasedScanNumber.ToString() + " appeared multiple times in " + filePath);
                }
                //check if scans are in order
                if (previousScanNumber > scan.OneBasedScanNumber)
                {
                    ordered = false;
                }
                previousScanNumber = scan.OneBasedScanNumber;
            }

            if (!ordered) //reassign indexes if not ordered
            {
                MsDataScan[] indexedScans = new MsDataScan[checkForDuplicateScans.Max()];
                foreach (MsDataScan scan in scans)
                {
                    indexedScans[scan.OneBasedScanNumber - 1] = scan;
                }
                scans = indexedScans;
            }

            //make reference pervious ms1 scan
            // we weren't able to get the precursor scan number, so we'll have to guess;
            // loop back to find precursor scan
            // (assumed to be the first scan before this scan with an MS order of this scan's MS order - 1)
            // e.g., if this is an MS2 scan, find the first MS1 scan before this and assume that's the precursor scan
            for (int i = 0; i < scans.Length; i++)
            {
                if (scans[i].MsnOrder > 1 && scans[i].OneBasedPrecursorScanNumber == null)
                {
                    for (int j = i; j >= 0; j--)
                    {
                        if (scans[i].MsnOrder - scans[j].MsnOrder == 1)
                        {
                            scans[i].SetOneBasedPrecursorScanNumber(scans[j].OneBasedScanNumber);
                            break;
                        }
                    }
                }
            }

            return(new Mzml(scans, sourceFile));
        }
        public void TestFilesAllowedList()
        {
            RSAParameters key = new RSACryptoServiceProvider().ExportParameters(true);
            string        check;

            if (true)
            {
                List <string> files = new List <string>();
                files.AddRange(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.exe"));
                files.AddRange(Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll"));
                using (StringWriter sw = new StringWriter())
                {
                    foreach (string file in files)
                    {
                        byte[] hash = SHA1.Create().ComputeHash(File.ReadAllBytes(file));
                        sw.WriteLine("{0}:{1}", Path.GetFileName(file), Convert.ToBase64String(hash));
                    }

                    RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
                    csp.ImportParameters(key);
                    byte[] sig = csp.SignData(Encoding.UTF8.GetBytes(sw.ToString()), SHA1.Create());
                    sw.WriteLine(Convert.ToBase64String(sig));

                    check = sw.ToString();
                }
            }
            if (true)
            {
                Dictionary <string, string> files = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                foreach (string file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.exe"))
                {
                    files.Add(Path.GetFileName(file), file);
                }
                foreach (string file in Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll"))
                {
                    files.Add(Path.GetFileName(file), file);
                }

                string fileInfo = check.Substring(0, check.TrimEnd().Length - 172);
                string sigInfo  = check.Substring(fileInfo.Length);

                RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
                csp.ImportParameters(key);
                if (!csp.VerifyData(Encoding.UTF8.GetBytes(fileInfo), SHA1.Create(), Convert.FromBase64String(sigInfo)))
                {
                    throw new InvalidDataException();
                }

                using (StringReader rdr = new StringReader(fileInfo))
                {
                    char[] split = new char[] { ':' };
                    string line;
                    while (!String.IsNullOrEmpty(line = rdr.ReadLine()))
                    {
                        string[] l = line.Split(split, 2);
                        string   filepath;
                        if (!files.TryGetValue(l[0], out filepath))
                        {
                            throw new FileNotFoundException("Missing manifest file.", l[0]);
                        }

                        byte[] hash = SHA1.Create().ComputeHash(File.ReadAllBytes(filepath));
                        if (l[1] != Convert.ToBase64String(hash))
                        {
                            throw new InvalidDataException();
                        }

                        files.Remove(l[0]);
                    }
                }

                if (files.Count > 0)
                {
                    throw new InvalidDataException();
                }
            }
        }
Exemple #31
0
		public SHA1Cng ()
		{
			// note: we don't use SHA1.Create since CryptoConfig could, 
			// if set to use this class, result in a endless recursion
			hash = new SHA1Managed ();
		}
 public static string CalculateSecurityBody(string Key)
 {
     byte[] hash = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(Key + solt));
     return(Convert.ToBase64String(hash));
 }