Ejemplo n.º 1
0
        public bool Register(string username, string password)
        {
            SHA1Hasher sha1 = new SHA1Hasher();

            sha1.ComputeHash(Encoding.Unicode.GetBytes(password));
            UserInfo userInfo = new UserInfo(username, sha1.HashedString);

            try
            {
                using (var context = new DBContext())
                {
                    if (context.TryAddUser(userInfo) != -1)
                    {
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                //Shouldnt throw exceptions
                //throw new Exception("Error registering the user.", e);
            }

            return(false);
        }
Ejemplo n.º 2
0
        public void Hashers_HMAC_SHA1()
        {
            byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            byte[] key;
            byte[] digest;

            key    = new byte[] { 0, 1, 2, 3, 4, 5 };
            digest = SHA1Hasher.Compute(key, data);
            Assert.AreEqual(SHA1Hasher.DigestSize, digest.Length);

            key = new byte[128];
            for (int i = 0; i < key.Length; i++)
            {
                key[i] = (byte)i;
            }

            digest = SHA1Hasher.Compute(key, data);
            Assert.AreEqual(SHA1Hasher.DigestSize, digest.Length);

            // $todo(jeff.lill):
            //
            // At some point I'd like to verify this
            // against a hash produced by another
            // codebase.
        }
Ejemplo n.º 3
0
        private static Hasher CreateHasher(int crypto)
        {
            Hasher hasher = null;

            switch (crypto)
            {
            case (int)HashName.MD5:
                hasher = new MD5Hasher();
                break;

            case (int)HashName.SHA1:
                hasher = new SHA1Hasher();
                break;

            case (int)HashName.SHA256:
                hasher = new SHA256Hasher();
                break;

            case (int)HashName.SHA384:
                hasher = new SHA384Hasher();
                break;

            case (int)HashName.SHA512:
                hasher = new SHA512Hasher();
                break;
            }
            return(hasher);
        }
        private void AddRecord(string fileName, CryptoChoice settings, string fileHash)
        {
            byte[] encryptedDataFile = ReadDataFile();
            byte[] fileBytes         = DecryptDataFile(encryptedDataFile);

            SHA1Hasher sha1 = new SHA1Hasher();

            sha1.ComputeHash(Encoding.UTF8.GetBytes(IdentificationUsername));
            SHA1Hasher sha2 = new SHA1Hasher();

            sha2.ComputeHash(Encoding.UTF8.GetBytes(fileName));

            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine($"{sha2.HashedString}:{sha1.HashedString}:{fileHash}:{settings.Choice.ToString()}:{Encoding.UTF8.GetString(settings.Key)}:{settings.Depad}");
            byte[] recordBytes = Encoding.UTF8.GetBytes(stringBuilder.ToString());

            byte[] newFileBytes = new byte[fileBytes.Length + recordBytes.Length];
            Array.Copy(fileBytes, 0, newFileBytes, 0, fileBytes.Length);
            Array.Copy(recordBytes, 0, newFileBytes, fileBytes.Length, recordBytes.Length);

            encryptedDataFile = EncryptDataFile(newFileBytes);

            WriteDataFile(encryptedDataFile);
        }
Ejemplo n.º 5
0
        public RemoteUserInfo Login(string username, string password)
        {
            RemoteUserInfo answer = null;

            SHA1Hasher sha1 = new SHA1Hasher();

            sha1.ComputeHash(Encoding.Unicode.GetBytes(password));
            UserInfo userInfo = new UserInfo(username, sha1.HashedString);

            try
            {
                using (var context = new DBContext())
                {
                    if (context.CheckUserCredentials(userInfo))
                    {
                        SessionManager.Instance.AddSession(GetChannelIdentification(), userInfo);
                        answer               = new RemoteUserInfo();
                        answer.Username      = userInfo.Username;
                        answer.LeftoverSpace = userInfo.LeftoverSpace;
                    }
                }
            }
            catch (Exception e)
            {
                //Shouldnt throw exceptions
                //throw new Exception("Error logging in.", e);
            }

            return(answer);
        }
Ejemplo n.º 6
0
        public void HashString(string content, string expectedHash)
        {
            var SHA1Hasher = new SHA1Hasher(new Mock <IRetryableFileOpener>(MockBehavior.Strict).Object);

            var hash = SHA1Hasher.GetHash(content);

            Assert.AreEqual(expectedHash, hash);
        }
Ejemplo n.º 7
0
        public void HashString_NullContent()
        {
            var SHA1Hasher = new SHA1Hasher(new Mock <IRetryableFileOpener>(MockBehavior.Strict).Object);

            var ex = Assert.Throws <InvalidOperationException>(() => SHA1Hasher.GetHash((string)null));

            Assert.AreEqual("Can't calculate hash for null content.", ex.Message);
        }
Ejemplo n.º 8
0
        public void RequestFileDownload(string fileName, string directoryPath, string supposedFileHash)
        {
            string FileManagerServiceUrl = "http://localhost:56082/MyCloudStore/CloudStoreService.svc";
            var    serviceUrl            = string.Format($"{FileManagerServiceUrl}/DownloadFile/{fileName}");
            var    request = (HttpWebRequest)WebRequest.Create(serviceUrl);

            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (var fileStream = response.GetResponseStream())
                    {
                        if (fileStream == null)
                        {
                            System.Windows.Forms.MessageBox.Show("File not recieved");
                            return;
                        }

                        byte[] fileBytes = fileStream.ReadToEnd();

                        //decrypt bytes
                        byte[] decryptedFile;
                        try
                        {
                            decryptedFile = cryptionController.DecryptFile(fileBytes, fileName);
                        }
                        catch (Exception e)
                        {
                            throw new Exception("Error decrypting the downloaded file: " + e.Message);
                        }

                        //Compare hash (double check since the cryptionController already does this
                        SHA1Hasher sha1 = new SHA1Hasher();
                        sha1.ComputeHash(decryptedFile);
                        string hashValue = sha1.HashedString;

                        if (hashValue != supposedFileHash)
                        {
                            System.Windows.Forms.MessageBox.Show("Your downloaded file's hash and its recorded hash before uploading do not match!");
                        }

                        //save them to a location
                        File.WriteAllBytes(Path.Combine(directoryPath, fileName), decryptedFile);

                        //open with adequate application
                        System.Diagnostics.Process.Start(Path.Combine(directoryPath, fileName));
                    }

                    System.Windows.Forms.MessageBox.Show(string.Format("Client: Receive Response HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription));
                }
            }
            catch (Exception e)
            {
                throw new Exception("Error downloading the file: " + e.GetFullMessage());
            }
        }
Ejemplo n.º 9
0
        public void HashFileInfo_FileDoesntExist()
        {
            var info       = new FileInfo("fakeFile");
            var SHA1Hasher = new SHA1Hasher(new RetryableFileOpener());
            var ex         = Assert.Throws <FileNotFoundException>(() => SHA1Hasher.GetHash(info));

            //mono 3 uses " instead of ' around file name
            Assert.True(ex.Message.StartsWith("Could not find file"));
            Assert.True(ex.Message.Contains(info.FullName));
        }
        private byte[] GenerateBytePattern(string fileName)
        {
            SHA1Hasher sha1 = new SHA1Hasher();

            sha1.ComputeHash(Encoding.UTF8.GetBytes(IdentificationUsername));
            SHA1Hasher sha2 = new SHA1Hasher();

            sha2.ComputeHash(Encoding.UTF8.GetBytes(fileName));

            return(Encoding.UTF8.GetBytes(sha2.HashedString + ":" + sha1.HashedString));
        }
        static void Main(string[] args)
        {
            byte[]     input = new byte[] { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66 };
            SHA1Hasher sha1  = new SHA1Hasher();
            var        sha11 = new SHA1CryptoServiceProvider();

            //byte[] hash1 = sha11.ComputeHash(input);
            //uint[] hash2 = sha1.ComputeHash(input);

            //Console.WriteLine(CryptoHelpers.byteArrayToString(hash1));
            //Console.WriteLine(sha1.HashedString);

            //string data = "pricam nesto";
            //sha1.ComputeHash(Encoding.UTF8.GetBytes(data));
            //string hashBefore = sha1.HashedString;
            //byte[] key = new byte[16] { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76 };
            //string key2 = Encoding.UTF8.GetString(key);
            //TEACrypter tEACrypter = new TEACrypter(Encoding.UTF8.GetBytes(key2));
            //var resultBytes = TEACrypter.DepadData(tEACrypter.Decrypt(tEACrypter.Encrypt(TEACrypter.PadData(Encoding.UTF8.GetBytes(data)))));
            //string result = Encoding.UTF8.GetString(resultBytes);
            //sha1.ComputeHash(Encoding.UTF8.GetBytes(result));
            //string hashAfter = sha1.HashedString;

            //OneTimePadCrypter oneTimePadCrypter = new OneTimePadCrypter(Encoding.UTF8.GetBytes("sifrasifrasifras"));
            //byte[] encryptedBytes = oneTimePadCrypter.Encrypt(Encoding.UTF8.GetBytes(data));
            //byte[] fileBytes = oneTimePadCrypter.Decrypt(encryptedBytes);

            //byte[] bigArray = CryptoHelpers.ReadAllBytes("C:\\Users\\DjordjeNikolic\\Desktop\\Djole shit\\Cooking\\15591782_1328152383902883_659942100_n.jpg");
            //sha1.ComputeHash(bigArray);
            //string hashBefore = sha1.HashedString;

            //OneTimePadCrypter oneTimePadCrypter = new OneTimePadCrypter(Encoding.UTF8.GetBytes("sifrasifrasifras"));
            //byte[] encryptedBytes = oneTimePadCrypter.Encrypt(bigArray);
            //byte[] fileBytes = oneTimePadCrypter.Decrypt(encryptedBytes);

            //sha1.ComputeHash(fileBytes);
            //string hashAfter = sha1.HashedString;

            //if (hashAfter != hashBefore)
            //    Console.WriteLine("Something wrong");
            //else
            //    CryptoHelpers.WriteAllBytes("C:\\desktop.jpg", fileBytes);

            StringBuilder stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("nesto");

            byte[] sbBytes = Encoding.UTF8.GetBytes(stringBuilder.ToString());

            byte[] nestoBytes = Encoding.UTF8.GetBytes("nesto");

            byte[] newlineBytes = Encoding.UTF8.GetBytes(Environment.NewLine);
            Console.WriteLine(newlineBytes.Length);
        }
Ejemplo n.º 12
0
 public Configuration()
 {
     DefaultJavascriptMimeType        = "application/javascript";
     DefaultCssMimeType               = "text/css";
     DefaultCacheInvalidationStrategy = new DefaultCacheInvalidationStrategy();
     DefaultCssMinifier               = new Minifiers.CSS.MsMinifier();
     DefaultHashKeyName               = "r";
     DefaultJsMinifier          = new Minifiers.JavaScript.MsMinifier();
     DefaultTempPathProvider    = new TempPathProvider();
     DefaultRetryableFileOpener = new RetryableFileOpener();
     DefaultHasher = new SHA1Hasher(DefaultRetryableFileOpener);
 }
Ejemplo n.º 13
0
        public void RequestFileUpload(string filePath, CryptoChoice answer, bool replaceOnConflict = false)
        {
            string fileName = Path.GetFileName(filePath);

            byte[] fileBytes = File.ReadAllBytes(filePath);

            SHA1Hasher sha1 = new SHA1Hasher();

            sha1.ComputeHash(fileBytes);
            string hashValue = sha1.HashedString;

            byte[] encryptedBytes;
            try
            {
                encryptedBytes = cryptionController.EncryptFile(fileName, fileBytes, answer, replaceOnConflict);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException("Couldn't encrypt the file: " + e.Message);
            }

            HttpWebResponse resp = null;

            try
            {
                string FileManagerServiceUrl = "http://localhost:56082/MyCloudStore/CloudStoreService.svc";
                var    serviceUrl            = string.Format($"{FileManagerServiceUrl}/UploadFile/{fileName}/{hashValue}");
                var    request = (HttpWebRequest)WebRequest.Create(serviceUrl);
                request.Method      = "POST";
                request.ContentType = "text/plain";

                System.IO.Stream reqStream = request.GetRequestStream();
                reqStream.Write(encryptedBytes, 0, encryptedBytes.Length);
                reqStream.Close();

                resp = (HttpWebResponse)request.GetResponse();
                System.Windows.Forms.MessageBox.Show(string.Format("Client: Receive Response HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription));
            }
            catch (Exception e)
            {
                throw new Exception("Error uploading the file to the service: " + e.GetFullMessage());
            }
            finally
            {
                if (resp != null && resp.StatusCode != HttpStatusCode.OK)
                {
                    cryptionController.RemoveFileRecord(fileName);
                }

                resp.Dispose();
            }
        }
Ejemplo n.º 14
0
        public void HashFileInfo(string data)
        {
            var info = new FileInfo(data);

            var retryableFileOpener = new Mock <IRetryableFileOpener>(MockBehavior.Strict);

            retryableFileOpener.Setup(rfo => rfo.OpenFileStream(info, 5, FileMode.Open, FileAccess.Read, FileShare.Read))
            .Returns(new MemoryStream(Encoding.ASCII.GetBytes(data)));

            var SHA1Hasher = new SHA1Hasher(retryableFileOpener.Object);

            Assert.AreEqual(SHA1Hasher.GetHash(data), SHA1Hasher.GetHash(info));
        }
Ejemplo n.º 15
0
        public void Hashers_SHA1()
        {
            EnhancedMemoryStream ms;

            byte[] data;
            byte[] digest1, digest2;

            digest1 = SHA1Hasher.Compute(new byte[] { 0, 1, 2, 3 }, 0, 4);
            Assert.AreEqual(20, digest1.Length);
            Assert.AreEqual(20, SHA1Hasher.DigestSize);

            digest2 = SHA1Hasher.Compute(new byte[] { 1, 1, 2, 3 }, 0, 4);
            Assert.AreNotEqual(digest1, digest2);

            digest1 = SHA1Hasher.Compute(new byte[0]);
            Assert.AreEqual(20, digest1.Length);
            Assert.AreEqual(20, SHA1Hasher.DigestSize);

            digest1 = SHA1Hasher.Compute(new byte[] { 0, 1, 2, 3 });
            ms      = new EnhancedMemoryStream();

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(new byte[] { 0, 1, 2, 3 }, 0, 4);
            ms.Seek(0, SeekOrigin.Begin);
            digest2 = SHA1Hasher.Compute(ms, 4);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(20, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            data = new byte[2048];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            digest1 = SHA1Hasher.Compute(data);

            ms.Seek(0, SeekOrigin.Begin);
            ms.Write(data, 0, data.Length);
            ms.Seek(0, SeekOrigin.Begin);

            digest2 = SHA1Hasher.Compute(ms, data.Length);
            CollectionAssert.AreEqual(digest1, digest2);
            Assert.AreEqual(20, digest2.Length);
            Assert.AreEqual(0, ms.Position);

            digest1 = SHA1Hasher.Compute("hello");
            digest2 = SHA1Hasher.Compute("world");
            CollectionAssert.AreNotEqual(digest1, digest2);
            CollectionAssert.AreEqual(digest1, SHA1Hasher.Compute("hello"));
        }
        public byte[] EncryptFile(string fileName, byte[] fileBytes, CryptoChoice settings, bool replaceRecordIfConflict = false)
        {
            if (ReadRecord(fileName) != null)
            {
                if (replaceRecordIfConflict)
                {
                    RemoveRecord(fileName);
                }
                else
                {
                    throw new InvalidOperationException("The record for a file with this name already exists. If you want to replace it, pass another bool as an argument to the method.");
                }
            }

            SHA1Hasher sha1 = new SHA1Hasher();

            sha1.ComputeHash(fileBytes);
            string fileHash = sha1.HashedString;

            byte[] encryptedBytes;

            switch (settings.Choice)
            {
            case CryptoChoices.OneTimePad:
                OneTimePadCrypter otp = new OneTimePadCrypter(settings.Key);
                encryptedBytes = otp.Encrypt(fileBytes);
                break;

            case CryptoChoices.TEA:
                TEACrypter tea = new TEACrypter(settings.Key);
                if (TEACrypter.CheckIfDataNeedsPadding(fileBytes))
                {
                    fileBytes      = TEACrypter.PadData(fileBytes);
                    settings.Depad = true;
                }
                encryptedBytes = tea.Encrypt(fileBytes);
                break;

            default:
                throw new InvalidOperationException("Cryption settings are not valid: Desired cryption algorithm doesn't exist.");
            }

            AddRecord(fileName, settings, fileHash);

            return(encryptedBytes);
        }
        public byte[] DecryptFile(byte[] encryptedBytes, string fileName)
        {
            var foundRecord = ReadRecord(fileName);

            if (foundRecord == null)
            {
                throw new ArgumentException("There is no record for this file.");
            }

            CryptoChoice settings         = foundRecord.Item1;
            string       originalFileHash = foundRecord.Item2;

            byte[] fileBytes;
            switch (settings.Choice)
            {
            case CryptoChoices.OneTimePad:
                OneTimePadCrypter otp = new OneTimePadCrypter(settings.Key);
                fileBytes = otp.Decrypt(encryptedBytes);
                break;

            case CryptoChoices.TEA:
                TEACrypter tea = new TEACrypter(settings.Key);
                fileBytes = tea.Decrypt(encryptedBytes);
                if (settings.Depad)
                {
                    fileBytes = TEACrypter.DepadData(fileBytes);
                }
                break;

            default:
                throw new InvalidOperationException("Cryption settings are not valid: Desired cryption algorithm doesn't exist.");
            }

            SHA1Hasher sha1 = new SHA1Hasher();

            sha1.ComputeHash(fileBytes);

            if (originalFileHash != sha1.HashedString)
            {
                throw new Exception("The hash value of the decrypted file and the original file hash value do not match. Access denied.");
            }

            return(fileBytes);
        }
        public static long Create(String login, String password, long roleId)
        {
            SHA1Hasher.CalculatePasswordHash(password, out String passwordSalt, out String passwordHash);

            DAL.tblAuthenticationActor currItem = new DAL.tblAuthenticationActor()
            {
                Login        = login,
                PasswordSalt = passwordHash,
                PasswordHash = passwordHash,
                IsDeleted    = false,
                RoleId       = roleId
            };
            DAL.CurrDBContext.Get().tblAuthenticationActor.Add(currItem);
            DAL.CurrDBContext.Get().SaveChanges();

            long id = currItem.Id;

            return(id);
        }
        // for password Changing set 'Password' field to value, otherwise set 'Password' field = null
        // if PasswordSalt and PasswordHash recalculated to new values. It must changed in newActor too
        public static void Update(Actor newActor)
        {
            DAL.tblAuthenticationActor dataItem = DAL.CurrDBContext.Get().tblAuthenticationActor.Where(x => x.Id == newActor.Id).Single();

            dataItem.Login     = newActor.Login;
            dataItem.IsDeleted = newActor.IsDeleted;
            dataItem.RoleId    = newActor.RoleId;

            if (newActor.Password != null)
            {
                SHA1Hasher.CalculatePasswordHash(newActor.Password, out String passwordSalt, out String passwordHash);
                dataItem.PasswordSalt = passwordSalt;
                dataItem.PasswordHash = passwordHash;

                newActor.PasswordSalt = passwordSalt;
                newActor.PasswordHash = passwordHash;
            }

            DAL.CurrDBContext.Get().SaveChanges();
        }
Ejemplo n.º 20
0
        public HttpResponseMessage Access(HttpRequestMessage request)
        {
            IEnumerable <KeyValuePair <string, string> > queryStr = request.GetQueryNameValuePairs();
            string signature = queryStr.GetValue("signature");
            string timestamp = queryStr.GetValue("timestamp");
            string nonce     = queryStr.GetValue("nonce");
            string echostr   = queryStr.GetValue("echostr");

            Log4.Logger.Debug("signature:" + signature);
            Log4.Logger.Debug("timestamp:" + timestamp);
            Log4.Logger.Debug("nonce:" + nonce);
            Log4.Logger.Debug("echostr:" + echostr);

            string[] array = { DevConfig.Token, timestamp, nonce };
            Array.Sort(array);
            string hashed = string.Join(string.Empty, array);

            hashed = new SHA1Hasher().Hash(hashed);

            Log4.Logger.Debug("Hashed:" + hashed);

            if (hashed == signature)
            {
                Log4.Logger.Debug("Return echostr.");

                HttpResponseMessage response = new HttpResponseMessage();
                response.Content = new StringContent(echostr);
                return(response);
            }
            else
            {
                Log4.Logger.Debug("Return HttpStatusCode.Forbidden.");

                HttpResponseMessage response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
                return(response);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Authenticates the account credentials against the authentication extension.
        /// </summary>
        /// <param name="realm">The authentication realm.</param>
        /// <param name="account">The account ID.</param>
        /// <param name="password">The password.</param>
        /// <returns>A <see cref="AuthenticationResult" /> instance with the result of the operation.</returns>
        /// <remarks>
        /// <para>
        /// The <see cref="AuthenticationResult.Status" /> property indicates the disposition
        /// of the authentication operation.  Extensions will return <see cref="AuthenticationStatus.Authenticated" />
        /// if the operation was successful.  Authentication failures due to the
        /// sumbission of invalid credentials will be indicated by returning one of
        /// the error codes.  Extensions may return specific error codes such as
        /// <see cref="AuthenticationStatus.BadPassword" /> and <see cref="AuthenticationStatus.BadAccount" />
        /// or the generic error code <see cref="AuthenticationStatus.AccessDenied" />.
        /// </para>
        /// <para>
        /// The <see cref="AuthenticationResult.MaxCacheTime" /> returns as the maximum time the
        /// results of the authentication operation should be cached.
        /// </para>
        /// </remarks>
        /// <exception cref="AuthenticationException">Thrown for authentication related exception.</exception>
        public AuthenticationResult Authenticate(string realm, string account, string password)
        {
            OdbcConnection dbCon;
            OdbcCommand    cmd;
            OdbcDataReader reader = null;
            MacroProcessor processor;
            string         _conString;
            string         query;
            int            authCode;

            using (TimedLock.Lock(this))
            {
                if (!IsOpen)
                {
                    throw new AuthenticationException("Authentication extension is closed.");
                }

                cAuthentications++;
                _conString = conString;

                // Substitute the credentials into the query template.

                processor = new MacroProcessor();
                processor.Add("realm", SqlHelper.Literal(realm));
                processor.Add("account", SqlHelper.Literal(account));
                processor.Add("password", SqlHelper.Literal(password));
                processor.Add("md5-password", SqlHelper.Literal(MD5Hasher.Compute(password)));
                processor.Add("sha1-password", SqlHelper.Literal(SHA1Hasher.Compute(password)));
                processor.Add("sha256-password", SqlHelper.Literal(SHA256Hasher.Compute(password)));
                processor.Add("sha512-password", SqlHelper.Literal(SHA512Hasher.Compute(password)));
                query = processor.Expand(queryTemplate);
            }

            // Perform the query.

            dbCon = new OdbcConnection(_conString);
            dbCon.Open();

            try
            {
                cmd             = dbCon.CreateCommand();
                cmd.CommandText = query;
                cmd.CommandType = CommandType.Text;

                perf.Queries.Increment();
                reader = cmd.ExecuteReader();
                if (!reader.Read())
                {
                    authCode = (int)AuthenticationStatus.AccessDenied; // Empty result set
                }
                else
                {
                    object o    = reader[0];
                    Type   type = o.GetType();

                    if (type == typeof(byte))
                    {
                        authCode = (int)(byte)o;
                    }
                    else if (type == typeof(int))
                    {
                        authCode = (int)o;
                    }
                    else if (type == typeof(long))
                    {
                        authCode = (int)(long)o;
                    }
                    else
                    {
                        throw new AuthenticationException("ODBC authenticate query returned a [{0}] instead of the expected [integer].", type.Name);
                    }

                    if (authCode < 0 || authCode > 5)
                    {
                        throw new AuthenticationException("ODBC authenticate query returned the invalid return code [{0}]. Valid codes range from 0..5", authCode);
                    }
                }
            }
            catch (Exception e)
            {
                perf.Exceptions.Increment();
                throw new AuthenticationException(e);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }

                dbCon.Close();
            }

            return(new AuthenticationResult((AuthenticationStatus)authCode, maxCacheTime));
        }
Ejemplo n.º 22
0
        public void Initialize()
        {
            Helper.InitializeApp(Assembly.GetExecutingAssembly());

            this.ADSettings   = new ADTestSettings();
            this.DB           = SqlTestDatabase.Create();
            this.AuthFilePath = Path.GetTempFileName();

            //-------------------------------------------------------------
            // Initialize file authentication

            Helper.WriteToFile(this.AuthFilePath, @"

file.com;file1;file-password1
file.com;file2;file-password2
");
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.File, "file.com", "file1", "file-password1"));
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.File, "file.com", "file2", "file-password2"));

            //-------------------------------------------------------------
            // Initialize RADIUS authentication

            RadiusServerSettings radiusSettings = new RadiusServerSettings();

            radiusSettings.NetworkBinding = NetworkBinding.Parse("ANY:52111");
            radiusSettings.Devices.Add(new RadiusNasInfo(IPAddress.Loopback, this.RadiusSecret));
            radiusSettings.Devices.Add(new RadiusNasInfo(NetHelper.GetActiveAdapter(), this.RadiusSecret));

            this.RadiusServer = new RadiusServer();
            this.RadiusServer.Start(radiusSettings);
            this.RadiusServer.LoadAccountsFromString(@"

radius.com;radius1;radius-password1
radius.com;radius2;radius-password2
");
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Radius, "radius.com", "radius1", "radius-password1"));
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Radius, "radius.com", "radius2", "radius-password2"));

            //-------------------------------------------------------------
            // Initialize config authentication

            Config.SetConfig(@"

Accounts[0] = config.com;config1;config-password1
Accounts[1] = config.com;config2;config-password2
");
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Config, "config.com", "config1", "config-password1"));
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Config, "config.com", "config2", "config-password2"));

