Example #1
0
        public static string MakeTURNAuthToken(string companyNameOrTenant)
        {
            string key     = GetTURNServersKey();
            string servers = GetTURNServersList();

            if (string.IsNullOrEmpty(key) || string.IsNullOrEmpty(servers))
            {
                return(string.Empty);
            }

            DateTime expirationTime = DateTime.UtcNow + TimeSpan.FromMinutes(long.Parse(GetAuthTokenLifetimeMinutes()));
            string   userCombo      = $"{(long)((expirationTime - DateTime.UnixEpoch).TotalSeconds)}:{companyNameOrTenant}";

            using (System.Security.Cryptography.HMACMD5 hashAlg = new System.Security.Cryptography.HMACMD5())
            {
                hashAlg.Key = Encoding.UTF8.GetBytes(key);
                byte[] bytes    = hashAlg.ComputeHash(Encoding.UTF8.GetBytes(userCombo));
                string password = Convert.ToBase64String(bytes);

                string token =
                    $"{{\"username\":\"{userCombo}\", \"password\":\"{password}\", " +
                    $"\"uris\":[{servers}]}}";

                return(token);
            }
        }
        /// <summary>
        ///User Verify PasswordHash
        /// </summary>
        /// <param name="password"></param>
        /// <returns>bool</returns>
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            bool IsVerifyed = default(bool);

            try
            {
                //TODO:@AbdelRahman
                //Avoid Multiple Return
                using (var hmac = new System.Security.Cryptography.HMACMD5(passwordSalt))
                {
                    var CoumputedHash = hmac.ComputeHash(System.Text.Encoding.ASCII.GetBytes(password));
                    IsVerifyed = true;
                    for (int i = 0; i < CoumputedHash.Length; i++)
                    {
                        if (CoumputedHash[i] != passwordHash[i])
                        {
                            IsVerifyed = false;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                //Logger.Instance.LogException(exception, LogLevel.Medium);
                IsVerifyed = false;
            }
            return(IsVerifyed);
        }
        /// <summary>
        ///User Verify PasswordHash
        /// </summary>
        /// <param name="password"></param>
        /// <returns>bool</returns>
        private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
        {
            bool IsVerifyed = default(bool);

            try
            {
                using (var hmac = new System.Security.Cryptography.HMACMD5(passwordSalt))
                {
                    var CoumputedHash = hmac.ComputeHash(System.Text.Encoding.ASCII.GetBytes(password));
                    IsVerifyed = true;
                    for (int i = 0; i < CoumputedHash.Length; i++)
                    {
                        if (CoumputedHash[i] != passwordHash[i])
                        {
                            IsVerifyed = false;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                IsVerifyed = false;
            }
            return(IsVerifyed);
        }
Example #4
0
 /// <summary>
 /// Computes a new hash of <paramref name="data"/> usign the <paramref name="key"/> specified.
 /// </summary>
 /// <param name="key">A byte array containing the key (secret) to use to generate a hash.</param>
 /// <param name="data">A byte arrasy containing the data to be hashed.</param>
 /// <returns>A new byte array containing the hash result.</returns>
 public byte[] ComputeHash(byte[] key, byte[] data)
 {
     using (var hasher = new System.Security.Cryptography.HMACMD5(key))
     {
         return(hasher.ComputeHash(data));
     }
 }
Example #5
0
        private byte[] ComputeHMACMD5HashByPassword(byte[] buf)
        {
            var hmacMd5 = new System.Security.Cryptography.HMACMD5(Encoding.UTF8.GetBytes(Password));

            byte[] encCha = hmacMd5.ComputeHash(buf);
            hmacMd5.Clear();
            return(encCha);
        }
Example #6
0
 private void CreatePaswordHash(string password, out byte[] passHash, out byte[] passSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACMD5())
     {
         passSalt = hmac.Key;
         passHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
     }
 }
        private static string CalculateHash(string orderRequest)
        {
            var hashEngine = new System.Security.Cryptography.HMACMD5(new byte[] { 14, 4, 78 });

            byte[] hash       = hashEngine.ComputeHash(Encoding.UTF8.GetBytes(orderRequest));
            string hashString = string.Empty;

            foreach (byte x in hash)
            {
                hashString += string.Format("{0:x2}", x);
            }
            return(hashString);
        }
        /// <summary>
        /// 独有干扰MD5加密
        /// </summary>
        /// <param name="data">待加密的数据</param>
        /// <param name="key">加密的密钥</param>
        /// <returns></returns>
        public static string HMACMD5(this string data, byte[] key)
        {
            if (string.IsNullOrEmpty(data))
            {
                return(string.Empty);
            }

            System.Security.Cryptography.HMACMD5 md5Provider = new System.Security.Cryptography.HMACMD5(key);

            byte[] hashBuff = md5Provider.ComputeHash(data.ToUpper().ToBytes());

            return(hashBuff.ToHexString());
        }
Example #9
0
        private bool VerifyHash(string password, string storedHash)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty, null or whitespace only string.", "password");
            }

            byte[] key = HashConverter.PlainTextToBytes(Secrets.MD5Key);
            using (var hmac = new System.Security.Cryptography.HMACMD5(key))
            {
                var computedHash = HashConverter.ToString(hmac.ComputeHash(HashConverter.PlainTextToBytes(password)));
                return(storedHash == computedHash);
            }
        }
Example #10
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="fileLocation"></param>
 /// <returns></returns>
 public static string CalculateMd5CheckSum(string fileLocation)
 {
     System.Security.Cryptography.HashAlgorithm hmacMd5 = new System.Security.Cryptography.HMACMD5();
     byte[] hashByte;
     using (Stream fileStream = new FileStream(fileLocation, FileMode.Open))
     using (Stream bufferedStream = new BufferedStream(fileStream, 1200000))
         hashByte = hmacMd5.ComputeHash(bufferedStream);
     StringBuilder sbResult = new StringBuilder();
     for (int i = 0; i < hashByte.Length; i++)
     {
         sbResult.Append(hashByte[i].ToString("x2"));
     }
     return sbResult.ToString().ToUpper();
 }
Example #11
0
 public static bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACMD5(passwordSalt))
     {
         var computedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));
         for (int i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
     }
     return(true);
 }
