dotnet加密算法,Server公网访问设置

DotNet中几种常用的加密算法,dotnet加密算法

     
在.NET项目中,我们较多的使用到加密这个操作。因为在现代的项目中,对信息安全的要求越来越高,那么多信息的加密就变得至关重要。现在提供几种常用的加密/解密算法。

  1.用于文本和Base64编码文本的互相转换 和
Byte[]和Base64编码文本的互相转换:

    (1).将普通文本转换成Base64编码的文本

       /// <summary>
        /// 将普通文本转换成Base64编码的文本
        /// </summary>
        /// <param name="value">普通文本</param>
        /// <returns></returns>
        public static string StringToBase64String(string value)
        {
            if (string.IsNullOrEmpty(value))
            {
                throw new ArgumentNullException(value);
            }
            try
            {
                var binBuffer = (new UnicodeEncoding()).GetBytes(value);
                var base64ArraySize = (int)Math.Ceiling(binBuffer.Length / 3d) * 4;
                var charBuffer = new char[base64ArraySize];
                Convert.ToBase64CharArray(binBuffer, 0, binBuffer.Length, charBuffer, 0);
                var s = new string(charBuffer);
                return s;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

   (2).将Base64编码的文本转换成普通文本

        /// <summary>
        /// 将Base64编码的文本转换成普通文本
        /// </summary>
        /// <param name="base64">Base64编码的文本</param>
        /// <returns></returns>
        public static string Base64StringToString(string base64)
        {
            if (string.IsNullOrEmpty(base64))
            {
                throw new ArgumentNullException(base64);
            }
            try
            {
                var charBuffer = base64.ToCharArray();
                var bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
                return (new UnicodeEncoding()).GetString(bytes);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

  (3).将Byte[]转换成Base64编码文本

        /// <summary>
        /// 将Byte[]转换成Base64编码文本
        /// </summary>
        /// <param name="binBuffer">Byte[]</param>
        /// <returns></returns>
        public string ToBase64(byte[] binBuffer)
        {
            if (binBuffer == null)
            {
                throw new ArgumentNullException("binBuffer");
            }
            try
            {
                var base64ArraySize = (int)Math.Ceiling(binBuffer.Length / 3d) * 4;
                var charBuffer = new char[base64ArraySize];
                Convert.ToBase64CharArray(binBuffer, 0, binBuffer.Length, charBuffer, 0);
                var s = new string(charBuffer);
                return s;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

 (4).将Base64编码文本转换成Byte[]

       /// <summary>
        /// 将Base64编码文本转换成Byte[]
        /// </summary>
        /// <param name="base64">Base64编码文本</param>
        /// <returns></returns>
        public byte[] Base64ToBytes(string base64)
        {
            if (string.IsNullOrEmpty(base64))
            {
                throw new ArgumentNullException(base64);
            }
            try
            {
                var charBuffer = base64.ToCharArray();
                var bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length);
                return bytes;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

2. DES加密/解密类。

  (1).加密

  private static readonly string KEY = "pengze0902";

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="Text"></param>
        /// <returns></returns>
        public static string Encrypt(string Text)
        {
            return Encrypt(Text, KEY);
        }
        /// <summary> 
        /// 加密数据 
        /// </summary> 
        /// <param name="Text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Encrypt(string Text, string sKey)
        {
            var des = new DESCryptoServiceProvider();
            var inputByteArray = Encoding.Default.GetBytes(Text);
            var bKey = Encoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8));
            des.Key = bKey;
            des.IV = bKey;
            var ms = new System.IO.MemoryStream();
            var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            var ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

  (2).解密

   private static readonly string KEY = "pengze0902";
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string Decrypt(string text)
        {
            return Decrypt(text, KEY);
        }

        /// <summary> 
        /// 解密数据 
        /// </summary> 
        /// <param name="text"></param> 
        /// <param name="sKey"></param> 
        /// <returns></returns> 
        public static string Decrypt(string text, string sKey)
        {
            var des = new DESCryptoServiceProvider();
            var len = text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x;
            for (x = 0; x < len; x++)
            {
                var i = Convert.ToInt32(text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            var bKey = Encoding.ASCII.GetBytes(Md5Hash(sKey).Substring(0, 8));
            des.Key = bKey;
            des.IV = bKey;
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Encoding.Default.GetString(ms.ToArray());
        }

 (3).取得MD5加密串

        //// <summary>
        /// 取得MD5加密串
        /// </summary>
        /// <param name="input">源明文字符串</param>
        /// <returns>密文字符串</returns>
        public static string Md5Hash(string input)
        {
            var md5 = new MD5CryptoServiceProvider();
            var bs = Encoding.UTF8.GetBytes(input);
            bs = md5.ComputeHash(bs);
            var s = new StringBuilder();
            foreach (var b in bs)
            {
                s.Append(b.ToString("x2").ToUpper());
            }
            var password = s.ToString();
            return password;
        }

3.MD5加密

   (1). 32位大写

        /// <summary>
        /// 32位大写
        /// </summary>
        /// <returns></returns>
        public static string Upper32(string s)
        {
            var hashPasswordForStoringInConfigFile = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5");
            if (hashPasswordForStoringInConfigFile != null)
                s = hashPasswordForStoringInConfigFile.ToString();
            return s.ToUpper();
        }

  (2). 32位小写

        /// <summary>
        /// 32位小写
        /// </summary>
        /// <returns></returns>
        public static string Lower32(string s)
        {
            var hashPasswordForStoringInConfigFile = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5");
            if (hashPasswordForStoringInConfigFile != null)
                s = hashPasswordForStoringInConfigFile.ToString();
            return s.ToLower();
        }

  (3).16位大写

        /// <summary>
        /// 16位大写
        /// </summary>
        /// <returns></returns>
        public static string Upper16(string s)
        {
            var hashPasswordForStoringInConfigFile = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5");
            if (hashPasswordForStoringInConfigFile != null)
                s = hashPasswordForStoringInConfigFile.ToString();
            return s.ToUpper().Substring(8, 16);
        }

 (4).16位小写

        /// <summary>
        /// 16位小写
        /// </summary>
        /// <returns></returns>
        public static string Lower16(string s)
        {
            var hashPasswordForStoringInConfigFile = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(s, "md5");
            if (hashPasswordForStoringInConfigFile != null)
                s = hashPasswordForStoringInConfigFile.ToString();
            return s.ToLower().Substring(8, 16);
        }

4.Sha1签名算法

        /// <summary>
        /// 签名算法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetSha1(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                throw new ArgumentNullException(str);
            }
            try
            {
                //建立SHA1对象
                SHA1 sha = new SHA1CryptoServiceProvider();
                //将mystr转换成byte[] 
                var enc = new ASCIIEncoding();
                var dataToHash = enc.GetBytes(str);
                //Hash运算
                var dataHashed = sha.ComputeHash(dataToHash);
                //将运算结果转换成string
                var hash = BitConverter.ToString(dataHashed).Replace("-", "");
                return hash;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

5.Sha256加密算法

       /// <summary>
        /// 将字符串转换为sha256散列
        /// </summary>
        /// <param name="data">字符串进行转换</param>
        /// <returns>sha256散列或null</returns>
        public static string ToSha256(this string data)
        {
            try
            {
                if (string.IsNullOrEmpty(data))
                    return null;

                var hashValue = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(data));
                var hex = hashValue.Aggregate("", (current, x) => current + String.Format("{0:x2}", x));

                if (string.IsNullOrEmpty(hex))
                    throw new Exception("Erro creating SHA256 hash");

                return hex;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e);
            }
        }

   以上是一些较为常用的算法代码。

在.NET项目中,我们较多的使用到加密这个操作。因为在现代的项目中,对信息安全的要求越来…

Glassfish Server在国内应用的不多,遇到问题在网上找到中文的帖子比较困难,用英文搜索会很较多的答案。我自己的一个开发项目使用了glassfishV3
来部署EJB应用,客户端使用javaSwing调用远程接口服务实现。过程中遇到较多的问题,最后也终于碰碰撞撞完成了项目。

XAF点滴:很具体很用实用—处理三个小问题,xaf点滴

以下内容全部为web版本的老模板风格下完成。

一、在编辑状态的详细视图下打印报表。

有些时候,需要在编辑状态下直接打印报表内容,官方默认是不允许这样做的。用Reflector查看源码,可以看到:

Declaring Type: DevExpress.ExpressApp.ReportsV2.PrintSelectionBaseController 
Assembly: DevExpress.ExpressApp.ReportsV2.v16.1, Version=16.1.5.0
protected virtual void UpdateActionState()
{
    if (base.View != null)
    {
        this.ShowInReportAction.Enabled["DisableActionWhenThereAreChanges"] = true;
        if (this.ShowInReportActionEnableMode == ActionEnabledMode.ModifiedChanged)
        {
            this.ShowInReportAction.Enabled["DisableActionWhenThereAreChanges"] = !base.View.ObjectSpace.IsModified;
        }
        else if ((this.ShowInReportActionEnableMode == ActionEnabledMode.ViewMode) && (base.View is DetailView))
        {
            this.ShowInReportAction.Enabled["DisableActionWhenThereAreChanges"] = ((DetailView) base.View).ViewEditMode == ViewEditMode.View;
        }
    }
}

在这个方法中禁止了显示按钮的逻辑。

ShowInReportActionEnableMode 是在构造函数中做了初始化,如下:

public PrintSelectionBaseController()
{
    base.TypeOfView = typeof(ObjectView);
    this.showInReportAction = new SingleChoiceAction(this, "ShowInReportV2", PredefinedCategory.Reports);
    this.showInReportAction.Caption = "Show in Report";
    this.showInReportAction.ToolTip = "Show selected records in a report";
    this.showInReportAction.Execute += new SingleChoiceActionExecuteEventHandler(this.showInReportAction_Execute);
    this.showInReportAction.ItemType = SingleChoiceActionItemType.ItemIsOperation;
    this.showInReportAction.SelectionDependencyType = SelectionDependencyType.RequireMultipleObjects;
    this.showInReportAction.ImageName = "Action_Report_Object_Inplace_Preview";
    this.ShowInReportActionEnableMode = ShowInReportActionEnableModeDefault;  //<<<<---------------看这里
}

 

 

ShowInReportActionEnableModeDefault 是一个静态变量。

public static ActionEnabledMode ShowInReportActionEnableModeDefault;

也就是说,可以全局设定行为。 再来详细的看一下如何显示的逻辑:

protected virtual void UpdateActionState()
{
    if (base.View != null)
    {
        this.ShowInReportAction.Enabled["DisableActionWhenThereAreChanges"] = true; //默认可以用,但这个名称取的和值是不是很难理解?
        if (this.ShowInReportActionEnableMode == ActionEnabledMode.ModifiedChanged) //标注1
        {
            this.ShowInReportAction.Enabled["DisableActionWhenThereAreChanges"] = !base.View.ObjectSpace.IsModified;
        }
        else if ((this.ShowInReportActionEnableMode == ActionEnabledMode.ViewMode) && (base.View is DetailView)) //这个模式下,只有当前详细视图是查看时才能用。
        {
            this.ShowInReportAction.Enabled["DisableActionWhenThereAreChanges"] = ((DetailView) base.View).ViewEditMode == ViewEditMode.View;
        }
    }
}

 

标注1:如果 模式设置为ModifiedChanged则, 有编辑的对象,就不可以用这个按钮。看到这里你一定认为,官方不是支持了编辑状态的打印报表了吗?然而,这个ObjectSpace.IsModified的值在没,有编辑时也经常会变为true,即使是刚刚按过保存按钮。
我认为用这个值做判断很难控制,不如直接改掉吧。
多说一句,官方的考虑是正确的,如:你刚刚修改了内容,没按保存去打印单据,那么结果可能数据库里的内容和打印的结果是不一致的。
所以我们进行一下改造。

    public class PrintReportController : PrintSelectionBaseController
    {
        protected override void UpdateActionState()
        {
            if (View is DetailView)
            {
                //详细视图下,都是可用的
            }
            else
            {
                base.UpdateActionState(); //如果不是detailview时,还按原来的逻辑走
            }

        }

        protected override void ShowInReport(SingleChoiceActionExecuteEventArgs e, string reportContainerHandle)
        {
            var dv = View as DetailView;
            if (dv != null && dv.ViewEditMode == DevExpress.ExpressApp.Editors.ViewEditMode.Edit)
            {
                this.ObjectSpace.CommitChanges();
            }//执行按钮前,先保存一下数据
            base.ShowInReport(e, reportContainerHandle);
        }
    }

就是这么简单。

二、让查看状态的视图支持“返回”到上一个视图的功能。

这个相当简单,当做初学者的学习示例吧,但用户还是很需要这个功能的。

    public partial class CloseDetailViewController : ViewController<DetailView>
    {
        public CloseDetailViewController()
        {
            InitializeComponent();
            this.CloseViewModeDetail.Execute += CloseViewModeDetail_Execute;
            // Target required Views (via the TargetXXX properties) and create their Actions.
        }

        private void CloseViewModeDetail_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            this.View.Close();
        }

        protected override void OnActivated()
        {
            base.OnActivated();
            this.CloseViewModeDetail.Active["InViewMode"] = View.ViewEditMode == ViewEditMode.View; //这个按钮只有在查看状态中显示
            // Perform various tasks depending on the target View.
        }
        protected override void OnViewControlsCreated()
        {
            base.OnViewControlsCreated();
            // Access and customize the target View control.
        }
        protected override void OnDeactivated()
        {
            // Unsubscribe from previously subscribed events and release other references and resources.
            base.OnDeactivated();
        }
    }

//按钮是这样设置的:
            this.CloseViewModeDetail.Caption = "返回";
            this.CloseViewModeDetail.Category = "Export";
            this.CloseViewModeDetail.Id = "CloseViewModeDetail";

三、在编辑状态的主表点击明细表时直接转到编辑状态

这个功能也很实用,因为点击编辑按钮有点累,按钮图标太小,如果点击任意行位置,弹出的是查看状态的记录内容。所以现在改变为,如果是编辑状态的主表,弹出的也是编辑状态的界面。

 public partial class DetailItemViewController : ViewController<DetailView>
    {
        public DetailItemViewController()
        {
            InitializeComponent();
        }
        protected override void OnActivated()
        {
            base.OnActivated();
            var os = this.ObjectSpace as XPNestedObjectSpace; //如果有上级详细视图并且是在编辑状态的视图,那把本级别的编辑视图也设置成编辑状态。
            if (os!=null)
            {
                var dv = os.ParentObjectSpace.Owner as DetailView;
                if (dv!=null)
                {
                    this.View.ViewEditMode = dv.ViewEditMode;
                }
            }
            // Perform various tasks depending on the target View.
        }
        protected override void OnViewControlsCreated()
        {
            base.OnViewControlsCreated();
            // Access and customize the target View control.
        }
        protected override void OnDeactivated()
        {
            // Unsubscribe from previously subscribed events and release other references and resources.
            base.OnDeactivated();
        }
    }

现在XAF中支持的列表自由编辑还有有很多不支持的功能,这样折中处理一下也不错。

 

 

以下内容全部为web版本的老模板风格下完成。
一、在编辑状态的详细视图下打印报表…

如果您需要您的glassfish服务器跑在公网上,那必须做相关设置,默认设置是不对公网访问的。

设置步骤:

1. 管理后台,在configuration
->ORB->IIOPListeners

发表评论