#if TEST_AD
            //-------------------------------------------------------------
            // Initialize active directory authentication

#if !TEST_AD_LDAP
            if (ADSettings.NasSecret != string.Empty)   // Disable the test if the NAS secret is blank
#endif
            this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Ldap, ADSettings.Domain, ADSettings.Account, ADSettings.Password));
#endif

            //-------------------------------------------------------------
            // Initalize ODBC authentication

            SqlConnection   sqlCon = null;
            SqlScriptRunner scriptRunner;
            MacroProcessor  processor;
            string          initScript =
                @"
create table Accounts (

Realm           varchar(64),
Account         varchar(64),
Password        varchar(64),
MD5             varbinary(128),
SHA1            varbinary(128),
SHA256          varbinary(128),
SHA512          varbinary(128)
)
go

insert into Accounts(Realm,Account,Password,MD5,SHA1,SHA256,SHA512)
values ('odbc.com','odbc1','odbc-password1',$(md5-1),$(sha1-1),$(sha256-1),$(sha512-1))

insert into Accounts(Realm,Account,Password,MD5,SHA1,SHA256,SHA512)
values ('odbc.com','odbc2','odbc-password2',$(md5-2),$(sha1-2),$(sha256-2),$(sha512-2))

go
";
            try
            {
                processor = new MacroProcessor();
                processor.Add("md5-1", SqlHelper.Literal(MD5Hasher.Compute("odbc-password1")));
                processor.Add("sha1-1", SqlHelper.Literal(SHA1Hasher.Compute("odbc-password1")));
                processor.Add("sha256-1", SqlHelper.Literal(SHA256Hasher.Compute("odbc-password1")));
                processor.Add("sha512-1", SqlHelper.Literal(SHA512Hasher.Compute("odbc-password1")));

                processor.Add("md5-2", SqlHelper.Literal(MD5Hasher.Compute("odbc-password2")));
                processor.Add("sha1-2", SqlHelper.Literal(SHA1Hasher.Compute("odbc-password2")));
                processor.Add("sha256-2", SqlHelper.Literal(SHA256Hasher.Compute("odbc-password2")));
                processor.Add("sha512-2", SqlHelper.Literal(SHA512Hasher.Compute("odbc-password2")));

                initScript = processor.Expand(initScript);

                sqlCon       = DB.OpenConnection();
                scriptRunner = new SqlScriptRunner(initScript);
                scriptRunner.Run(sqlCon);

                this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Odbc, "odbc.com", "odbc1", "odbc-password1"));
                this.Accounts.Add(new AuthTestAccount(AuthTestExtensionType.Odbc, "odbc.com", "odbc2", "odbc-password2"));
            }
            finally
            {
                if (sqlCon != null)
                {
                    sqlCon.Close();
                }
            }
        }