Example #12
0
        //CRAM-MD5で返す文字列を計算する
        private static string CreateCramMd5ResponseString(string challenge, string username, string password)
        {
            //デコードする
            byte[] decCha = Convert.FromBase64String(challenge);
            //passwordをキーとしてHMAC-MD5で暗号化する
            System.Security.Cryptography.HMACMD5 hmacMd5 = new System.Security.Cryptography.HMACMD5(Encoding.UTF8.GetBytes(password));
            byte[] encCha = hmacMd5.ComputeHash(decCha);
            hmacMd5.Clear();
            //16進数の文字列にする
            string hexCha = BitConverter.ToString(encCha).Replace("-", "").ToLower();

            //usernameを付ける
            hexCha = username + " " + hexCha;
            //Base64で文字列にする
            return(Convert.ToBase64String(Encoding.UTF8.GetBytes(hexCha)));
        }
Example #13
0
        /// <summary>
        /// Returns HMAC SHA256 hash value of <paramref name="name"/> with "u_" prefix (to comply with SignalR naming requirements)
        /// </summary>
        public static string GetNameHash(string input, string hashKey)
        {
            StringBuilder hash = new StringBuilder("u_");

            using (System.Security.Cryptography.HMACMD5 hashAlg = new System.Security.Cryptography.HMACMD5())
            {
                hashAlg.Key = Encoding.UTF8.GetBytes(hashKey.Substring(Math.Min(0, hashKey.Length - 16)));
                byte[] bytes = hashAlg.ComputeHash(Encoding.UTF8.GetBytes(input));

                for (int i = 0; i < bytes.Length; i++)
                {
                    hash.Append(bytes[i].ToString("x2"));
                }
                return(hash.ToString());
            }
        }
Example #14
0
        public void Execute()
        {
            ProgressChanged(0, 1);

            System.Security.Cryptography.HMAC hmacAlgorithm;

            switch ((HMACSettings.HashFunction)settings.SelectedHashFunction)
            {
            case HMACSettings.HashFunction.MD5:
                hmacAlgorithm = new System.Security.Cryptography.HMACMD5();
                break;

            case HMACSettings.HashFunction.RIPEMD160:
                hmacAlgorithm = new System.Security.Cryptography.HMACRIPEMD160();
                break;

            case HMACSettings.HashFunction.SHA1:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA1();
                break;

            case HMACSettings.HashFunction.SHA256:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA256();
                break;

            case HMACSettings.HashFunction.SHA384:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA384();
                break;

            case HMACSettings.HashFunction.SHA512:
                hmacAlgorithm = new System.Security.Cryptography.HMACSHA512();
                break;

            default:
                GuiLogMessage("No hash algorithm for HMAC selected, using MD5.", NotificationLevel.Warning);
                hmacAlgorithm = new System.Security.Cryptography.HMACMD5();
                break;
            }

            hmacAlgorithm.Key = key;

            OutputData = (inputData != null) ? hmacAlgorithm.ComputeHash(inputData.CreateReader()) : hmacAlgorithm.ComputeHash(new byte[] {});

            GuiLogMessage(String.Format("HMAC computed. (using hash algorithm {0}: {1})", settings.SelectedHashFunction, hmacAlgorithm.GetType().Name), NotificationLevel.Info);

            ProgressChanged(1, 1);
        }
