16進制可逆加密算法


16進制可逆操作類:

 public static class Hex16
    {
        /// <summary>
        /// 作用:將字符串內容轉化為16進制數據編碼,其逆過程是Decode
        /// 參數說明:
        /// strEncode 需要轉化的原始字符串
        /// 轉換的過程是直接把字符轉換成Unicode字符,比如數字"3"-->0033,漢字"我"-->U+6211
        /// 函數decode的過程是encode的逆過程.
        /// </summary>
        public static string Encode(string strEncode)
        {
            string strReturn = "";//  存儲轉換后的編碼
            try
            {
                foreach (short shortx in strEncode.ToCharArray())
                {
                    strReturn += shortx.ToString("X4");
                }
            }
            catch { }
            return strReturn;
        }

        /// <summary>
        /// 作用:將16進制數據編碼轉化為字符串,是Encode的逆過程
        /// </summary>
        public static string Decode(string strDecode)
        {
            string sResult = "";
            try
            {
                for (int i = 0; i < strDecode.Length / 4; i++)
                {
                    sResult += (char)short.Parse(strDecode.Substring(i * 4, 4),
                        global::System.Globalization.NumberStyles.HexNumber);
                }
            }
            catch { }
            return sResult;
        }

        /// <summary>
        /// 將數字轉換成16進制字符串,后兩位加入隨機字符,其可逆方法為DecodeForNum
        /// </summary>
        public static string EncodeForNum(int id)
        {
            //用戶加上起始位置后的
            int startUserIndex = id;
            //轉換成16進制
            string hexStr = Convert.ToString(startUserIndex, 16);

            //后面兩位加入隨機數
            string randomchars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

            string tmpstr ="";

            //整除的后得到的數可能大於被除數
            tmpstr += randomchars[(id / randomchars.Length) > randomchars.Length ? randomchars.Length - 1 : (id / randomchars.Length)];

            //余數不可能大於被除數
            tmpstr += randomchars[(id % randomchars.Length) > randomchars.Length ? randomchars.Length - 1 : (id % randomchars.Length)];
            
            //返回拼接后的字符,轉成大寫
            string retStr = (hexStr + tmpstr).ToUpper();

            return retStr;
        }

        /// <summary>
        /// 解密16進制字符串,此方法只適合后面兩位有隨機字符的
        /// </summary>
        public static int DecodeForNum(string strDecode)
        {
            if (strDecode.Length>2)
            {
                strDecode = strDecode.Substring(0, strDecode.Length - 2);
                return Convert.ToInt32(strDecode, 16);
            }
            return 0;
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM