Beispiel #1
0
        static Boolean RunWebDAVTests(WebDAVClient c)
        {
            autoResetEvent = new AutoResetEvent(false);

            // Generate unique string to test with.
            string basepath           = Path.GetRandomFileName() + '/';
            string copypath           = basepath + "copy/";
            string tempFilePath       = Path.GetTempFileName();
            string uploadTestFilePath = @"c:\windows\notepad.exe";
            //string uploadTestFilePath = @"c:\windows\explorer.exe";
            // string uploadTestFilePath = @"c:\windows\setuplog.txt";
            string uploadTestFileName = Path.GetFileName(uploadTestFilePath);

            c.CreateDirComplete += new CreateDirCompleteDel(c_CreateDirComplete);
            c.CreateDir(basepath);
            autoResetEvent.WaitOne();
            c.CreateDir(copypath);
            autoResetEvent.WaitOne();
            Debug.WriteLine("CreateDir passed");

            c.ListComplete += new ListCompleteDel(c_ListComplete);
            c.List(basepath);
            autoResetEvent.WaitOne();
            if (_files.Count != 1)
            {
                return(false);
            }
            Debug.WriteLine("List passed");

            c.UploadComplete += new UploadCompleteDel(c_UploadComplete);
            c.Upload(uploadTestFilePath, basepath + uploadTestFileName);
            autoResetEvent.WaitOne();
            Debug.WriteLine("Upload 1/2 passed");
            c.List(basepath);
            autoResetEvent.WaitOne();
            if (_files.Count != 2)
            {
                return(false);
            }
            Debug.WriteLine("Upload 2/2 passed");

            autoResetEvent      = new AutoResetEvent(false);
            c.DownloadComplete += new DownloadCompleteDel(c_DownloadComplete);
            c.Download(basepath + uploadTestFileName, tempFilePath);
            autoResetEvent.WaitOne();
            c.Download(basepath, @"c:\Users\iamedu\test");
            autoResetEvent.WaitOne();
            Debug.WriteLine("Download 1/2 passed");
            HashAlgorithm h = HashAlgorithm.Create("SHA1");

            byte[] localhash;
            byte[] remotehash;
            using (FileStream fs = new FileStream(uploadTestFilePath, FileMode.Open, FileAccess.Read))
            {
                localhash = h.ComputeHash(fs);
            }
            using (FileStream fs = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read))
            {
                remotehash = h.ComputeHash(fs);
            }
            for (int i = 0; i < localhash.Length; i++)
            {
                if (localhash[i] != remotehash[i])
                {
                    return(false);
                }
            }
            Debug.WriteLine("Download 2/2 passed");

            c.CopyComplete += new CopyCompleteDel(c_CopyComplete);
            c.Copy(basepath + uploadTestFileName, copypath + uploadTestFileName);
            autoResetEvent.WaitOne();
            c.MoveComplete += new MoveCompleteDel(c_MoveComplete);
            c.Move(basepath + uploadTestFileName, basepath + "moved" + uploadTestFileName);
            autoResetEvent.WaitOne();
            c.DeleteComplete += new DeleteCompleteDel(c_DeleteComplete);
            c.Delete(basepath + "moved" + uploadTestFileName);
            autoResetEvent.WaitOne();
            c.Delete(copypath + uploadTestFileName);
            autoResetEvent.WaitOne();
            c.Delete(copypath);
            autoResetEvent.WaitOne();
            Debug.WriteLine("Delete 1/2 passed");

            c.List(basepath);
            autoResetEvent.WaitOne();
            if (_files.Count != 0)
            {
                return(false);
            }
            c.Delete(basepath);
            autoResetEvent.WaitOne();
            Debug.WriteLine("Delete 2/2 passed");

            return(true);
        }
Beispiel #2
0
        internal static SharedFile ShareFile(string filePath, string hashAlgo, BitChat chat, SynchronizationContext syncCxt)
        {
            FileStream fS = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);

            HashAlgorithm hash     = HashAlgorithm.Create(hashAlgo);
            int           hashSize = hash.HashSize / 8;

            //calculate block size
            int blockSize;
            {
                //header size = ChatMessage header + FileAdvertisement header
                int packetHeaderSize    = (20 + 1 + 2) + (1 + 1 + 255 + 1 + 255 + 8 + 8 + 4 + 1 + 10 + 1);
                int packetDataSize      = 65536 - packetHeaderSize;
                int totalBlocksPossible = packetDataSize / hashSize;
                blockSize = Convert.ToInt32(fS.Length / totalBlocksPossible);

                if (blockSize <= short.MaxValue)
                {
                    blockSize = short.MaxValue + 1;
                }
                else
                {
                    //align to 16 bytes
                    int remainder = blockSize % 16;
                    if (remainder > 0)
                    {
                        blockSize = blockSize - remainder + 16;
                    }
                }
            }

            //compute block hashes and file info hash
            int totalBlocks = Convert.ToInt32(Math.Ceiling(Convert.ToDouble((double)fS.Length / blockSize)));

            byte[][]         blockHash      = new byte[totalBlocks][];
            FileBlockState[] blockAvailable = new FileBlockState[totalBlocks];

            //init
            for (int i = 0; i < totalBlocks; i++)
            {
                long offset = i * blockSize;
                long length = blockSize;

                if ((offset + length) > fS.Length)
                {
                    length = fS.Length - offset;
                }

                blockHash[i]      = hash.ComputeHash(new OffsetStream(fS, offset, length));
                blockAvailable[i] = FileBlockState.Available;
            }

            //get file meta data
            SharedFileMetaData metaData = new SharedFileMetaData(Path.GetFileName(fS.Name), WebUtilities.GetContentType(fS.Name), File.GetLastWriteTimeUtc(fS.Name), fS.Length, blockSize, hashAlgo, blockHash);

            //check if file already shared
            lock (_sharedFiles)
            {
                SharedFile sharedFile;

                if (_sharedFiles.ContainsKey(metaData.FileID))
                {
                    sharedFile = _sharedFiles[metaData.FileID];

                    if (sharedFile._isComplete)
                    {
                        fS.Dispose();
                    }
                    else
                    {
                        sharedFile.Remove(chat);

                        sharedFile = new SharedFile(fS, metaData, blockAvailable, blockAvailable.Length, syncCxt);
                        sharedFile.StartSharing();

                        _sharedFiles.Add(metaData.FileID, sharedFile);
                    }
                }
                else
                {
                    sharedFile = new SharedFile(fS, metaData, blockAvailable, blockAvailable.Length, syncCxt);
                    sharedFile.StartSharing();

                    _sharedFiles.Add(metaData.FileID, sharedFile);
                }

                sharedFile.AddChat(chat);

                return(sharedFile);
            }
        }
Beispiel #3
0
 [System.Security.SecuritySafeCritical]  // auto-generated
 public HMACSHA512(byte[] key)
 {
     m_hashName     = "SHA512";
     m_hash1        = GetHashAlgorithmWithFipsFallback(() => new SHA512Managed(), () => HashAlgorithm.Create("System.Security.Cryptography.SHA512CryptoServiceProvider"));
     m_hash2        = GetHashAlgorithmWithFipsFallback(() => new SHA512Managed(), () => HashAlgorithm.Create("System.Security.Cryptography.SHA512CryptoServiceProvider"));
     HashSizeValue  = 512;
     BlockSizeValue = BlockSize;
     base.InitializeKey(key);
 }
Beispiel #4
0
        /// <summary>
        /// 计算数据块内容的哈希值
        /// </summary>
        /// <param name="buffer">数据块内容</param>
        /// <returns>byte数组的哈希值</returns>
        public static byte[] CalculateHash(byte[] buffer)
        {
            HashAlgorithm hash = HashAlgorithm.Create();

            return(hash.ComputeHash(buffer));
        }