Example #15
0
/// <summary>
/// 不使用BouncyCastle的写法
/// </summary>
/// <param name="data"></param>
/// <param name="key"></param>
/// <returns></returns>
        public static byte[] Compute2(string data, string key)
        {
            if (string.IsNullOrEmpty(data))
            {
                throw new ArgumentNullException(nameof(data));
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException(nameof(key));
            }

            using (var hmacMd5 = new System.Security.Cryptography.HMACMD5(Encoding.UTF8.GetBytes(key)))
            {
                return(hmacMd5.ComputeHash(Encoding.UTF8.GetBytes(data)));
            }
        }
Example #16
0
        private byte[] CreateHash(string password)
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Value cannot be empty, null or whitespace only string.", "password");
            }

            string key = Secrets.MD5Key;

            byte[] keyByte = HashConverter.PlainTextToBytes(key);

            byte[] hash;
            using (var hmac = new System.Security.Cryptography.HMACMD5(keyByte))
            {
                hash = hmac.ComputeHash(HashConverter.PlainTextToBytes(password));
            }
            return(hash);
        }
Example #17
0
        private static string Encrypt(string secretSalt, string clearSecret)
        {
            try
            {
                string returnValue = string.Empty;

                secretSalt  = GetHexString(secretSalt);
                clearSecret = GetHexString(clearSecret);

                System.Security.Cryptography.HMACMD5 hash = new System.Security.Cryptography.HMACMD5();

                byte[] returnBytes = new byte[secretSalt.Length / 2];
                for (int i = 0; i < returnBytes.Length; i++)
                {
                    returnBytes[i] = Convert.ToByte(secretSalt.Substring(i * 2, 2), 16);
                }
                hash.Key = returnBytes;

                string encodedSecret = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(clearSecret)));

#pragma warning disable CA1305 // Specify IFormatProvider
                string newSecret = string.Format("{0}{1}", secretSalt, encodedSecret);
#pragma warning restore CA1305 // Specify IFormatProvider
                byte[]        bytes = Encoding.UTF8.GetBytes(newSecret);
                StringBuilder sb    = new StringBuilder();
                foreach (byte bt in bytes)
                {
#pragma warning disable CA1305 // Specify IFormatProvider
                    sb.AppendFormat("{0:x2}", bt);
#pragma warning restore CA1305 // Specify IFormatProvider
                }
                returnValue = sb.ToString();
                return(returnValue);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    throw e.InnerException;
                }

                throw;
            }
        }
Example #18
0
 /// <summary>
 /// Computes the HMAC MD5 hash value for the specified byte array.
 /// </summary>
 /// <param name="bytes">The input to compute the hash code for.</param>
 /// <returns>The computed hash code as GUID.</returns>
 /// <remarks>
 /// One instance of the MD5 Crypto Service Provider
 /// can't operate properly with multiple simultaneous threads.
 /// Use lock to solve this problem.
 /// </remarks>
 public Guid ComputeHash(byte[] bytes, byte[] hashKeyBytes = null)
 {
     byte[] hash;
     // If HMAC hash key is not supplied then...
     if (hashKeyBytes == null)
     {
         lock (MacProviderLock)
             // Use default from config file.
             hash = MacProvider.ComputeHash(bytes);
     }
     else
     {
         // Create MD5HMAC hash provider.
         var macProvider = new System.Security.Cryptography.HMACMD5();
         macProvider.Key = hashKeyBytes;
         hash            = macProvider.ComputeHash(bytes);
     }
     return(new Guid(hash));
 }
 /// <summary>
 ///User Create PasswordHash
 /// </summary>
 /// <param name="password"></param>
 /// <returns>bool</returns>
 private UserPasswordDTO CreatePasswordHash(string password)
 {
     #region Declare a return type with initial value.
     UserPasswordDTO userPasswordDTO = null;
     #endregion
     try
     {
         using (var hmac = new System.Security.Cryptography.HMACMD5())
         {
             userPasswordDTO = new UserPasswordDTO()
             {
                 PasswordSalt = hmac.Key,
                 PasswordHash = hmac.ComputeHash(System.Text.Encoding.ASCII.GetBytes(password))
             };
         }
     }
     catch (Exception exception)
     {
         // Logger.Instance.LogException(exception, LogLevel.Medium);
     }
     return(userPasswordDTO);
 }
        private static string GetMd5Hash(string inp)
        {
            byte[] keyInBytes = System.Text.UTF8Encoding.UTF8.GetBytes("secret_key");
            byte[] payloadInBytes = System.Text.UTF8Encoding.UTF8.GetBytes(inp);

            var md5 = new System.Security.Cryptography.HMACMD5(keyInBytes);
            byte[] hash = md5.ComputeHash(payloadInBytes);

            var result = BitConverter.ToString(hash).Replace("-", string.Empty);
            return result;
        }
