public void Compuate_with_json_string_returns_hash_test()
        {
            var compute = new ComputeHash();
            var result  = compute.Compute(JsonConvert.SerializeObject(_hashTestParent));

            Assert.AreEqual(HashObjectString, result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseObject"/> class.
        /// </summary>
        /// <param name="sOrigUrl">The original URL.</param>
        /// <param name="sPathToFile">The path to file.</param>
        /// <param name="sFileName">Name of the file.</param>
        /// <param name="sFileExtension">The file extension.</param>
        /// <param name="sContentType">Type of the content.</param>
        /// <param name="oRequestMsg">The request message.</param>
        /// <param name="listCookieInformation">The list cookie information.</param>
        public BaseObject(
            string sOrigUrl,
            string sPathToFile,
            string sFileName,
            string sFileExtension,
            string sContentType,
            HTTPMsg oRequestMsg,
            List <string> listCookieInformation)
        {
            this.RequestMessage = oRequestMsg;
            this.OriginalUrl    = sOrigUrl;
            this.PathToFileName = sPathToFile;
            this.FileName       = sFileName;
            this.FileExtension  = sFileExtension;
            this.ContentType    = sContentType;

            this.Referrer    = ObjectParser.ParseReferer((HttpRequestHeader)oRequestMsg.HTTPHeader);
            this.HostAddress = ObjectParser.ParseHostAddress((HttpRequestHeader)oRequestMsg.HTTPHeader);

            this.Content      = oRequestMsg.PairMessages[0].HTTPContent.Content;
            this.TimeStamp    = oRequestMsg.TimeStamp;
            this.ExportSource = oRequestMsg.ExportSources[0];

            this.CookieInformation = listCookieInformation;
            this.UniqueHash        = ComputeHash.GetMd5Hash(this.Content);


            this.FileSize            = this.Content.LongLength;
            this.ListOfNewReferences = new List <string>();
        }
        public void Compuate_with_empty_string_returns_hash_test()
        {
            var compute = new ComputeHash();
            var result  = compute.Compute(string.Empty);

            Assert.AreEqual(HashEmptyString, result);
        }
Exemplo n.º 4
0
        public String StoreFile(FileInfo file)
        {
            string hash = ComputeHash.SHA1(file);

            if (FileExists(hash))
            {
                return(hash);
            }

            FileInfo destination = GetFileInfo(hash);

            Debug.Assert(destination != null, "destination filename is null");
            Directory.CreateDirectory(destination.DirectoryName);
            File.Copy(file.FullName, destination.FullName);

            // verify the hash, paranoid, but would detect some possible hardware issues
            string hashNew = ComputeHash.SHA1(destination);

            if (hash != hashNew)
            {
                destination.Delete();
                throw new Exception("Copy not equal to original image (SHA1 hash differs)");
            }
            destination.Attributes = destination.Attributes | FileAttributes.ReadOnly;
            return(hashNew);
        }
Exemplo n.º 5
0
 public FileInformation(FileInfo file)
     : this()
 {
     Id       = ComputeHash.SHA1(file);
     FileSize = file.Length;
     Title    = file.Name;
     MimeType = MimeExtractor.MimeType.Extract(file);
     RefreshMetadata(file);
     AddPath(file);
 }
Exemplo n.º 6
0
        public YouRoomClient(string consumerKey, string consumerSecret, ComputeHash hashFunction, RetrievePinCode retrievePin)
        {
            Assert.IsNotNullOrWhiteSpace(consumerKey, nameof(consumerKey));
            Assert.IsNotNullOrWhiteSpace(consumerSecret, nameof(consumerSecret));
            Assert.IsNotNull(hashFunction, nameof(hashFunction));
            Assert.IsNotNull(retrievePin, nameof(retrievePin));

            this.consumerKey    = consumerKey;
            this.consumerSecret = consumerSecret;
            this.retrievePin    = retrievePin;
            this.accessToken    = null;

            OAuthUtility.ComputeHash = (key, buffer) => hashFunction(key, buffer);
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            try
            {
                var response = (new HttpClient()).GetAsync(args[0]).Result;

                // Convert to JSON Object and back so that formatting is exactly the same as the implementation used by telemetry
                var templatejson = response.Content.ReadAsStringAsync().Result.FromJson <Template>().ToJson();

                Console.WriteLine(ComputeHash.MurmurHash64(templatejson).ToString());
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Compresses each archive part and construct index.rdf file with webpage base metadata.
        /// </summary>
        /// <param name="oZipArchive">The parent zip archive.</param>
        /// <param name="oTimeStamp">The time stamp of parent archive.</param>
        /// <param name="sExportDirectory">The export directory.</param>
        /// <param name="iPartPosition">The position of archive part.</param>
        public void CompressArchivePart(ZipArchive oZipArchive, DateTime oTimeStamp, string sExportDirectory, int iPartPosition)
        {
            // INDEX RDF
            var sRdfData = "<?xml version=\"1.0\"?>\n" +
                           "       <RDF:RDF xmlns:MAF=\"http://maf.mozdev.org/metadata/rdf#\"\n" +
                           "       xmlns:NC=\"http://netfox.fit.vutbr.cz/About.en.cshtml\"\n" +
                           "       xmlns:RDF=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" +
                           "  <RDF:Description RDF:about=\"urn:root\">\n" +
                           "    <MAF:originalurl RDF:resource=\"" + "http://" + this.ParentObject.HostAddress + "/\"/>\n" +
                           "    <MAF:title RDF:resource=\"" + this.ParentObject.GetTitle() + "\"/>\n" +
                           "    <MAF:archivetime RDF:resource=\"" + DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local).ToString("dd.MM.yyyy hh: mm:ss tt") + "\"/>\n" +
                           "    <MAF:indexfilename RDF:resource=\"index.html\"/>\n" +
                           "    <MAF:charset RDF:resource=\"" + this.ParentObject.GetCharSet() + "\"/>\n" +
                           "  </RDF:Description>\n" +
                           "</RDF:RDF>";

            // END INDEX RDF

            //Do zip comprimation
            this.BaseFolder = ComputeHash.GetMd5Hash(oTimeStamp.Ticks + this.ParentObject.HostAddress + this.ParentObject.GetCharSet() + this.ExportListOfArchiveObjects.Count + iPartPosition);

            //RDF WRITE
            var rdfEntry            = oZipArchive.CreateEntry(this.BaseFolder + "/" + "index.rdf");
            var rdfEntryWriteStream = new BinaryWriter(rdfEntry.Open());

            rdfEntryWriteStream.Write(Encoding.GetEncoding(437).GetBytes(sRdfData));
            rdfEntryWriteStream.Dispose();
            //END RDF WRITE

            foreach (var oItemToArchive in this.ExportListOfArchiveObjects)
            {
                if (!(oItemToArchive is ParentObject))
                {
                    oItemToArchive.FileName = "index_files/" + oItemToArchive.FileName;
                    if (oItemToArchive is TextObject)
                    {
                        ((TextObject)oItemToArchive).ProcessReferences();
                    }
                }
                else
                {
                    ((ParentObject)oItemToArchive).ProcessReferences();
                }

                oItemToArchive.SaveObjectContent(oZipArchive, sExportDirectory, this.BaseFolder);
            }
        }
        public void Compuate_different_hash_returns_false_test()
        {
            var compute = new ComputeHash();

            var obj = new HashTestParent()
            {
                someProperty = "test one",
                someChild    = new HashTestChild()
                {
                    childProperty = "test Child"
                }
            };
            var latestHash = compute.Compute(JsonConvert.SerializeObject(obj));
            var result     = compute.Compare(HashObjectString, latestHash);

            Assert.IsFalse(result);
        }
Exemplo n.º 10
0
 public Handler(
     IAmazonSimpleNotificationService snsClient,
     IAmazonS3 s3Client,
     ApprovalCanceler approvalCanceler,
     ComputeHash hash,
     ILinkService linkService,
     IOptions <Config> config,
     ILogger <Handler> logger
     )
 {
     this.snsClient        = snsClient;
     this.s3Client         = s3Client;
     this.approvalCanceler = approvalCanceler;
     this.computeHash      = hash;
     this.linkService      = linkService;
     this.config           = config.Value;
     this.logger           = logger;
 }
        public void Compuate_with_null_throws_error_test()
        {
            var compute = new ComputeHash();

            Assert.That(() => compute.Compute(null), Throws.TypeOf <ArgumentNullException>());
        }
        public IActionResult Index([FromBody] DTOMigration Migration)
        {
            // LoginStatus to return
            LoginStatus objLoginStatus = new LoginStatus();

            objLoginStatus.isLoggedIn = false;

            if ((Migration.userName != null) && (Migration.password != null) && (Migration.passwordNew != null))
            {
                // Get values passed
                var paramUserName    = Migration.userName;
                var paramPassword    = ComputeHash.GetSwcMD5(paramUserName.Trim().ToLower() + Migration.password.Trim());
                var paramPasswordNew = Migration.passwordNew;

                var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();
                optionsBuilder.UseSqlServer(GetConnectionString());

                using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
                {
                    // Must be in legacy User table
                    var objAdefHelpDeskUser = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers
                                               where AdefHelpDeskUsers.Username == paramUserName
                                               where AdefHelpDeskUsers.Password == paramPassword
                                               select AdefHelpDeskUsers).FirstOrDefault();

                    if (objAdefHelpDeskUser != null)
                    {
                        // Email Validation ****************************

                        if (objAdefHelpDeskUser.Email == null)
                        {
                            objLoginStatus.status     = "The Email for this account is not valid. It cannot be migrated.";
                            objLoginStatus.isLoggedIn = false;
                            return(Ok(objLoginStatus));
                        }

                        EmailValidation objEmailValidation = new EmailValidation();
                        if (!objEmailValidation.IsValidEmail(objAdefHelpDeskUser.Email))
                        {
                            objLoginStatus.status     = "The Email for this account is not valid. It cannot be migrated.";
                            objLoginStatus.isLoggedIn = false;
                            return(Ok(objLoginStatus));
                        }

                        // Migrate Account

                        var user = new ApplicationUser {
                            UserName = paramUserName, Email = objAdefHelpDeskUser.Email
                        };
                        var result = _userManager.CreateAsync(user, paramPasswordNew).Result;

                        if (result.Succeeded)
                        {
                            // Sign the User in
                            var SignInResult = _signInManager.PasswordSignInAsync(
                                paramUserName, paramPasswordNew, false, lockoutOnFailure: false).Result;

                            if (!SignInResult.Succeeded)
                            {
                                // Return the error
                                objLoginStatus.status     = $"Could not sign user {paramUserName} in.";
                                objLoginStatus.isLoggedIn = false;
                                return(Ok(objLoginStatus));
                            }
                            else
                            {
                                try
                                {
                                    // Everything worked
                                    // Update the users password in the legacy table
                                    objAdefHelpDeskUser.Password = ComputeHash.GetSwcMD5(paramUserName.Trim().ToLower() + paramPasswordNew.Trim());
                                    context.SaveChanges();
                                }
                                catch
                                {
                                    // Do nothing if this does not work
                                    // This password is only needed if connecting from the older
                                    // Non Angular version of ADefHelpDesk
                                }

                                // Success
                                objLoginStatus.status     = $"Logged {paramUserName} in.";
                                objLoginStatus.isLoggedIn = true;
                                return(Ok(objLoginStatus));
                            }
                        }
                        else
                        {
                            // Return the errors from the Memberhip API Creation
                            string strErrors = "";
                            foreach (var Error in result.Errors)
                            {
                                strErrors = strErrors + "\n" + Error.Description;
                            }

                            // Return the error
                            objLoginStatus.status     = strErrors;
                            objLoginStatus.isLoggedIn = false;
                            return(Ok(objLoginStatus));
                        }
                    }
                    else
                    {
                        objLoginStatus.status = "Orginal password does not match.";
                        return(Ok(objLoginStatus));
                    }
                }
            }

            objLoginStatus.status = "Authentication Failure";

            return(Ok(objLoginStatus));
        }
Exemplo n.º 13
0
        public LoginStatus ValidateUser(DTOAuthentication Authentication)
        {
            // LoginStatus to return
            LoginStatus objLoginStatus = new LoginStatus();

            objLoginStatus.isLoggedIn = false;

            // Get values passed
            var paramUserName = Authentication.userName;
            var paramPassword = Authentication.password;

            if ((paramUserName != null) && (paramPassword != null))
            {
                var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();
                optionsBuilder.UseSqlServer(GetConnectionString());

                // Only check the legacy User password if user is not in the main table
                if (_userManager.Users.Where(x => x.UserName == paramUserName).FirstOrDefault() == null)
                {
                    using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
                    {
                        // First check the legacy User table
                        var objAdefHelpDeskUser = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers
                                                   where AdefHelpDeskUsers.Username == paramUserName
                                                   where AdefHelpDeskUsers.Password != ""
                                                   select AdefHelpDeskUsers).FirstOrDefault();

                        if (objAdefHelpDeskUser != null)
                        {
                            // User is in the Legacy table and the password is not null
                            // Check their password to see if this account can be migrated
                            if (objAdefHelpDeskUser.Password ==
                                ComputeHash.GetSwcMD5(paramUserName.Trim().ToLower() + paramPassword.Trim()))
                            {
                                // Return that this account can be migrated
                                objLoginStatus.status = "Migrate";
                                return(objLoginStatus);
                            }
                        }
                    }
                }

                // Check to see if the user needs to Verify their account
                using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
                {
                    var objAdefHelpDeskUser = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers
                                               where AdefHelpDeskUsers.Username == paramUserName
                                               select AdefHelpDeskUsers).FirstOrDefault();

                    if (objAdefHelpDeskUser != null)
                    {
                        if (objAdefHelpDeskUser.VerificationCode != null)
                        {
                            objLoginStatus.status = "Verify";
                            return(objLoginStatus);
                        }
                    }
                }

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = _signInManager.PasswordSignInAsync(
                    paramUserName,
                    paramPassword, false,
                    lockoutOnFailure: false).Result;

                if (result.Succeeded)
                {
                    objLoginStatus.status     = "Success";
                    objLoginStatus.isLoggedIn = true;
                    return(objLoginStatus);
                }
                if (result.RequiresTwoFactor)
                {
                    objLoginStatus.status = "RequiresVerification";
                    return(objLoginStatus);
                }
                if (result.IsLockedOut)
                {
                    objLoginStatus.status = "IsLockedOut";
                    return(objLoginStatus);
                }
            }

            objLoginStatus.status = "Authentication Failure";

            return(objLoginStatus);
        }