Beispiel #5
0
 public DigestOutputStream(string hashType)
 {
     this.hashType = hashType;
     hash          = HashAlgorithm.Create(hashType);
     hashBuffer    = new byte[512];
 }
 public static string EncodePasswordToBase64(string password)
 {
     byte[] bytes   = Encoding.Unicode.GetBytes(password);
     byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
     return(Convert.ToBase64String(inArray));
 }
        private async Task <string> SerializeIdentityTokenAsync(
            ClaimsIdentity identity, AuthenticationProperties properties,
            OpenIdConnectMessage request, OpenIdConnectMessage response)
        {
            // properties.IssuedUtc and properties.ExpiresUtc
            // should always be preferred when explicitly set.
            if (properties.IssuedUtc == null)
            {
                properties.IssuedUtc = Options.SystemClock.UtcNow;
            }

            if (properties.ExpiresUtc == null)
            {
                properties.ExpiresUtc = properties.IssuedUtc + Options.IdentityTokenLifetime;
            }

            // Replace the identity by a new one containing only the filtered claims.
            // Actors identities are also filtered (delegation scenarios).
            identity = identity.Clone(claim => {
                // Never exclude ClaimTypes.NameIdentifier.
                if (string.Equals(claim.Type, ClaimTypes.NameIdentifier, StringComparison.OrdinalIgnoreCase))
                {
                    return(true);
                }

                // Claims whose destination is not explicitly referenced or doesn't
                // contain "id_token" are not included in the identity token.
                return(claim.HasDestination(OpenIdConnectConstants.Destinations.IdentityToken));
            });

            // Create a new ticket containing the updated properties and the filtered identity.
            var ticket = new AuthenticationTicket(identity, properties);

            ticket.SetUsage(OpenIdConnectConstants.Usages.IdentityToken);

            // Associate a random identifier with the identity token.
            ticket.SetTicketId(Guid.NewGuid().ToString());

            // By default, add the client_id to the list of the
            // presenters allowed to use the identity token.
            if (!string.IsNullOrEmpty(request.ClientId))
            {
                ticket.SetAudiences(request.ClientId);
                ticket.SetPresenters(request.ClientId);
            }

            var notification = new SerializeIdentityTokenContext(Context, Options, request, response, ticket)
            {
                Issuer = Context.GetIssuer(Options),
                SecurityTokenHandler = Options.IdentityTokenHandler,
                SigningCredentials   = Options.SigningCredentials.FirstOrDefault()
            };

            await Options.Provider.SerializeIdentityToken(notification);

            if (notification.HandledResponse || !string.IsNullOrEmpty(notification.IdentityToken))
            {
                return(notification.IdentityToken);
            }

            else if (notification.Skipped)
            {
                return(null);
            }

            if (notification.SecurityTokenHandler == null)
            {
                return(null);
            }

            if (!identity.HasClaim(claim => claim.Type == OpenIdConnectConstants.Claims.Subject) &&
                !identity.HasClaim(claim => claim.Type == ClaimTypes.NameIdentifier))
            {
                throw new InvalidOperationException("A unique identifier cannot be found to generate a 'sub' claim: " +
                                                    "make sure to add a 'ClaimTypes.NameIdentifier' claim.");
            }

            if (notification.SigningCredentials == null)
            {
                throw new InvalidOperationException("A signing key must be provided.");
            }

            // Store the unique subject identifier as a claim.
            if (!identity.HasClaim(claim => claim.Type == OpenIdConnectConstants.Claims.Subject))
            {
                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, identity.GetClaim(ClaimTypes.NameIdentifier));
            }

            // Remove the ClaimTypes.NameIdentifier claims to avoid getting duplicate claims.
            // Note: the "sub" claim is automatically mapped by JwtSecurityTokenHandler
            // to ClaimTypes.NameIdentifier when validating a JWT token.
            // Note: make sure to call ToArray() to avoid an InvalidOperationException
            // on old versions of Mono, where FindAll() is implemented using an iterator.
            foreach (var claim in identity.FindAll(ClaimTypes.NameIdentifier).ToArray())
            {
                identity.RemoveClaim(claim);
            }

            // Store the "unique_id" property as a claim.
            ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.JwtId, ticket.GetTicketId());

            // Store the "usage" property as a claim.
            ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.Usage, ticket.GetUsage());

            // If the ticket is marked as confidential, add a new
            // "confidential" claim in the security token.
            if (ticket.IsConfidential())
            {
                ticket.Identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.Confidential, "true", ClaimValueTypes.Boolean));
            }

            // Store the audiences as claims.
            foreach (var audience in notification.Audiences)
            {
                ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.Audience, audience);
            }

            // If a nonce was present in the authorization request, it MUST
            // be included in the id_token generated by the token endpoint.
            // See http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation
            var nonce = request.Nonce;

            if (request.IsAuthorizationCodeGrantType())
            {
                // Restore the nonce stored in the authentication
                // ticket extracted from the authorization code.
                nonce = ticket.GetNonce();
            }

            if (!string.IsNullOrEmpty(nonce))
            {
                ticket.Identity.AddClaim(OpenIdConnectConstants.Claims.Nonce, nonce);
            }

            using (var algorithm = HashAlgorithm.Create(notification.SigningCredentials.DigestAlgorithm)) {
                // Create an authorization code hash if necessary.
                if (!string.IsNullOrEmpty(response.Code))
                {
                    var hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(response.Code));

                    // Note: only the left-most half of the hash of the octets is used.
                    // See http://openid.net/specs/openid-connect-core-1_0.html#HybridIDToken
                    identity.AddClaim(OpenIdConnectConstants.Claims.CodeHash, Base64UrlEncoder.Encode(hash, 0, hash.Length / 2));
                }

                // Create an access token hash if necessary.
                if (!string.IsNullOrEmpty(response.AccessToken))
                {
                    var hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(response.AccessToken));

                    // Note: only the left-most half of the hash of the octets is used.
                    // See http://openid.net/specs/openid-connect-core-1_0.html#CodeIDToken
                    identity.AddClaim(OpenIdConnectConstants.Claims.AccessTokenHash, Base64UrlEncoder.Encode(hash, 0, hash.Length / 2));
                }
            }

            // Extract the presenters from the authentication ticket.
            var presenters = notification.Presenters.ToArray();

            switch (presenters.Length)
            {
            case 0: break;

            case 1:
                identity.AddClaim(OpenIdConnectConstants.Claims.AuthorizedParty, presenters[0]);
                break;

            default:
                Options.Logger.LogWarning("Multiple presenters have been associated with the identity token " +
                                          "but the JWT format only accepts single values.");

                // Only add the first authorized party.
                identity.AddClaim(OpenIdConnectConstants.Claims.AuthorizedParty, presenters[0]);
                break;
            }

            var token = notification.SecurityTokenHandler.CreateToken(
                subject: ticket.Identity,
                issuer: notification.Issuer,
                signingCredentials: notification.SigningCredentials,
                notBefore: ticket.Properties.IssuedUtc.Value.UtcDateTime,
                expires: ticket.Properties.ExpiresUtc.Value.UtcDateTime);

            token.Payload[OpenIdConnectConstants.Claims.IssuedAt] =
                EpochTime.GetIntDate(ticket.Properties.IssuedUtc.Value.UtcDateTime);

            // Try to extract a key identifier from the signing credentials
            // and add the "kid" property to the JWT header if applicable.
            LocalIdKeyIdentifierClause clause = null;

            if (notification.SigningCredentials.SigningKeyIdentifier.TryFind(out clause))
            {
                token.Header[JwtHeaderParameterNames.Kid] = clause.LocalId;
            }

            return(notification.SecurityTokenHandler.WriteToken(token));
        }