Example #21
0
 /// <summary>
 /// Hash of string as byte array.
 /// </summary>
 /// <param name="inString">Input string</param>
 /// <param name="inKey">Input salt</param>
 /// <returns>Output bytes</returns>
 public byte[] hashString(string inString, byte[] inKey)
 {
     byte[] toHash = System.Text.Encoding.ASCII.GetBytes(inString);
     hmac.Key = inKey;
     return(hmac.ComputeHash(toHash));
 }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (!IsPostBack)
            {
                StringBuilder sb = new StringBuilder();
                if (Request.QueryString["tbl"] != null && Request.QueryString["key"] != null)
                {
                    /* prevent manually constructed request that would lead to information leakage via hashing of
                     * query string and session secret, only apply for database related retrieval which are all generated by the system
                     */
                    ValidatedQS();
                    string dbConnectionString;
                    if (Request.QueryString["sys"] != null)
                    {
                        sid = byte.Parse(Request.QueryString["sys"].ToString());
                    }
                    else
                    {
                        throw new Exception("Please make sure '&sys=' is present and try again.");
                    }
                    if (new AdminSystem().IsMDesignDb(Request.QueryString["tbl"].ToString()))
                    {
                        dbConnectionString = base.SysConnectStr(sid);
                    }
                    else
                    {
                        dbConnectionString = base.AppConnectStr(sid);
                    }

                    if (Request.QueryString["multi"] != null)
                    {
                        SaveMultiDocUpload(dbConnectionString, base.AppPwd(sid), sid, true);
                    }
                    else
                    {
                        SaveUpload(dbConnectionString, sid);
                    }
                    return;

                    /* To be Deleted:
                     * DataTable dt = null;
                     * try
                     * {
                     *  if (Request.QueryString["knm"] != null && Request.QueryString["col"] != null)     // ImageButton
                     *  {
                     *      dt = (new AdminSystem()).GetDbImg(Request.QueryString["key"].ToString(), Request.QueryString["tbl"].ToString(), Request.QueryString["knm"].ToString(), Request.QueryString["col"].ToString(), dbConnectionString, base.AppPwd(sid));
                     *      Response.Buffer = true; Response.ClearHeaders(); Response.ClearContent();
                     *      Response.ContentType = "image/jpeg";
                     *      Response.AppendHeader("Content-Disposition", "Attachment; Filename=");
                     *      Response.BinaryWrite((byte[])dt.Rows[0][0]);
                     *      HttpContext.Current.ApplicationInstance.CompleteRequest();
                     *  }
                     *  else // Document.
                     *  {
                     *      dt = (new AdminSystem()).GetDbDoc(Request.QueryString["key"].ToString(), Request.QueryString["tbl"].ToString(), dbConnectionString, base.AppPwd(sid));
                     *      Response.Buffer = true; Response.ClearHeaders(); Response.ClearContent();
                     *      Response.ContentType = dt.Rows[0]["MimeType"].ToString();
                     *      Response.AppendHeader("Content-Disposition", "Attachment; Filename=" + dt.Rows[0]["DocName"].ToString());
                     *      Response.BinaryWrite((byte[])dt.Rows[0]["DocImage"]);
                     *      Response.End();
                     *  }
                     * }
                     * catch (Exception err) { ApplicationAssert.CheckCondition(false, "DnLoadModule", "", err.Message); }
                     */
                }
                else if (Request.QueryString["file"] != null)
                {
                    /* file based download needs to be catered manually by webrule for protected contents
                     * via access control in the IIS directory level(no access) and gated by dnloadmodule via server side transfer
                     */
                    try
                    {
                        bool pub = true;
                        if (LImpr != null)
                        {
                            string UsrGroup = (char)191 + base.LImpr.UsrGroups + (char)191;
                            if (UsrGroup.IndexOf((char)191 + "25" + (char)191) < 0 && UsrGroup.IndexOf((char)191 + "5" + (char)191) < 0)
                            {
                                pub = true;
                            }
                            else
                            {
                                pub = false;
                            }
                        }
                        string fileName         = Request.QueryString["file"].ToString();
                        string key              = Request.QueryString["key"].ToString();
                        string DownloadLinkCode = Session.SessionID;
                        byte[] Download_code    = System.Text.Encoding.ASCII.GetBytes(DownloadLinkCode);
                        System.Security.Cryptography.HMACMD5 bkup_hmac = new System.Security.Cryptography.HMACMD5(Download_code);
                        byte[] Download_hash       = bkup_hmac.ComputeHash(System.Text.Encoding.ASCII.GetBytes(fileName));
                        string Download_hashString = BitConverter.ToString(Download_hash);
                        bool   allowDownload       = Download_hashString == key;
                        fileName = fileName.ToLower().Replace("/guarded/", "/source/");
                        string             url          = fileName;
                        string             fullfileName = Server.MapPath(fileName); // we enforce everything file for download is under ../files
                        System.IO.FileInfo file         = new System.IO.FileInfo(fullfileName);
                        string             oname        = file.Name;
                        if (!allowDownload && pub && !(file.Name.StartsWith("Pub") || file.Name.StartsWith("pub")))
                        {
                            if (file.Name.EndsWith(".wmv"))
                            {
                                file = new FileInfo(file.DirectoryName + "/PubMsg.wmv");
                                url  = fileName.Replace(oname, "PubMsg.wmv");
                            }
                            else
                            {
                                if (LUser == null || LUser.LoginName == "Anonymous")
                                {
                                    string loginUrl = System.Web.Security.FormsAuthentication.LoginUrl;
                                    if (string.IsNullOrEmpty(loginUrl))
                                    {
                                        loginUrl = "MyAccount.aspx";
                                    }
                                    this.Redirect(loginUrl + (loginUrl.IndexOf('?') > 0 ? "&" : "?") + "wrn=1&ReturnUrl=" + Server.UrlEncode(Request.Url.PathAndQuery));
                                }
                                else
                                {
                                    throw new Exception("Access Denied");
                                }
                            }
                        }
                        Response.Buffer      = true; Response.ClearHeaders(); Response.ClearContent();
                        Response.ContentType = GetMimeTypeFromExtension(file.Extension);
                        Response.AddHeader("Content-Disposition", "Attachment; Filename=" + file.Name);
                        Response.AddHeader("Content-Length", file.Length.ToString());
                        Server.Transfer(url);
                    }
                    catch (Exception err) { ApplicationAssert.CheckCondition(false, "DnLoadModule", "", err.Message); }
                }
            }
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            if (!IsPostBack)
            {
                StringBuilder sb = new StringBuilder();
                if (Request.QueryString["tbl"] != null && Request.QueryString["key"] != null)
                {
                    /* prevent manually constructed request that would lead to information leakage via hashing of
                     * query string and session secret, only apply for database related retrieval which are all generated by the system
                     */
                    ValidatedQS();
                    string dbConnectionString;
                    if (Request.QueryString["sys"] != null)
                    {
                        sid = byte.Parse(Request.QueryString["sys"].ToString());
                    }
                    else
                    {
                        throw new Exception("Please make sure '&sys=' is present and try again.");
                    }
                    if (new AdminSystem().IsMDesignDb(Request.QueryString["tbl"].ToString()))
                    {
                        dbConnectionString = base.SysConnectStr(sid);
                    }
                    else
                    {
                        dbConnectionString = base.AppConnectStr(sid);
                    }
                    DataTable dt = null;
                    try
                    {
                        if (Request.QueryString["knm"] != null && Request.QueryString["col"] != null)     // ImageButton
                        {
                            dt = (new AdminSystem()).GetDbImg(Request.QueryString["key"].ToString(), Request.QueryString["tbl"].ToString(), Request.QueryString["knm"].ToString(), Request.QueryString["col"].ToString(), dbConnectionString, base.AppPwd(sid));
                            Response.Buffer = true; Response.ClearHeaders(); Response.ClearContent();
                            string fileContent   = RO.Common3.Utils.DecodeFileStream((byte[])dt.Rows[0][0]);
                            string fileName      = "";
                            string mimeType      = "application/octet";
                            string contentBase64 = "";
                            System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
                            try
                            {
                                RO.Common3.FileUploadObj fileInfo = jss.Deserialize <RO.Common3.FileUploadObj>(fileContent);
                                mimeType      = fileInfo.mimeType;
                                fileName      = fileInfo.fileName;
                                contentBase64 = fileInfo.base64;
                            }
                            catch
                            {
                                try
                                {
                                    List <RO.Common3._ReactFileUploadObj> fileList = jss.Deserialize <List <RO.Common3._ReactFileUploadObj> >(fileContent);
                                    List <FileUploadObj> x = new List <FileUploadObj>();
                                    foreach (var fileInfo in fileList)
                                    {
                                        mimeType      = fileInfo.mimeType;
                                        fileName      = fileInfo.fileName;
                                        contentBase64 = fileInfo.base64;
                                        break;
                                    }
                                }
                                catch
                                {
                                    contentBase64 = fileContent;
                                    fileName      = "";
                                    mimeType      = "image/jpeg";
                                }
                            }

                            string contentDisposition = "attachment";
                            if (!string.IsNullOrEmpty(Request.QueryString["inline"]) && Request.QueryString["inline"] == "Y")
                            {
                                contentDisposition = "inline";
                            }

                            byte[] content = new byte[0];
                            try
                            {
                                content = (byte[])Convert.FromBase64String(contentBase64);
                                Response.ContentType = mimeType;
                                Response.AppendHeader("Content-Disposition", contentDisposition + "; Filename=" + fileName);
                            }
                            catch (Exception ex)
                            {
                                try
                                {
                                    content = (byte[])dt.Rows[0][0];
                                    Response.ContentType = "image/jpeg";
                                    Response.AppendHeader("Content-Disposition", contentDisposition + "; Filename=");
                                }
                                catch { }
                            }
                            Response.Flush();
                            Response.BinaryWrite(content);
                            Response.End();
                        }
                        else // Document.
                        {
                            dt = (new AdminSystem()).GetDbDoc(Request.QueryString["key"].ToString(), Request.QueryString["tbl"].ToString(), dbConnectionString, base.AppPwd(sid));
                            Response.Buffer      = true; Response.ClearHeaders(); Response.ClearContent();
                            Response.ContentType = dt.Rows[0]["MimeType"].ToString();
                            string contentDisposition = "attachment";
                            if (!string.IsNullOrEmpty(Request.QueryString["inline"]) && Request.QueryString["inline"] == "Y")
                            {
                                contentDisposition = "inline";
                            }
                            Response.AppendHeader("Content-Disposition", contentDisposition + "; Filename=" + dt.Rows[0]["DocName"].ToString());
                            //Response.AppendHeader("Content-Disposition", "Attachment; Filename=" + dt.Rows[0]["DocName"].ToString());
                            Response.BinaryWrite((byte[])dt.Rows[0]["DocImage"]);
                            Response.End();
                        }
                    }
                    catch (Exception err) {
                        if (!(err is ThreadAbortException))
                        {
                            ApplicationAssert.CheckCondition(false, "DnLoadModule", "", err.Message);
                        }
                    }
                }
                else if (Request.QueryString["file"] != null)
                {
                    /* file based download needs to be catered manually by webrule for protected contents
                     * via access control in the IIS directory level(no access) and gated by dnloadmodule via server side transfer
                     */
                    try
                    {
                        bool pub = true;
                        if (LImpr != null)
                        {
                            string UsrGroup = (char)191 + base.LImpr.UsrGroups + (char)191;
                            if (UsrGroup.IndexOf((char)191 + "25" + (char)191) < 0 && UsrGroup.IndexOf((char)191 + "5" + (char)191) < 0)
                            {
                                pub = true;
                            }
                            else
                            {
                                pub = false;
                            }
                        }
                        string fileName         = Request.QueryString["file"].ToString();
                        string key              = Request.QueryString["key"].ToString();
                        string DownloadLinkCode = Session.SessionID;
                        byte[] Download_code    = System.Text.Encoding.ASCII.GetBytes(DownloadLinkCode);
                        System.Security.Cryptography.HMACMD5 bkup_hmac = new System.Security.Cryptography.HMACMD5(Download_code);
                        byte[] Download_hash       = bkup_hmac.ComputeHash(System.Text.Encoding.ASCII.GetBytes(fileName));
                        string Download_hashString = BitConverter.ToString(Download_hash);
                        bool   allowDownload       = Download_hashString == key;
                        fileName = fileName.ToLower().Replace("/guarded/", "/source/");
                        string             url          = fileName;
                        string             fullfileName = Server.MapPath(fileName); // we enforce everything file for download is under ../files
                        System.IO.FileInfo file         = new System.IO.FileInfo(fullfileName);
                        string             oname        = file.Name;
                        if (!allowDownload && pub && !(file.Name.StartsWith("Pub") || file.Name.StartsWith("pub")))
                        {
                            if (file.Name.EndsWith(".wmv"))
                            {
                                file = new FileInfo(file.DirectoryName + "/PubMsg.wmv");
                                url  = fileName.Replace(oname, "PubMsg.wmv");
                            }
                            else
                            {
                                if (LUser == null || LUser.LoginName == "Anonymous")
                                {
                                    string loginUrl = System.Web.Security.FormsAuthentication.LoginUrl;
                                    if (string.IsNullOrEmpty(loginUrl))
                                    {
                                        loginUrl = "MyAccount.aspx";
                                    }
                                    Response.Redirect(loginUrl + (loginUrl.IndexOf('?') > 0 ? "&" : "?") + "wrn=1&ReturnUrl=" + Server.UrlEncode(Request.Url.PathAndQuery));
                                }
                                else
                                {
                                    throw new Exception("Access Denied");
                                }
                            }
                        }
                        Response.Buffer      = true; Response.ClearHeaders(); Response.ClearContent();
                        Response.ContentType = GetMimeTypeFromExtension(file.Extension);
                        Response.AddHeader("Content-Disposition", "Attachment; Filename=" + file.Name);
                        Response.AddHeader("Content-Length", file.Length.ToString());
                        Server.Transfer(url);
                    }
                    catch (Exception err) { ApplicationAssert.CheckCondition(false, "DnLoadModule", "", err.Message); }
                }
            }
        }