Ejemplo n.º 23
0
        private void ProcessRequest(Options commandLineOptions)
        {
            StreamHasher fileHashMaker;

            switch (commandLineOptions.HashAgorithm.ToUpper())
            {
            case "MD160":
                fileHashMaker = new MD160Hasher();
                break;

            case "SHA1":
                fileHashMaker = new SHA1Hasher();
                break;

            case "SHA256":
                fileHashMaker = new SHA256Hasher();
                break;

            case "SHA384":
                fileHashMaker = new SHA384Hasher();
                break;

            case "SHA512":
                fileHashMaker = new SHA512Hasher();
                break;

            case "MD5":
            default:
                fileHashMaker = new MD5Hasher();
                break;
            }

            fileHashMaker.HashBlockProcessed += fileHashMaker_HashBlockProcessed;

            List <String[]> inputFiles = new List <String[]>();

            if (commandLineOptions.Concatenate)
            {
                // Files will be treated as a single stream -
                // copy all filenames into a string array,
                // then add the array to the List
                String[] files = new String[commandLineOptions.Items.Count];
                for (int loop = 0; loop < commandLineOptions.Items.Count; loop++)
                {
                    files[loop] = commandLineOptions.Items[loop];
                }
                inputFiles.Add(files);
            }
            else
            {
                // Each file treated as a separate entity -
                // copy each filename into a separate string array,
                // then add each array to the List
                foreach (String fileToProcess in commandLineOptions.Items)
                {
                    String[] file = new String[] { fileToProcess };
                    inputFiles.Add(file);
                }
            }
            foreach (String[] fileEntry in inputFiles)
            {
                byte[] fileHash = fileHashMaker.ComputeFileHash(fileEntry, (int)commandLineOptions.BlockSize);
                Console.WriteLine(commandLineOptions.HashAgorithm.ToUpper() + ": " + BitConverter.ToString(fileHash));

                if (!string.IsNullOrWhiteSpace(commandLineOptions.AppendToHashFile))
                {
                    var settings = HashFile.OpenFile(commandLineOptions.AppendToHashFile);
                    settings.Add(fileEntry[0], BitConverter.ToString(fileHash).Replace("-", string.Empty), commandLineOptions.HashAgorithm.ToUpper());
                    settings.Save();
                }
            }
        }