Beispiel #8
0
        /// <summary>
        /// Verifies a simple RSA signature of the specified hash based on PKCS#1 1.5 padding schemes.
        /// </summary>
        /// <param name="rsa">The RSA.</param>
        /// <param name="hashAlgorithm">The hash algorithm.</param>
        /// <param name="hashValue">The hash value.</param>
        /// <param name="signature">The signature.</param>
        /// <returns></returns>
        public static bool VerifySign(RSAParameters parameters, string hashAlgorithm, byte[] bytes, byte[] signature)
        {
            var hasher = HashAlgorithm.Create(hashAlgorithm);

            return(VerifySignHash(parameters, hashAlgorithm, hasher.ComputeHash(bytes), signature));
        }
        private void ApplyEdit(PackageEdit edit)
        {
            // copy the original file
            string packageName  = $"{edit.Id}.{edit.Version}.nupkg".ToLower(CultureInfo.InvariantCulture);
            string originalPath = Path.Combine(this.PackagesPath, packageName);
            string backupPath   = Path.Combine(this.PackagesBackupPath, packageName);

            var    tempDir   = Path.Combine(this.PackagesTempPath, "HandlePackageEdits");
            string directory = Path.Combine(tempDir, edit.Id, edit.Version);
            string tempPath  = Path.Combine(directory, packageName);

            try
            {
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                Log.Info("Downloaded original copy of {0} {1}", edit.Id, edit.Version);
                File.Copy(originalPath, tempPath, true);

                // Load the zip file and find the manifest
                using (var originalStream = File.Open(tempPath, FileMode.Open, FileAccess.ReadWrite))
                    using (var archive = new ZipArchive(originalStream, ZipArchiveMode.Update))
                    {
                        // Find the nuspec
                        var nuspecEntries = archive.Entries.Where(e => ManifestSelector.IsMatch(e.FullName)).ToArray();
                        if (nuspecEntries.Length == 0)
                        {
                            throw new InvalidDataException(
                                      string.Format(
                                          CultureInfo.CurrentCulture,
                                          "Package has no manifest: {0} {1} (URL: {2})",
                                          edit.Id,
                                          edit.Version,
                                          tempPath));
                        }

                        if (nuspecEntries.Length > 1)
                        {
                            throw new InvalidDataException(
                                      string.Format(
                                          CultureInfo.CurrentCulture,
                                          "Package has multiple manifests: {0} {1} (URL: {2})",
                                          edit.Id,
                                          edit.Version,
                                          tempPath));
                        }

                        // We now have the nuspec
                        var manifestEntry = nuspecEntries.Single();

                        // Load the manifest with a constrained stream
                        Log.Info("Rewriting package file for {0} {1}", edit.Id, edit.Version);
                        using (var manifestStream = manifestEntry.Open())
                        {
                            var manifest = Manifest.ReadFrom(manifestStream, validateSchema: false);

                            // Modify the manifest as per the edit
                            edit.ApplyTo(manifest.Metadata);

                            // Save the manifest back
                            manifestStream.Seek(0, SeekOrigin.Begin);
                            manifestStream.SetLength(0);
                            manifest.Save(manifestStream);
                        }

                        Log.Info("Rewrote package file for {0} {1}", edit.Id, edit.Version);
                    }

                // replace original file and back it up
                Log.Info("Replacing original package file for {0} {1} ({2}, backup location {3}).", edit.Id, edit.Version, originalPath, backupPath);
                File.Replace(tempPath, originalPath, backupPath);

                // Calculate new size and hash
                string hash;
                long   size;
                using (var originalStream = File.OpenRead(originalPath))
                {
                    size = originalStream.Length;

                    var hashAlgorithm = HashAlgorithm.Create(HashAlgorithmName);
                    if (hashAlgorithm == null)
                    {
                        throw new InvalidOperationException($"Failed to create instance of hash algorithm {HashAlgorithmName}.");
                    }

                    hash = Convert.ToBase64String(hashAlgorithm.ComputeHash(originalStream));
                }

                // Update the database
                Log.Info("Updating package record for {0} {1}", edit.Id, edit.Version);
                using (var connection = this.PackageDatabase.ConnectTo())
                {
                    var parameters =
                        new DynamicParameters(
                            new
                    {
                        edit.Authors,
                        edit.Copyright,
                        edit.Description,
                        edit.IconUrl,
                        edit.LicenseUrl,
                        edit.ProjectUrl,
                        edit.ReleaseNotes,
                        edit.RequiresLicenseAcceptance,
                        edit.Summary,
                        edit.Title,
                        edit.Tags,
                        edit.Key,
                        edit.PackageKey,
                        edit.UserKey,
                        PackageFileSize = size,
                        Hash            = hash,
                        HashAlgorithm   = HashAlgorithmName
                    });

                    // Prep SQL for merging in authors
                    StringBuilder loadAuthorsSql = new StringBuilder();
                    var           authors        = edit.Authors.Split(',');
                    for (int i = 0; i < authors.Length; i++)
                    {
                        loadAuthorsSql.Append("INSERT INTO [PackageAuthors]([PackageKey],[Name]) VALUES(@PackageKey, @Author" + i + ")");
                        parameters.Add("Author" + i, authors[i]);
                    }

                    connection.Query <int>(@"
                            BEGIN TRANSACTION
                                -- Form a comma-separated list of authors
                                DECLARE @existingAuthors nvarchar(MAX)
                                SELECT @existingAuthors = COALESCE(@existingAuthors + ',', '') + Name
                                FROM PackageAuthors
                                WHERE PackageKey = @PackageKey

                                -- Copy packages data to package history table
                                INSERT INTO [PackageHistories]
                                SELECT      [Key] AS PackageKey,
                                            @UserKey AS UserKey,
                                            GETUTCDATE() AS Timestamp,
                                            Title,
                                            @existingAuthors AS Authors,
                                            Copyright,
                                            Description,
                                            IconUrl,
                                            LicenseUrl,
                                            ProjectUrl,
                                            ReleaseNotes,
                                            RequiresLicenseAcceptance,
                                            Summary,
                                            Tags,
                                            Hash,
                                            HashAlgorithm,
                                            PackageFileSize,
                                            LastUpdated,
                                            Published
                                FROM        [Packages]
                                WHERE       [Key] = @PackageKey

                                -- Update the packages table
                                UPDATE  [Packages]
                                SET     Copyright = @Copyright,
                                        Description = @Description,
                                        IconUrl = @IconUrl,
                                        LicenseUrl = @LicenseUrl,
                                        ProjectUrl = @ProjectUrl,
                                        ReleaseNotes = @ReleaseNotes,
                                        RequiresLicenseAcceptance = @RequiresLicenseAcceptance,
                                        Summary = @Summary,
                                        Title = @Title,
                                        Tags = @Tags,
                                        LastEdited = GETUTCDATE(),
                                        LastUpdated = GETUTCDATE(),
                                        UserKey = @UserKey,
                                        Hash = @Hash,
                                        HashAlgorithm = @HashAlgorithm,
                                        PackageFileSize = @PackageFileSize,
                                        FlattenedAuthors = @Authors
                                WHERE   [Key] = @PackageKey

                                -- Update Authors
                                DELETE FROM [PackageAuthors] 
                                WHERE PackageKey = @PackageKey

                                " + loadAuthorsSql + @"
                            
                                -- Clean this edit and all previous edits.
                                DELETE FROM [PackageEdits]
                                WHERE [PackageKey] = @PackageKey
                                AND [Key] <= @Key

                                COMMIT TRANSACTION", parameters);
                }

                Log.Info("Updated package record for {0} {1}", edit.Id, edit.Version);
            }
            catch (Exception ex)
            {
                Log.Error("Failed to update package information. Package {0} {1}. Exception {2}", edit.Id, edit.Version, ex.Message);
                throw;
            }
            finally
            {
                DirectoryEx.TryDelete(directory);
            }
        }
Beispiel #10
0
 public static string EnkriptoPasswordBase64(string Password)
 {
     byte[] bytes   = System.Text.Encoding.Unicode.GetBytes(Password);
     byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
     return(Convert.ToBase64String(inArray));
 }
Beispiel #11
0
        /// <summary>
        /// Performs a simple RSA signing of the specified bytes based on PKCS#1 1.5 padding schemes.
        /// </summary>
        /// <param name="rsa">The RSA.</param>
        /// <param name="hashAlgorithm">The hash algorithm.</param>
        /// <param name="bytes">The bytes.</param>
        /// <returns></returns>
        public static byte[] SimpleSign(RSAParameters parameters, string hashAlgorithm, byte[] bytes)
        {
            var hasher = HashAlgorithm.Create(hashAlgorithm);

            return(SimpleSignHash(parameters, hashAlgorithm, hasher.ComputeHash(bytes)));
        }
Beispiel #12
0
        public Bitmap Create(byte[] value, Size size, Color backgroundcolor, Size blocks, IBlockGenerator[] blockGenerators, IBrushGenerator brushGenerator, string algorithm)
        {
            var ha = HashAlgorithm.Create(algorithm);

            if (ha == null)
            {
                throw new ArgumentOutOfRangeException(string.Format("Unknown algorithm '{0}'", algorithm));
            }

            if (blocks.Width < 1)
            {
                throw new ArgumentOutOfRangeException("blockshorizontal");
            }
            if (blocks.Height < 1)
            {
                throw new ArgumentOutOfRangeException("blocksvertical");
            }

            if (size.Width <= 0)
            {
                throw new ArgumentOutOfRangeException("width");
            }
            if (size.Height <= 0)
            {
                throw new ArgumentOutOfRangeException("height");
            }

            if (blockGenerators.Length == 0)
            {
                throw new ArgumentException("blockgenerators");
            }

            if (blockGenerators.Any(b => b == null))
            {
                throw new ArgumentNullException("blockgenerators");
            }

            size.Width  -= size.Width % blocks.Width;
            size.Height -= size.Height % blocks.Height;

            if (size.Width <= 0)
            {
                throw new ArgumentOutOfRangeException("width after rounding to nearest value");
            }
            if (size.Height <= 0)
            {
                throw new ArgumentOutOfRangeException("height after rounding to nearest value");
            }

            bool hasunevencols = blocks.Width % 2 != 0;
            var  allblockgens  = blockGenerators.ToArray();
            var  symblockgens  = blockGenerators.Where(sbg => sbg.IsSymmetric).ToArray();

            if (hasunevencols && symblockgens.Length == 0)
            {
                throw new Exception("At least one symmetrical blockgenerator required for identicons with uneven number of horizontal blocks");
            }

            ha.Initialize();
            var hash        = ha.ComputeHash(value);
            var blockwidth  = (int)Math.Ceiling((double)size.Width / blocks.Width);
            var blockheight = (int)Math.Ceiling((double)size.Height / blocks.Height);


            var result = new Bitmap(size.Width, size.Height);

            using (var bgbrush = new SolidBrush(backgroundcolor))
                using (var gfx = Graphics.FromImage(result))
                {
                    gfx.FillRectangle(bgbrush, 0, 0, size.Width, size.Height);

                    var dhash     = hash.Concat(hash).ToArray();
                    int hashlen   = hash.Length;
                    int i         = 0;
                    int halfwidth = blocks.Width / 2;
                    for (var x = 0; x < (hasunevencols ? halfwidth + 1 : halfwidth); x++)
                    {
                        for (var y = 0; y < blocks.Height; y++, i++)
                        {
                            var blockgen = GetBlockGenerator((x == halfwidth && hasunevencols) ? symblockgens : allblockgens, hash[i % hashlen]);
                            var seed     = BitConverter.ToUInt32(dhash, i % hashlen);

                            using (var fgbrush = brushGenerator.GetBrush(seed))
                            {
                                Rectangle rl = new Rectangle(x * blockwidth, y * blockheight, blockwidth, blockheight);
                                blockgen.Draw(gfx, rl, bgbrush, fgbrush, seed, false);

                                if ((x != halfwidth) || ((x == halfwidth) && !hasunevencols))
                                {
                                    Rectangle rr = new Rectangle((size.Width - blockwidth) - (x * blockwidth), y * blockheight, blockwidth, blockheight);
                                    blockgen.Draw(gfx, rr, bgbrush, fgbrush, seed, true);
                                }
                            }
                        }
                    }
                }
            return(result);
        }
Beispiel #13
0
 /// <summary>
 /// Computes the hash of the specified buffer.
 /// </summary>
 /// <param name="data">The data to hash.</param>
 /// <returns>
 /// The computed hash.
 /// </returns>
 public override byte[] Hash(byte[] data)
 {
     using (var hasher = HashAlgorithm.Create(this.HashAlgorithmName)) {
         return(hasher.ComputeHash(data));
     }
 }
Beispiel #14
0
 public static string GenerateHash(string plainText)
 {
     byte[] bytesArray = Encoding.Unicode.GetBytes(plainText);
     byte[] hashed     = HashAlgorithm.Create("MD5").ComputeHash(bytesArray);
     return(Convert.ToBase64String(hashed));
 }
Beispiel #15
0
 public void Disposable()
 {
     using (HashAlgorithm hash = HashAlgorithm.Create()) {
         hash.ComputeHash(new byte [0]);
     }
 }
Beispiel #16
0
 public KetamaLocator(string hashName = null)
 {
     _hashPool        = new HashPool(() => HashAlgorithm.Create(hashName ?? DefaultHashName));
     _nodeStateChange = _ => Reinitialize();
 }
Beispiel #17
0
 private string GerarHash(string senha)
 {
     byte[] bytes   = Encoding.Unicode.GetBytes(senha);
     byte[] inArray = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
     return(Convert.ToBase64String(inArray));
 }
Beispiel #18
0
 // Code taken from a stackoverflow example
 public static string MD5Base64Hash(string input)
 {
     byte[] bytes   = Encoding.Unicode.GetBytes(input);
     byte[] inArray = HashAlgorithm.Create("MD5").ComputeHash(bytes);
     return(Convert.ToBase64String(inArray));
 }
Beispiel #19
0
 public static string encode_tobase64(string password)
 {
     return(Convert.ToBase64String(HashAlgorithm.Create("SHA1").ComputeHash(Encoding.Unicode.GetBytes(password))));
 }
Beispiel #20
0
        private bool VerifyCounterSignature(PKCS7.SignerInfo cs, byte[] signature)
        {
            // SEQUENCE {
            //   INTEGER 1
            if (cs.Version > 1)
            {
                return(false);
            }
            //   SEQUENCE {
            //      SEQUENCE {

            string contentType   = null;
            ASN1   messageDigest = null;

            for (int i = 0; i < cs.AuthenticatedAttributes.Count; i++)
            {
                // SEQUENCE {
                //   OBJECT IDENTIFIER
                ASN1   attr = (ASN1)cs.AuthenticatedAttributes [i];
                string oid  = ASN1Convert.ToOid(attr[0]);
                switch (oid)
                {
                case "1.2.840.113549.1.9.3":
                    // contentType
                    contentType = ASN1Convert.ToOid(attr[1][0]);
                    break;

                case "1.2.840.113549.1.9.4":
                    // messageDigest
                    messageDigest = attr[1][0];
                    break;

                case "1.2.840.113549.1.9.5":
                    // SEQUENCE {
                    //   OBJECT IDENTIFIER
                    //     signingTime (1 2 840 113549 1 9 5)
                    //   SET {
                    //     UTCTime '030124013651Z'
                    //   }
                    // }
                    timestamp = ASN1Convert.ToDateTime(attr[1][0]);
                    break;

                default:
                    break;
                }
            }

            if (contentType != PKCS7.Oid.data)
            {
                return(false);
            }

            // verify message digest
            if (messageDigest == null)
            {
                return(false);
            }
            // TODO: must be read from the ASN.1 structure
            string hashName = null;

            switch (messageDigest.Length)
            {
            case 16:
                hashName = "MD5";
                break;

            case 20:
                hashName = "SHA1";
                break;

            case 32:
                hashName = "SHA256";
                break;

            case 48:
                hashName = "SHA384";
                break;

            case 64:
                hashName = "SHA512";
                break;
            }
            HashAlgorithm ha = HashAlgorithm.Create(hashName);

            if (!messageDigest.CompareValue(ha.ComputeHash(signature)))
            {
                return(false);
            }

            // verify signature
            byte[] counterSignature = cs.Signature;

            // change to SET OF (not [0]) as per PKCS #7 1.5
            ASN1 aa = new ASN1(0x31);

            foreach (ASN1 a in cs.AuthenticatedAttributes)
            {
                aa.Add(a);
            }
            byte[] p7hash = ha.ComputeHash(aa.GetBytes());

            // we need to try all certificates
            string issuer = cs.IssuerName;

            byte[] serial = cs.SerialNumber;
            foreach (X509Certificate x509 in coll)
            {
                if (CompareIssuerSerial(issuer, serial, x509))
                {
                    if (x509.PublicKey.Length > counterSignature.Length)
                    {
                        RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.RSA;
                        // we need to HACK around bad (PKCS#1 1.5) signatures made by Verisign Timestamp Service
                        // and this means copying stuff into our own RSAManaged to get the required flexibility
                        RSAManaged rsam = new RSAManaged();
                        rsam.ImportParameters(rsa.ExportParameters(false));
                        if (PKCS1.Verify_v15(rsam, ha, p7hash, counterSignature, true))
                        {
                            timestampChain.LoadCertificates(coll);
                            return(timestampChain.Build(x509));
                        }
                    }
                }
            }
            // no certificate can verify this signature!
            return(false);
        }
        private async Task ApplyEdit(PackageEdit edit)
        {
            // Download the original file
            string originalPath = null;

            TempDirectory = Path.Combine(Path.GetTempPath(), "NuGetService", "HandlePackageEdits");

            try
            {
                string directory = Path.Combine(TempDirectory, edit.Id, edit.Version);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                originalPath = Path.Combine(directory, "original.nupkg");
                var sourceBlob = SourceContainer.GetBlockBlobReference(
                    StorageHelpers.GetPackageBlobName(edit.Id, edit.Version));
                Trace.TraceInformation(string.Format("Name is {0}, storage uri is {1}", sourceBlob.Name, sourceBlob.StorageUri));
                Trace.TraceInformation(string.Format("Downloading original copy of {0} {1}", edit.Id, edit.Version));
                await sourceBlob.DownloadToFileAsync(originalPath, FileMode.Create);

                Trace.TraceInformation(string.Format("Downloaded original copy of {0} {1}", edit.Id, edit.Version));

                // Check that a backup exists
                var backupBlob = BackupsContainer.GetBlockBlobReference(
                    StorageHelpers.GetPackageBackupBlobName(edit.Id, edit.Version, edit.Hash));
                if (!await backupBlob.ExistsAsync())
                {
                    Trace.TraceInformation(string.Format("Backing up original copy of {0} {1}", edit.Id, edit.Version));
                    await backupBlob.UploadFromFileAsync(originalPath, FileMode.Open);

                    Trace.TraceInformation(string.Format("Backed up original copy of {0} {1}", edit.Id, edit.Version));
                }

                // Load the zip file and find the manifest
                using (var originalStream = File.Open(originalPath, FileMode.Open, FileAccess.ReadWrite))
                    using (var archive = new ZipArchive(originalStream, ZipArchiveMode.Update))
                    {
                        // Find the nuspec
                        var nuspecEntries = archive.Entries.Where(e => ManifestSelector.IsMatch(e.FullName)).ToArray();
                        if (nuspecEntries.Length == 0)
                        {
                            throw new InvalidDataException(string.Format(
                                                               CultureInfo.CurrentCulture,
                                                               Strings.HandlePackageEditsJob_MissingManifest,
                                                               edit.Id,
                                                               edit.Version,
                                                               backupBlob.Uri.AbsoluteUri));
                        }
                        else if (nuspecEntries.Length > 1)
                        {
                            throw new InvalidDataException(string.Format(
                                                               CultureInfo.CurrentCulture,
                                                               Strings.HandlePackageEditsJob_MultipleManifests,
                                                               edit.Id,
                                                               edit.Version,
                                                               backupBlob.Uri.AbsoluteUri));
                        }

                        // We now have the nuspec
                        var manifestEntry = nuspecEntries.Single();

                        // Load the manifest with a constrained stream
                        Trace.TraceInformation(string.Format("Rewriting package file for {0} {1}", edit.Id, edit.Version));
                        Manifest manifest;
                        using (var manifestStream = manifestEntry.Open())
                        {
                            manifest = Manifest.ReadFrom(manifestStream, validateSchema: false);

                            // Modify the manifest as per the edit
                            edit.ApplyTo(manifest.Metadata);

                            // Save the manifest back
                            manifestStream.Seek(0, SeekOrigin.Begin);
                            manifestStream.SetLength(0);
                            manifest.Save(manifestStream);
                        }
                        Trace.TraceInformation(string.Format("Rewrote package file for {0} {1}", edit.Id, edit.Version));
                    }

                // Snapshot the original blob
                Trace.TraceInformation(string.Format("Snapshotting original blob for {0} {1} ({2}).", edit.Id, edit.Version, sourceBlob.Uri.AbsoluteUri));
                var sourceSnapshot = await sourceBlob.CreateSnapshotAsync();

                Trace.TraceInformation(string.Format("Snapshotted original blob for {0} {1} ({2}).", edit.Id, edit.Version, sourceBlob.Uri.AbsoluteUri));

                // Upload the updated file
                Trace.TraceInformation(string.Format("Uploading modified package file for {0} {1} to {2}", edit.Id, edit.Version, sourceBlob.Uri.AbsoluteUri));
                await sourceBlob.UploadFromFileAsync(originalPath, FileMode.Open);

                Trace.TraceInformation(string.Format("Uploaded modified package file for {0} {1} to {2}", edit.Id, edit.Version, sourceBlob.Uri.AbsoluteUri));

                // Calculate new size and hash
                string hash;
                long   size;
                using (var originalStream = File.OpenRead(originalPath))
                {
                    size = originalStream.Length;

                    var hashAlgorithm = HashAlgorithm.Create(HashAlgorithmName);
                    hash = Convert.ToBase64String(
                        hashAlgorithm.ComputeHash(originalStream));
                }

                // Update the database
                try
                {
                    Trace.TraceInformation(string.Format("Updating package record for {0} {1}", edit.Id, edit.Version));
                    using (var connection = await PackageDatabase.ConnectTo())
                    {
                        var parameters = new DynamicParameters(new
                        {
                            edit.Authors,
                            edit.Copyright,
                            edit.Description,
                            edit.IconUrl,
                            edit.LicenseUrl,
                            edit.ProjectUrl,
                            edit.ReleaseNotes,
                            edit.RequiresLicenseAcceptance,
                            edit.Summary,
                            edit.Title,
                            edit.Tags,
                            edit.Key,
                            edit.PackageKey,
                            edit.UserKey,
                            PackageFileSize = size,
                            Hash            = hash,
                            HashAlgorithm   = HashAlgorithmName
                        });

                        // Prep SQL for merging in authors
                        StringBuilder loadAuthorsSql = new StringBuilder();
                        var           authors        = edit.Authors.Split(',');
                        for (int i = 0; i < authors.Length; i++)
                        {
                            loadAuthorsSql.Append("INSERT INTO [PackageAuthors]([PackageKey],[Name]) VALUES(@PackageKey, @Author" + i.ToString() + ")");
                            parameters.Add("Author" + i.ToString(), authors[i]);
                        }

                        await connection.QueryAsync <int>(@"
                            BEGIN TRANSACTION
                                -- Form a comma-separated list of authors
                                DECLARE @existingAuthors nvarchar(MAX)
                                SELECT @existingAuthors = COALESCE(@existingAuthors + ',', '') + Name
                                FROM PackageAuthors
                                WHERE PackageKey = @PackageKey

                                -- Copy packages data to package history table
                                INSERT INTO [PackageHistories]
                                SELECT      [Key] AS PackageKey,
                                            @UserKey AS UserKey,
                                            GETUTCDATE() AS Timestamp,
                                            Title,
                                            @existingAuthors AS Authors,
                                            Copyright,
                                            Description,
                                            IconUrl,
                                            LicenseUrl,
                                            ProjectUrl,
                                            ReleaseNotes,
                                            RequiresLicenseAcceptance,
                                            Summary,
                                            Tags,
                                            Hash,
                                            HashAlgorithm,
                                            PackageFileSize,
                                            LastUpdated,
                                            Published
                                FROM        [Packages]
                                WHERE       [Key] = @PackageKey

                                -- Update the packages table
                                UPDATE  [Packages]
                                SET     Copyright = @Copyright,
                                        Description = @Description,
                                        IconUrl = @IconUrl,
                                        LicenseUrl = @LicenseUrl,
                                        ProjectUrl = @ProjectUrl,
                                        ReleaseNotes = @ReleaseNotes,
                                        RequiresLicenseAcceptance = @RequiresLicenseAcceptance,
                                        Summary = @Summary,
                                        Title = @Title,
                                        Tags = @Tags,
                                        LastEdited = GETUTCDATE(),
                                        LastUpdated = GETUTCDATE(),
                                        UserKey = @UserKey,
                                        Hash = @Hash,
                                        HashAlgorithm = @HashAlgorithm,
                                        PackageFileSize = @PackageFileSize,
                                        FlattenedAuthors = @Authors
                                WHERE   [Key] = @PackageKey

                                -- Update Authors
                                DELETE FROM [PackageAuthors] 
                                WHERE PackageKey = @PackageKey

                                " + loadAuthorsSql.ToString() + @"
                            
                                -- Clean this edit and all previous edits.
                                DELETE FROM [PackageEdits]
                                WHERE [PackageKey] = @PackageKey
                                AND [Key] <= @Key
                            " + "COMMIT TRANSACTION",
                                                          parameters);
                    }
                    Trace.TraceInformation(string.Format("Updated package record for {0} {1}", edit.Id, edit.Version));
                }
                catch (Exception)
                {
                    // Error occurred while updaing database, roll back the blob to the snapshot
                    // Can't do "await" in a catch block, but this should be pretty quick since it just starts the copy
                    Trace.TraceInformation(string.Format("Rolling back updated blob for {0} {1}. Copying snapshot {2} to {3}", edit.Id, edit.Version, sourceSnapshot.Uri.AbsoluteUri, sourceBlob.Uri.AbsoluteUri));
                    sourceBlob.StartCopyFromBlob(sourceSnapshot);
                    Trace.TraceInformation(string.Format("Rolled back updated blob for {0} {1}. Copying snapshot {2} to {3}", edit.Id, edit.Version, sourceSnapshot.Uri.AbsoluteUri, sourceBlob.Uri.AbsoluteUri));
                    throw;
                }

                Trace.TraceInformation(string.Format("Deleting snapshot blob {2} for {0} {1}.", edit.Id, edit.Version, sourceSnapshot.Uri.AbsoluteUri));
                await sourceSnapshot.DeleteAsync();

                Trace.TraceInformation(string.Format("Deleted snapshot blob {2} for {0} {1}.", edit.Id, edit.Version, sourceSnapshot.Uri.AbsoluteUri));
            }
            finally
            {
                if (!string.IsNullOrEmpty(originalPath) && File.Exists(originalPath))
                {
                    File.Delete(originalPath);
                }
            }
        }
Beispiel #22
0
        private void btnSignIn_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text == "")
            {
                MessageBox.Show("Please enter user name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUserName.Focus();
                return;
            }
            if (txtPassword.Text == "")
            {
                MessageBox.Show("Please enter password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPassword.Focus();
                return;
            }
            try
            {
                string clearText      = txtPassword.Text.Trim();
                string password       = clearText;
                byte[] bytes          = Encoding.Unicode.GetBytes(password);
                byte[] inArray        = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
                string readyPassword1 = Convert.ToBase64String(inArray);
                readyPassword = readyPassword1;


                con = new SqlConnection(cs.DBConn);
                con.Open();
                string qry = "SELECT UserName,Password FROM Registration WHERE UserName = '******' AND Password = '******'";
                cmd  = new SqlCommand(qry, con);
                rdr1 = cmd.ExecuteReader();
                if (rdr1.Read() == true)
                {
                    dbUserName = (rdr1.GetString(0));
                    dbPassword = (rdr1.GetString(1));


                    con = new SqlConnection(cs.DBConn);
                    con.Open();
                    string ct = "select UserType,UserId from Registration where UserName='******' and Password='******'";
                    cmd            = new SqlCommand(ct);
                    cmd.Connection = con;
                    rdr            = cmd.ExecuteReader();
                    if (rdr.Read())
                    {
                        userType = (rdr.GetString(0));
                        uId2     = (rdr.GetInt32(1));
                    }
                    if ((rdr != null))
                    {
                        rdr.Close();
                    }
                    //if (dbUserName == txtUserName.Text && dbPassword == readyPassword && userType.Trim() == "SuperAdmin")
                    //{


                    //}


                    if (dbUserName == txtUserName.Text && txtUserName.Text == "*****@*****.**" || txtUserName.Text == "iqbal" && dbPassword == readyPassword && userType.Trim() == "Admin")
                    {
                        this.Hide();
                        frmMainUI frm = new frmMainUI();
                        frm.Show();
                        frm.lblUser.Text = txtUserName.Text;
                        txtPassword.Clear();
                        txtUserName.Clear();
                    }


                    //if (dbUserName == txtUserName.Text && dbPassword == readyPassword && userType.Trim() == "Admin")
                    //{
                    //    this.Hide();
                    //    frmMainUI frm = new frmMainUI();
                    //    frm.Show();
                    //    frm.lblUser.Text = txtUserName.Text;
                    //    txtPassword.Clear();
                    //    txtUserName.Clear();

                    //}

                    else
                    {
                        MessageBox.Show("Invalid Credential");
                        txtUserName.Clear();
                        txtPassword.Clear();
                        txtUserName.Focus();
                    }
                    //if (dbUserName == txtUserName.Text && dbPassword == readyPassword && userType.Trim() == "User")
                    //{
                    //    this.Hide();
                    //    FiscalYear frm = new FiscalYear();
                    //    frm.Show();

                    //}
                }
                else
                {
                    MessageBox.Show("Login is Failed...Try again !", "Login Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtUserName.Clear();
                    txtPassword.Clear();
                    txtUserName.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //if (txtUserName.Text == "")
            //{
            //    MessageBox.Show("Please enter user name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    txtUserName.Focus();
            //    return;
            //}
            //if (txtPassword.Text == "")
            //{
            //    MessageBox.Show("Please enter password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    txtPassword.Focus();
            //    return;
            //}
            //try
            //{
            //    SqlConnection myConnection = default(SqlConnection);
            //    myConnection = new SqlConnection(cs.DBConn);

            //    SqlCommand myCommand = default(SqlCommand);

            //    myCommand = new SqlCommand("SELECT Username,password FROM Registration WHERE Username = @username AND Password = @UserPassword", myConnection);
            //    SqlParameter uName = new SqlParameter("@username", SqlDbType.VarChar);
            //    SqlParameter uPassword = new SqlParameter("@UserPassword", SqlDbType.VarChar);
            //    uName.Value = txtUserName.Text;
            //    uPassword.Value = txtPassword.Text;
            //    myCommand.Parameters.Add(uName);
            //    myCommand.Parameters.Add(uPassword);

            //    myCommand.Connection.Open();

            //    SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

            //    if (myReader.Read() == true)
            //    {
            //        int i;
            //        ProgressBar1.Visible = true;
            //        ProgressBar1.Maximum = 5000;
            //        ProgressBar1.Minimum = 0;
            //        ProgressBar1.Value = 4;
            //        ProgressBar1.Step = 1;

            //        for (i = 0; i <= 5000; i++)
            //        {
            //            ProgressBar1.PerformStep();
            //        }
            //        con = new SqlConnection(cs.DBConn);
            //        con.Open();
            //        string ct = "select usertype,UserId from Registration where Username='******'and Password='******'";
            //        cmd = new SqlCommand(ct);
            //        cmd.Connection = con;
            //        rdr = cmd.ExecuteReader();
            //        if (rdr.Read())
            //        {
            //            txtUserType.Text = (rdr.GetString(0));
            //            uId2 = (rdr.GetInt32(1));

            //        }
            //        if ((rdr != null))
            //        {
            //            rdr.Close();
            //        }

            //        if (txtUserType.Text.Trim() == "Admin")
            //        {
            //            this.Hide();
            //            frmMainUI frm = new frmMainUI();
            //            frm.Show();
            //            //this.Visible = false;
            //            //frm.ShowDialog();
            //            frm.lblUser.Text = txtUserName.Text;
            //            //this.Visible = true;
            //            txtPassword.Clear();
            //            txtUserName.Clear();
            //        }
            //        //if (txtUserType.Text.Trim() == "User")
            //        //{

            //        //    MasterPagesForUser frm = new MasterPagesForUser();
            //        //    this.Visible = false;
            //        //    frm.ShowDialog();
            //        //    this.Visible = true;

            //        //}

            //    }


            //    else
            //    {
            //        MessageBox.Show("Login is Failed...Try again !", "Login Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);

            //        txtUserName.Clear();
            //        txtPassword.Clear();
            //        txtUserName.Focus();

            //    }
            //    if (myConnection.State == ConnectionState.Open)
            //    {
            //        myConnection.Dispose();
            //    }



            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }
Beispiel #23
0
        private static byte[] Hash([NotNull] byte[] clearBytes, [NotNull] HashAlgorithmType hashAlgorithmType)
        {
            CodeContracts.ArgumentNotNull(clearBytes, "clearBytes");

            return(HashAlgorithm.Create(hashAlgorithmType.GetStringValue()).ComputeHash(clearBytes));
        }
Beispiel #24
0
        public void MessageAudio(string to, string filepath)
        {
            to = GetJID(to);
            FileInfo finfo = new FileInfo(filepath);
            string   type  = string.Empty;

            switch (finfo.Extension)
            {
            case ".wav":
                type = "audio/wav";
                break;

            case ".ogg":
                type = "audio/ogg";
                break;

            case ".aif":
                type = "audio/x-aiff";
                break;

            case ".aac":
                type = "audio/aac";
                break;

            case ".m4a":
                type = "audio/mp4";
                break;

            default:
                type = "audio/mpeg";
                break;
            }

            //create hash
            string filehash = string.Empty;

            using (FileStream fs = File.OpenRead(filepath))
            {
                using (BufferedStream bs = new BufferedStream(fs))
                {
                    using (HashAlgorithm sha = HashAlgorithm.Create("sha256"))
                    {
                        byte[] raw = sha.ComputeHash(bs);
                        filehash = Convert.ToBase64String(raw);
                    }
                }
            }

            //request upload
            WaUploadResponse response = this.UploadFile(filehash, "audio", finfo.Length, filepath, to, type);

            if (response != null && !String.IsNullOrEmpty(response.url))
            {
                //send message
                FMessage msg = new FMessage(to, true)
                {
                    media_wa_type = FMessage.Type.Audio, media_mime_type = response.mimetype, media_name = response.url.Split('/').Last(), media_size = response.size, media_url = response.url, media_duration_seconds = response.duration
                };
                this.SendMessage(msg);
            }
        }
Beispiel #25
0
        /** Add the SHA1 of every file to the manifest, creating it if necessary. */
        private static Manifest addDigestsToManifest(JarFile jar)
        {
            Manifest   input  = jar.Manifest;
            Manifest   output = new Manifest();
            Attributes main   = output.MainAttributes;

            if (input != null)
            {
                main.AddAll(input.MainAttributes);
            }
            else
            {
                main.Add("Manifest-Version", "1.0");
                main.Add("Created-By", "1.0 (Android SignApk)");
            }

            byte[] buffer = new byte[4096];
            int    num;

            IEnumerable <JarEntry> jes;

            if (input == null)
            {
                jes = jar.OrderBy(j => j.Name);
            }
            else
            {
                var entries       = jar.ToDictionary(j => j.Name);
                var sortedEntries = new List <JarEntry>();
                foreach (var entry in input.Entries)
                {
                    sortedEntries.Add(entries[entry.Key]);
                }
                jes = sortedEntries;
            }

            foreach (JarEntry entry in jes)
            {
                HashAlgorithm md   = HashAlgorithm.Create("SHA1");
                String        name = entry.Name;
                if (!entry.IsDirectory && !name.Equals(JarFile.MANIFEST_NAME) &&
                    !name.Equals(CERT_SF_NAME) && !name.Equals(CERT_RSA_NAME) &&
                    !name.Equals(OTACERT_NAME) &&
                    (stripPattern == null ||
                     !stripPattern.IsMatch(name)))
                {
                    Stream data = jar.GetInputStream(entry);
                    while ((num = data.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        md.TransformBlock(buffer, 0, num, null, 0);
                    }
                    md.TransformFinalBlock(buffer, 0, 0);

                    Attributes attr = null;
                    if (input != null)
                    {
                        attr = input.GetAttributes(name);
                    }
                    attr = attr != null ? new Attributes(attr) : new Attributes();
                    attr.Add("SHA1-Digest", Convert.ToBase64String(md.Hash));
                    output.Entries.Add(name, attr);
                }
            }

            return(output);
        }
Beispiel #26
0
        private void oKButton_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text == "")
            {
                MessageBox.Show("Please enter user name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUserName.Focus();
                return;
            }
            if (txtPassword.Text == "")
            {
                MessageBox.Show("Please enter password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtPassword.Focus();
                return;
            }
            try
            {
                string clearText      = txtPassword.Text.Trim();
                string password       = clearText;
                byte[] bytes          = Encoding.Unicode.GetBytes(password);
                byte[] inArray        = HashAlgorithm.Create("SHA1").ComputeHash(bytes);
                string readyPassword1 = Convert.ToBase64String(inArray);
                readyPassword = readyPassword1;


                con = new SqlConnection(cs.DBConn);
                con.Open();
                string qry = "SELECT Username,passwords FROM Registration WHERE Username = '******' AND passwords = '" + readyPassword + "'";
                cmd  = new SqlCommand(qry, con);
                rdr1 = cmd.ExecuteReader();
                if (rdr1.Read() == true)
                {
                    dbUserName = (rdr1.GetString(0));
                    dbPassword = (rdr1.GetString(1));


                    con = new SqlConnection(cs.DBConn);
                    con.Open();
                    string ct = "select usertype,UserId from Registration where Username='******' and Passwords='" + readyPassword + "'";
                    cmd            = new SqlCommand(ct);
                    cmd.Connection = con;
                    rdr            = cmd.ExecuteReader();
                    if (rdr.Read())
                    {
                        userType = (rdr.GetString(0));
                        uId      = (rdr.GetInt32(1));
                    }
                    if ((rdr != null))
                    {
                        rdr.Close();
                    }
                    if (dbUserName == txtUserName.Text)
                    {
                        if (dbPassword == readyPassword && userType.Trim() == "SuperAdmin")
                        {
                            this.Hide();
                            FiscalYear frm = new FiscalYear();
                            frm.Show();
                        }
                    }
                    if (dbUserName == txtUserName.Text)
                    {
                        if (dbPassword == readyPassword && userType.Trim() == "Admin")
                        {
                            this.Hide();
                            FiscalYear frm = new FiscalYear();
                            frm.Show();
                        }
                    }
                    if (dbUserName == txtUserName.Text)
                    {
                        if (dbPassword == readyPassword && userType.Trim() == "User")
                        {
                            this.Hide();
                            FiscalYear frm = new FiscalYear();
                            frm.Show();
                        }
                    }
                    if (dbUserName != txtUserName.Text)
                    {
                        MessageBox.Show("Please Type your User Name in Proper Case", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtUserName.Clear();
                        txtUserName.Focus();
                    }
                }
                else
                {
                    MessageBox.Show("Login is Failed...Try again !", "Login Denied", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtUserName.Clear();
                    txtPassword.Clear();
                    txtUserName.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #27
0
        /// <summary>
        /// Unix-like Crypt-MD5 function
        /// </summary>
        /// <param name="password">The user password</param>
        /// <param name="salt">The salt or the pepper of the password</param>
        /// <returns>a human readable string</returns>
        public static String crypt(String password, String salt)
        {
            int saltEnd;
            int len;
            int value;
            int i;

            byte[] final;
            byte[] passwordBytes;
            byte[] saltBytes;
            byte[] ctx;

            StringBuilder result;
            HashAlgorithm x_hash_alg = HashAlgorithm.Create("MD5");

            // Skip magic if it exists
            if (salt.StartsWith(magic))
            {
                salt = salt.Substring(magic.Length);
            }

            // Remove password hash if present
            if ((saltEnd = salt.LastIndexOf('$')) != -1)
            {
                salt = salt.Substring(0, saltEnd);
            }

            // Shorten salt to 8 characters if it is longer
            if (salt.Length > 8)
            {
                salt = salt.Substring(0, 8);
            }

            ctx   = Encoding.ASCII.GetBytes(password + magic + salt);
            final = x_hash_alg.ComputeHash(Encoding.ASCII.GetBytes(password + salt + password));

            // Add as many characters of ctx1 to ctx
            for (len = password.Length; len > 0; len -= 16)
            {
                if (len > 16)
                {
                    ctx = Concat(ctx, final);
                }
                else
                {
                    ctx = Concat(ctx, final, len);
                }
            }

            // Then something really weird...
            passwordBytes = Encoding.ASCII.GetBytes(password);

            for (i = password.Length; i > 0; i >>= 1)
            {
                if ((i & 1) == 1)
                {
                    ctx = Concat(ctx, new byte[] { 0 });
                }
                else
                {
                    ctx = Concat(ctx, new byte[] { passwordBytes[0] });
                }
            }

            final = x_hash_alg.ComputeHash(ctx);

            // Do additional mutations
            saltBytes = Encoding.ASCII.GetBytes(salt);
            for (i = 0; i < 1000; i++)
            {
                var ctx1 = new byte[] { };
                if ((i & 1) == 1)
                {
                    ctx1 = Concat(ctx1, passwordBytes);
                }
                else
                {
                    ctx1 = Concat(ctx1, final);
                }
                if (i % 3 != 0)
                {
                    ctx1 = Concat(ctx1, saltBytes);
                }
                if (i % 7 != 0)
                {
                    ctx1 = Concat(ctx1, passwordBytes);
                }
                if ((i & 1) != 0)
                {
                    ctx1 = Concat(ctx1, final);
                }
                else
                {
                    ctx1 = Concat(ctx1, passwordBytes);
                }
                final = x_hash_alg.ComputeHash(ctx1);
            }

            result = new StringBuilder();
            // Add the password hash to the result string
            value = ((final[0] & 0xff) << 16) | ((final[6] & 0xff) << 8)
                    | (final[12] & 0xff);
            result.Append(to64(value, 4));
            value = ((final[1] & 0xff) << 16) | ((final[7] & 0xff) << 8)
                    | (final[13] & 0xff);
            result.Append(to64(value, 4));
            value = ((final[2] & 0xff) << 16) | ((final[8] & 0xff) << 8)
                    | (final[14] & 0xff);
            result.Append(to64(value, 4));
            value = ((final[3] & 0xff) << 16) | ((final[9] & 0xff) << 8)
                    | (final[15] & 0xff);
            result.Append(to64(value, 4));
            value = ((final[4] & 0xff) << 16) | ((final[10] & 0xff) << 8)
                    | (final[5] & 0xff);
            result.Append(to64(value, 4));
            value = final[11] & 0xff;
            result.Append(to64(value, 2));

            // Return result string
            return(magic + salt + "$" + result);
        }
Beispiel #28
0
        internal StrongNameSignature StrongHash(Stream stream, StrongNameOptions options)
        {
            StrongNameSignature info = new StrongNameSignature();

            HashAlgorithm hash = HashAlgorithm.Create(TokenAlgorithm);
            CryptoStream  cs   = new CryptoStream(Stream.Null, hash, CryptoStreamMode.Write);

            // MS-DOS Header - always 128 bytes
            // ref: Section 24.2.1, Partition II Metadata
            byte[] mz = new byte [128];
            stream.Read(mz, 0, 128);
            if (BitConverterLE.ToUInt16(mz, 0) != 0x5a4d)
            {
                return(null);
            }
            UInt32 peHeader = BitConverterLE.ToUInt32(mz, 60);

            cs.Write(mz, 0, 128);
            if (peHeader != 128)
            {
                byte[] mzextra = new byte [peHeader - 128];
                stream.Read(mzextra, 0, mzextra.Length);
                cs.Write(mzextra, 0, mzextra.Length);
            }

            // PE File Header - always 248 bytes
            // ref: Section 24.2.2, Partition II Metadata
            byte[] pe = new byte [248];
            stream.Read(pe, 0, 248);
            if (BitConverterLE.ToUInt32(pe, 0) != 0x4550)
            {
                return(null);
            }
            if (BitConverterLE.ToUInt16(pe, 4) != 0x14c)
            {
                return(null);
            }
            // MUST zeroize both CheckSum and Security Directory
            byte[] v = new byte [8];
            Buffer.BlockCopy(v, 0, pe, 88, 4);
            Buffer.BlockCopy(v, 0, pe, 152, 8);
            cs.Write(pe, 0, 248);

            UInt16 numSection    = BitConverterLE.ToUInt16(pe, 6);
            int    sectionLength = (numSection * 40);

            byte[] sectionHeaders = new byte [sectionLength];
            stream.Read(sectionHeaders, 0, sectionLength);
            cs.Write(sectionHeaders, 0, sectionLength);

            UInt32 cliHeaderRVA = BitConverterLE.ToUInt32(pe, 232);
            UInt32 cliHeaderPos = RVAtoPosition(cliHeaderRVA, numSection, sectionHeaders);
            int    cliHeaderSiz = (int)BitConverterLE.ToUInt32(pe, 236);

            // CLI Header
            // ref: Section 24.3.3, Partition II Metadata
            byte[] cli = new byte [cliHeaderSiz];
            stream.Position = cliHeaderPos;
            stream.Read(cli, 0, cliHeaderSiz);

            UInt32 strongNameSignatureRVA = BitConverterLE.ToUInt32(cli, 32);

            info.SignaturePosition = RVAtoPosition(strongNameSignatureRVA, numSection, sectionHeaders);
            info.SignatureLength   = BitConverterLE.ToUInt32(cli, 36);

            UInt32 metadataRVA = BitConverterLE.ToUInt32(cli, 8);

            info.MetadataPosition = RVAtoPosition(metadataRVA, numSection, sectionHeaders);
            info.MetadataLength   = BitConverterLE.ToUInt32(cli, 12);

            if (options == StrongNameOptions.Metadata)
            {
                cs.Close();
                hash.Initialize();
                byte[] metadata = new byte [info.MetadataLength];
                stream.Position = info.MetadataPosition;
                stream.Read(metadata, 0, metadata.Length);
                info.Hash = hash.ComputeHash(metadata);
                return(info);
            }

            // now we hash every section EXCEPT the signature block
            for (int i = 0; i < numSection; i++)
            {
                UInt32 start   = BitConverterLE.ToUInt32(sectionHeaders, i * 40 + 20);
                int    length  = (int)BitConverterLE.ToUInt32(sectionHeaders, i * 40 + 16);
                byte[] section = new byte [length];
                stream.Position = start;
                stream.Read(section, 0, length);
                if ((start <= info.SignaturePosition) && (info.SignaturePosition < start + length))
                {
                    // hash before the signature
                    int before = (int)(info.SignaturePosition - start);
                    if (before > 0)
                    {
                        cs.Write(section, 0, before);
                    }
                    // copy signature
                    info.Signature = new byte [info.SignatureLength];
                    Buffer.BlockCopy(section, before, info.Signature, 0, (int)info.SignatureLength);
                    Array.Reverse(info.Signature);
                    // hash after the signature
                    int s     = (int)(before + info.SignatureLength);
                    int after = (int)(length - s);
                    if (after > 0)
                    {
                        cs.Write(section, s, after);
                    }
                }
                else
                {
                    cs.Write(section, 0, length);
                }
            }

            cs.Close();
            info.Hash = hash.Hash;
            return(info);
        }
        /// <summary>
        /// 使用指定算法计算Hash值
        /// </summary>
        /// <param name="bytes"></param>
        /// <param name="hashName"></param>
        /// <returns></returns>
        public static byte[] Hash(this byte[] bytes, string hashName = "ModSystem.Security.Cryptography.HashAlgorithm")
        {
            var algorithm = string.IsNullOrEmpty(hashName) ? HashAlgorithm.Create() : HashAlgorithm.Create(hashName);

            return(algorithm != null?algorithm.ComputeHash(bytes) : null);
        }
Beispiel #30
0
 public static string ToMd5(this string str)
 {
     return(BitConverter.ToString(HashAlgorithm.Create(HashAlgorithmName.MD5.Name).ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", ""));
 }