Example #24
0
 private static byte[] MD5Encrypt(Stream stream, string key, Encoding encode)
 {
     System.Security.Cryptography.HMACMD5 hmac = new System.Security.Cryptography.HMACMD5(encode.GetBytes(key));
     return(hmac.ComputeHash(stream));
 }
Example #25
0
        /// <summary>
        /// Register an account. Returns true if succeed, otherwise return false and write logs.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="rawPassword"></param>
        /// <param name="hashType"></param>
        /// <returns></returns>
        public static bool RegisterUser(string username, string rawPassword, int hashType)
        {
            try
            {
                string hashSaltBase64     = null;
                string passwordHashBase64 = null;
                byte[] saltBytes;
                System.Security.Cryptography.HMAC hmac;
                switch (hashType)
                {
                case (int)Enums.HMAC.MD5:
                    hashSaltBase64 = null;
                    using (System.Security.Cryptography.MD5 hasher = System.Security.Cryptography.MD5.Create())
                    {
                        passwordHashBase64 = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    }
                    break;

                case (int)Enums.HMAC.RIPEMD160:
                    hashSaltBase64 = null;
                    using (System.Security.Cryptography.RIPEMD160 hasher = System.Security.Cryptography.RIPEMD160.Create())
                    {
                        passwordHashBase64 = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    }
                    break;

                case (int)Enums.HMAC.SHA1:
                    hashSaltBase64 = null;
                    using (System.Security.Cryptography.SHA1 hasher = System.Security.Cryptography.SHA1.Create())
                    {
                        passwordHashBase64 = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    }
                    break;

                case (int)Enums.HMAC.SHA256:
                    hashSaltBase64 = null;
                    using (System.Security.Cryptography.SHA256 hasher = System.Security.Cryptography.SHA256.Create())
                    {
                        passwordHashBase64 = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    }
                    break;

                case (int)Enums.HMAC.SHA384:
                    hashSaltBase64 = null;
                    using (System.Security.Cryptography.SHA384 hasher = System.Security.Cryptography.SHA384.Create())
                    {
                        passwordHashBase64 = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    }
                    break;

                case (int)Enums.HMAC.SHA512:
                    hashSaltBase64 = null;
                    using (System.Security.Cryptography.SHA512 hasher = System.Security.Cryptography.SHA512.Create())
                    {
                        passwordHashBase64 = Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    }
                    break;

                case (int)Enums.HMAC.HMACMD5:
                    saltBytes = new byte[Settings.InitSetting.Instance.MaxNumberOfBytesInSalt];
                    new Random().NextBytes(saltBytes);
                    hashSaltBase64     = Convert.ToBase64String(saltBytes);
                    hmac               = new System.Security.Cryptography.HMACMD5(saltBytes);
                    passwordHashBase64 = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    break;

                case (int)Enums.HMAC.HMACRIPEMD160:
                    saltBytes = new byte[Settings.InitSetting.Instance.MaxNumberOfBytesInSalt];
                    new Random().NextBytes(saltBytes);
                    hashSaltBase64     = Convert.ToBase64String(saltBytes);
                    hmac               = new System.Security.Cryptography.HMACRIPEMD160(saltBytes);
                    passwordHashBase64 = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    break;

                case (int)Enums.HMAC.HMACSHA1:
                    saltBytes = new byte[Settings.InitSetting.Instance.MaxNumberOfBytesInSalt];
                    new Random().NextBytes(saltBytes);
                    hashSaltBase64     = Convert.ToBase64String(saltBytes);
                    hmac               = new System.Security.Cryptography.HMACSHA1(saltBytes);
                    passwordHashBase64 = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    break;

                case (int)Enums.HMAC.HMACSHA256:
                    saltBytes = new byte[Settings.InitSetting.Instance.MaxNumberOfBytesInSalt];
                    new Random().NextBytes(saltBytes);
                    hashSaltBase64     = Convert.ToBase64String(saltBytes);
                    hmac               = new System.Security.Cryptography.HMACSHA256(saltBytes);
                    passwordHashBase64 = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    break;

                case (int)Enums.HMAC.HMACSHA384:
                    saltBytes = new byte[Settings.InitSetting.Instance.MaxNumberOfBytesInSalt];
                    new Random().NextBytes(saltBytes);
                    hashSaltBase64     = Convert.ToBase64String(saltBytes);
                    hmac               = new System.Security.Cryptography.HMACSHA384(saltBytes);
                    passwordHashBase64 = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    break;

                case (int)Enums.HMAC.HMACSHA512:
                    saltBytes = new byte[Settings.InitSetting.Instance.MaxNumberOfBytesInSalt];
                    new Random().NextBytes(saltBytes);
                    hashSaltBase64     = Convert.ToBase64String(saltBytes);
                    hmac               = new System.Security.Cryptography.HMACSHA512(saltBytes);
                    passwordHashBase64 = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(rawPassword)));
                    break;

                default:
                    throw new NotImplementedException("Unspecified hash type.");
                }
                var acc = new Account()
                {
                    Uname                 = username,
                    HashSaltBase64        = hashSaltBase64,
                    HashTypeId            = hashType,
                    PasswordHashBase64    = passwordHashBase64,
                    IsTwoFactor           = false,
                    TwoFactorSecretBase32 = null
                };
                using (AuthorizeEntities ctx = new AuthorizeEntities())
                {
                    ctx.Accounts.Add(acc);
                    ctx.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "Cannot register user", ex);
                return(false);
            }
            return(true);
        }