Exemplo n.º 14
0
        public IActionResult Index([FromBody] DTOAuthentication Authentication)
        {
            // LoginStatus to return
            LoginStatus objLoginStatus = new LoginStatus();

            objLoginStatus.isLoggedIn = false;

            // Get values passed
            var paramUserName = Authentication.userName;
            var paramPassword = Authentication.password;

            if ((paramUserName != null) && (paramPassword != null))
            {
                // First log the user out
                if (this.User.Identity.IsAuthenticated)
                {
                    // Log user out
                    _signInManager.SignOutAsync().Wait();
                }

                var optionsBuilder = new DbContextOptionsBuilder <ADefHelpDeskContext>();
                optionsBuilder.UseSqlServer(GetConnectionString());

                try
                {
                    // Only check the legacy User password if user is not in the main table
                    if (_userManager.Users.Where(x => x.UserName == paramUserName).FirstOrDefault() == null)
                    {
                        using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
                        {
                            // First check the legacy User table
                            var objAdefHelpDeskUser = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers
                                                       where AdefHelpDeskUsers.Username == paramUserName
                                                       where AdefHelpDeskUsers.Password != ""
                                                       select AdefHelpDeskUsers).FirstOrDefault();

                            if (objAdefHelpDeskUser != null)
                            {
                                // User is in the Legacy table and the password is not null
                                // Check their password to see if this account can be migrated
                                if (objAdefHelpDeskUser.Password ==
                                    ComputeHash.GetSwcMD5(paramUserName.Trim().ToLower() + paramPassword.Trim()))
                                {
                                    // Return that this account can be migrated
                                    objLoginStatus.status = "Migrate";
                                    return(Ok(objLoginStatus));
                                }
                            }
                        }
                    }
                }
                catch
                {
                    // There may have been an error because this is an upgrade from a version
                    // of Adefhelpdesk before the AspNetUsers tables existed
                    using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
                    {
                        // Check the legacy User table
                        var objAdefHelpDeskUser = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers
                                                   where AdefHelpDeskUsers.Username == paramUserName
                                                   where AdefHelpDeskUsers.Password != ""
                                                   select AdefHelpDeskUsers).FirstOrDefault();

                        if (objAdefHelpDeskUser != null)
                        {
                            // User is in the Legacy table and the password is not null
                            // Check their password
                            if (objAdefHelpDeskUser.Password ==
                                ComputeHash.GetSwcMD5(paramUserName.Trim().ToLower() + paramPassword.Trim()))
                            {
                                // This database must be upgraded to ass the AspNetUseers table (for anything else to work)
                                InstallWizardController.RunUpdateScripts("00.00.00", _hostEnvironment, GetConnectionString());

                                // Return that this account can be migrated
                                objLoginStatus.status = "Migrate";
                                return(Ok(objLoginStatus));
                            }
                            else
                            {
                                objLoginStatus.status = "Error: Account needs to be migrated, but account cannot be migrated because the password is incorrect";
                                return(Ok(objLoginStatus));
                            }
                        }
                    }
                }

                // Check to see if the user needs to Verify their account
                using (var context = new ADefHelpDeskContext(optionsBuilder.Options))
                {
                    var objAdefHelpDeskUser = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers
                                               where AdefHelpDeskUsers.Username == paramUserName
                                               select AdefHelpDeskUsers).FirstOrDefault();

                    if (objAdefHelpDeskUser != null)
                    {
                        if (objAdefHelpDeskUser.VerificationCode != null)
                        {
                            objLoginStatus.status = "Verify";
                            return(Ok(objLoginStatus));
                        }
                    }
                }

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = _signInManager.PasswordSignInAsync(
                    paramUserName,
                    paramPassword, false,
                    lockoutOnFailure: false).Result;

                if (result.Succeeded)
                {
                    objLoginStatus.status     = "Success";
                    objLoginStatus.isLoggedIn = true;
                    return(Ok(objLoginStatus));
                }
                if (result.RequiresTwoFactor)
                {
                    objLoginStatus.status = "RequiresVerification";
                    return(Ok(objLoginStatus));
                }
                if (result.IsLockedOut)
                {
                    objLoginStatus.status = "IsLockedOut";
                    return(Ok(objLoginStatus));
                }
            }

            objLoginStatus.status = "Authentication Failure";

            return(Ok(objLoginStatus));
        }
Exemplo n.º 15
0
 /// <summary>
 /// Initialization of archive compressing and constructing compressed file.
 /// </summary>
 private void CompressInitialize()
 {
     this.ArchiveName      = this._oParentObject.HostAddress + "_" + ComputeHash.GetMd5Hash(this._oParentObject.HostAddress + this._oParentObject.TimeStamp.Ticks) + ".maff";
     this._fsZipFileStream = new FileStream(this.ExportDirectory + @"\" + this.ArchiveName, FileMode.Create);
     this._zipArchive      = new ZipArchive(this._fsZipFileStream, ZipArchiveMode.Update);
 }