Example #26
0
 public static byte[] HMAC_MD5(byte [] key, byte [] data)
 {
     System.Security.Cryptography.HMACMD5 hmacmd5 = new System.Security.Cryptography.HMACMD5(key);
     return(hmacmd5.ComputeHash(data));
 }
Example #27
0
        public static bool Login(string username, string password)
        {
            bool isOk = false;

            byte[] saltBytes;
            System.Security.Cryptography.HMAC hmac;
            try
            {
                using (AuthorizeEntities ctx = new AuthorizeEntities())
                {
                    var acc = ctx.Accounts.Where(x => x.Uname == username).FirstOrDefault();
                    if (acc != null)
                    {
                        switch (acc.HashTypeId)
                        {
                        case (int)Enums.HMAC.MD5:
                            using (System.Security.Cryptography.MD5 hasher = System.Security.Cryptography.MD5.Create())
                            {
                                isOk = acc.PasswordHashBase64.Equals(Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(password))));
                            }
                            break;

                        case (int)Enums.HMAC.RIPEMD160:
                            using (System.Security.Cryptography.RIPEMD160 hasher = System.Security.Cryptography.RIPEMD160.Create())
                            {
                                isOk = acc.PasswordHashBase64.Equals(Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(password))));
                            }
                            break;

                        case (int)Enums.HMAC.SHA1:
                            using (System.Security.Cryptography.SHA1 hasher = System.Security.Cryptography.SHA1.Create())
                            {
                                isOk = acc.PasswordHashBase64.Equals(Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(password))));
                            }
                            break;

                        case (int)Enums.HMAC.SHA256:
                            using (System.Security.Cryptography.SHA256 hasher = System.Security.Cryptography.SHA256.Create())
                            {
                                isOk = acc.PasswordHashBase64.Equals(Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(password))));
                            }
                            break;

                        case (int)Enums.HMAC.SHA384:
                            using (System.Security.Cryptography.SHA384 hasher = System.Security.Cryptography.SHA384.Create())
                            {
                                isOk = acc.PasswordHashBase64.Equals(Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(password))));
                            }
                            break;

                        case (int)Enums.HMAC.SHA512:
                            using (System.Security.Cryptography.SHA512 hasher = System.Security.Cryptography.SHA512.Create())
                            {
                                isOk = acc.PasswordHashBase64.Equals(Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(password))));
                            }
                            break;

                        case (int)Enums.HMAC.HMACMD5:
                            saltBytes = Convert.FromBase64String(acc.HashSaltBase64);
                            hmac      = new System.Security.Cryptography.HMACMD5(saltBytes);
                            isOk      = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(password))).Equals(acc.PasswordHashBase64);
                            break;

                        case (int)Enums.HMAC.HMACRIPEMD160:
                            saltBytes = Convert.FromBase64String(acc.HashSaltBase64);
                            hmac      = new System.Security.Cryptography.HMACRIPEMD160(saltBytes);
                            isOk      = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(password))).Equals(acc.PasswordHashBase64);
                            break;

                        case (int)Enums.HMAC.HMACSHA1:
                            saltBytes = Convert.FromBase64String(acc.HashSaltBase64);
                            hmac      = new System.Security.Cryptography.HMACSHA1(saltBytes);
                            isOk      = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(password))).Equals(acc.PasswordHashBase64);
                            break;

                        case (int)Enums.HMAC.HMACSHA256:
                            saltBytes = Convert.FromBase64String(acc.HashSaltBase64);
                            hmac      = new System.Security.Cryptography.HMACSHA256(saltBytes);
                            isOk      = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(password))).Equals(acc.PasswordHashBase64);
                            break;

                        case (int)Enums.HMAC.HMACSHA384:
                            saltBytes = Convert.FromBase64String(acc.HashSaltBase64);
                            hmac      = new System.Security.Cryptography.HMACSHA384(saltBytes);
                            isOk      = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(password))).Equals(acc.PasswordHashBase64);
                            break;

                        case (int)Enums.HMAC.HMACSHA512:
                            saltBytes = Convert.FromBase64String(acc.HashSaltBase64);
                            hmac      = new System.Security.Cryptography.HMACSHA512(saltBytes);
                            isOk      = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(password))).Equals(acc.PasswordHashBase64);
                            break;

                        default:
                            throw new NotImplementedException("Unspecified hash type.");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log4netLogger.Error(MethodBase.GetCurrentMethod().DeclaringType, "Cannot login", ex);
                isOk = false;
            }
            return(isOk);
        }