顯示具有 C# 標籤的文章。 顯示所有文章
顯示具有 C# 標籤的文章。 顯示所有文章

2013年12月17日 星期二

C# String To Unicode 編碼 (UTF-16BE)


public String text2uni2(String arg_Source)
{
       int enCode;
       char[] charArray = arg_Source.ToCharArray();
       StringBuilder uniText = new StringBuilder(arg_Source.Length * 2);
       for (int i = 0; i < charArray.Length; i++)
       {
              char a = charArray[i];
              uniText.Append("\\u");
              enCode = (a >> 8);
              string hexCode = enCode.ToString("X");
              if (hexCode.ToString().Length == 1)
              {
                     uniText.Append("0");
              }
              uniText.Append(hexCode);
              enCode = (a & 0xFF);
              hexCode = enCode.ToString("X");
              if (hexCode.ToString().Length == 1)
              {
                     uniText.Append("0");
              }
              uniText.Append(hexCode);
       }
       return (uniText.ToString());
}

例如
ドラマも大人気「のだめカンタービレ」の世界
轉換後
\u30c9\u30e9\u30de\u3082\u5927\u4eba\u6c17\u300c\u306e\u3060\u3081
\u30ab\u30f3\u30bf\u30fc\u30d3\u30ec\u300d\u306e\u4e16\u754c

La new打進冠軍決賽
轉換後
\u004c\u0061\u0020\u006e\u0065\u0077\u6253\u9032\u51a0\u8ecd\u6c7a\u8cfd

C# 透過 WebRequest 傳送資料、檔案

近來專案上有個檔案、照片上傳的需求,
但因為運行的架構為前後台分別獨立於不同的主機上運行,
當使用者從後台上傳檔案或照片時,棘手的問題就產生了,
於後台主機上傳的檔案、照片要怎樣同步傳送至前台主機?
當下我嚐試想要透過網芳共享資料夾的方式,
將使用者傳至後台主機的檔案或照片複製到前台的主機上,
弄了二天還是解決不了權限的問題,
解決不了只能用最原始的方法
用HTTP傳送及接收
下面的方法只能指定單一的本機檔案路徑
寫完後才想到有可能會是檔案是分佈在不同的資料中
當要傳送一次就得再呼叫一次有點麻煩
當需求產生時再補入

使用方法
UploadFilesToRemoteUrl(
"http://www.yousite.com/r.aspx" /*接收檔案的網址*/,
"d:\tmp" /*本機檔案路徑*/,
new[] {"a.png", "b.jpg"} /*傳送的檔案名稱,可傳送多個檔案*/,
new NameValueCollection {{"id","123"}} /*其他要傳送的參數*/)
程式如下 [C# 3.5]


發送端
/// 
/// 將本機檔案上傳到遠端主機上
/// 
///  接收檔案的網址
///  本機檔案路徑
///  傳送的檔案名稱
///  其他要傳送的參數
public void UploadFilesToRemoteUrl(string url, string filePath, IEnumerable fileNames, NameValueCollection param)
{
    var boundary = "----------------------------" + Guid.NewGuid();
    var webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
    webRequest.Method = "POST";
    webRequest.KeepAlive = true;
    webRequest.Credentials = CredentialCache.DefaultCredentials;
    var memStream = new MemoryStream();
    var boundarybytes = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}\r\n", boundary));

 var paramrHeader =
        string.Format(
        "\r\n--{0}\r\nContent-Disposition: form-data; name=\"{{0}}\";\r\n\r\n{{1}}",
        boundary);
    foreach (var paramItemBytes in
        from string key in param.Keys
        select string.Format(paramrHeader, key, param[key])
        into paramItem
            select Encoding.UTF8.GetBytes(paramItem))
    {
        memStream.Write(paramItemBytes, 0, paramItemBytes.Length);
    }
    memStream.Write(boundarybytes, 0, boundarybytes.Length);

    const 
string fileHeader =
        "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
    foreach (var t in fileNames)
    {
        var header = string.Format(fileHeader, t, t);
        var headerbytes = Encoding.UTF8.GetBytes(header);
        memStream.Write(headerbytes, 0, headerbytes.Length);
        var fileStream = new FileStream(
            string.Format("{0}/{1}", filePath, t),
            FileMode.Open,
            FileAccess.Read);
        var buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
        {
            memStream.Write(buffer, 0, bytesRead);
        }
        memStream.Write(boundarybytes, 0, boundarybytes.Length);
        fileStream.Close();
    }
    webRequest.ContentLength = memStream.Length;
    memStream.Position = 0;
    var memBuffer = new byte[memStream.Length];
    memStream.Read(memBuffer, 0, memBuffer.Length);
    memStream.Close();
    webRequest.GetRequestStream().Write(memBuffer, 0, memBuffer.Length);
} 

接收端

protected void Page_Load(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(Request["id"])) return;
    var strDirectory =
        string.Format(
            "{0}tmp/{1}",
            Request.PhysicalApplicationPath,
            Request["id"]);
    //建立主機上的檔案路徑
    Directory.CreateDirectory(strDirectory);
    foreach (var file in Request.Files)
    {
        Request.Files[file.ToString()].SaveAs(
            string.Format(
                "{0}/{1}",
                strDirectory,
                Request.Files[file.ToString()].FileName));
    }
} 

2013年6月10日 星期一

C# Calculating CRC32

最近需要在C#的環境中計算某Key的CRC值,於是翻了一下PHP和Pyton的源碼後合併二者的寫法。

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace jIAnSoft {
    public class Crc32 : HashAlgorithm {
        private long _crc;

        public override sealed void Initialize() {}

        protected override void HashCore(byte[] buffer, int offset, int count) {
            _crc = 0 ^ 0xFFFFFFFF;
            for (var i = offset; i < count; i++) {
                _crc = ((_crc >> 8) & 0x00FFFFFF) ^ Crc32Tab[(_crc ^ buffer[i]) & 0xFF];
            }
            _crc ^= 0xFFFFFFFF;
            _crc |= -(_crc & (1L << 31));
        }

        protected override byte[] HashFinal() {
            return BitConverter.GetBytes(_crc);
        }

        public static long Sum(string asciiString) {
            return ToInt32(new Crc32().ComputeHash(asciiString));
        }

        public static long Sum(Stream inputStream) {
            return ToInt32(new Crc32().ComputeHash(inputStream));
        }

        public static long Sum(byte[] buffer) {
            return ToInt32(new Crc32().ComputeHash(buffer));
        }

        public static long Sum(byte[] buffer, int offset, int count) {
            return ToInt32(new Crc32().ComputeHash(buffer, offset, count));
        }

        protected byte[] ComputeHash(string txt) {
            var rawBytes = Encoding.UTF8.GetBytes(txt);
            return ComputeHash(rawBytes);
        }

        protected new byte[] ComputeHash(Stream inputStream) {
            var buffer = new byte[6];
            int bytesRead;
            while ((bytesRead = inputStream.Read(buffer, 0, 6)) > 0) {
                HashCore(buffer, 0, bytesRead);
            }
            return HashFinal();
        }

        protected new byte[] ComputeHash(byte[] buffer) {
            return ComputeHash(buffer, 0, buffer.Length);
        }

        protected new byte[] ComputeHash(byte[] buffer, int offset, int count) {
            HashCore(buffer, offset, count);
            return HashFinal();
        }
        
        private static long ToInt32(byte[] buffer) {
            return BitConverter.ToInt32(buffer, 0);
        }

        private static readonly UInt32[] Crc32Tab = {
            0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
            0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
            0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
            0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
            0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
            0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
            0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
            0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
            0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
            0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
            0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
            0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
            0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
            0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
            0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
            0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
            0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
            0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
            0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
            0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
            0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
            0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
            0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
            0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
            0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
            0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
            0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
            0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
            0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
            0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
            0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
            0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
            0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
            0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
            0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
            0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
            0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
            0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
            0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
            0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
            0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
            0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
            0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
            0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
            0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
            0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
            0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
            0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
            0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
            0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
            0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
            0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
            0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
            0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
            0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
            0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
            0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
            0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
            0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
            0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
            0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
            0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
            0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
            0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
        };
    }
}

參考源碼 python:http://www6.uniovi.es/python/dev/src/c/html/binascii_8c-source.html
php:https://github.com/php/php-src/blob/642721b38a9c5ebf336c81027c0dafd6f9246bd6/ext/standard/crc32.c

2012年7月11日 星期三

C# 繁簡轉換效能大車拚


就目前已知在.Net平台上繁簡互轉的作法大約有四種
1. Microsoft.VisualBasic.dll 
    .Net平台內建可以直接參考使用,效率三級。                
2. Microsoft Visual Studio International Pack 1.0 SR1
    微軟官方所出的官方套件,需要另外安裝,目前不支援 VS 2008 以上的版本,官方網站下載後無法在VS 2008 以上的版本安裝,需要另外在網路上尋找 ChineseConverter.dll 加入參考,效率二級。               
3. Microsoft.Office.Interop.Word.dll(Office 2010 Ver.14.0.4762.1000)
    系統上若裝了 Office 就有,唯一提供繁簡詞意互轉的套件,但是轉換效能就不那麼漂亮,效率五級。               
4. OS Kernel LCMapString
    什麼都不用裝,直接使用系統內核kernel32.dll 提供的LCMapString 來進行轉換,效率一級。

測試結果數據如下︰ 
VisualBasic Convert︰15.9458 ms
Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter︰3.5011 ms       
Microsoft.Office.Interop.Word︰10082.5081 ms
Kernel32 LCMapString︰1.5212 ms

相關的程式碼︰
///
/// 使用系統 kernel32.dll 進行轉換
///
private const int LocaleSystemDefault = 0x0800;
private const int LcmapSimplifiedChinese = 0x02000000;
private const int LcmapTraditionalChinese = 0x04000000;
 
[DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
private static extern int LCMapString(int locale, int dwMapFlags, string lpSrcStr, int cchSrc,
                                      [Out] string lpDestStr, int cchDest);
 
public static string ToSimplified(string argSource)
{
    var t = new String(' ', argSource.Length);
    LCMapString(LocaleSystemDefault, LcmapSimplifiedChinese, argSource, argSource.Length, t, argSource.Length);
    return t;
}
 
public static string ToTraditional(string argSource)
{
    var t = new String(' ', argSource.Length);
    LCMapString(LocaleSystemDefault, LcmapTraditionalChinese, argSource, argSource.Length, t, argSource.Length);
    return t;
}
 
///
/// 使用 Office Word (Microsoft.Office.Interop.Word) 進行轉換
///
public static string ConvertUsingWord(string argSource, bool argIsCht)
{
    var doc = new Document();
    doc.Content.Text = argSource;
    doc.Content.TCSCConverter(
        argIsCht
            ? WdTCSCConverterDirection.wdTCSCConverterDirectionTCSC
            : WdTCSCConverterDirection.wdTCSCConverterDirectionSCTC, true, true);
    var ret = doc.Content.Text;
    object saveChanges = false;
    object originalFormat = Missing.Value;
    object routeDocument = Missing.Value;
    doc.Close(ref saveChanges, ref originalFormat, ref routeDocument);
    return ret;
}

測式碼︰
public void RunTest()
{   
    var i = 1000;
    var sw = new System.Diagnostics.Stopwatch();
    sw.Reset();
    sw.Start();
    while (--i > 0)
    {
        Strings.StrConv("她來聽我 的演唱會 在十七歲的初戀 第一次約會,繁轉簡", VbStrConv.SimplifiedChinese, 2052);
        Strings.StrConv("她来听我 的演唱会 在十七岁的初恋 第一次约会,簡轉繁", VbStrConv.TraditionalChinese, 2052);
    }
 
    sw.Stop();
    Response.Write(string.Format("VisualBasic Convert︰{0}",  sw.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)));
    i = 1000;
    sw.Reset();
    sw.Start();
    while (--i > 0)
    {
        ChineseConverter.Convert("她來聽我 的演唱會 在十七歲的初戀 第一次約會,繁轉簡", ChineseConversionDirection.TraditionalToSimplified);
        ChineseConverter.Convert("她来听我 的演唱会 在十七岁的初恋 第一次约会,簡轉繁", ChineseConversionDirection.SimplifiedToTraditional);
    }
    sw.Stop();
    Response.Write(
        string.Format("Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter︰{0}", sw.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)));
 
    i = 100;
    sw.Reset();
    sw.Start();
    while (--i > 0)
    { 
        ConvertUsingWord("她來聽我 的演唱會 在十七歲的初戀 第一次約會,繁轉簡", true);
        ConvertUsingWord("她来听我 的演唱会 在十七岁的初恋 第一次约会,簡轉繁", false);
    }
    sw.Stop();
    Response.Write(string.Format("Microsoft.Office.Interop.Word︰{0}", sw.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)));
    i = 1000;
    sw.Reset();
    sw.Start();
    while (--i > 0)
    { 
        ToSimplified("她來聽我 的演唱會 在十七歲的初戀 第一次約會,繁轉簡");
        ToTraditional("她来听我 的演唱会 在十七岁的初恋 第一次约会,簡轉繁");
    }
    sw.Stop();
    Response.Write(string.Format("kernel32 LCMapString︰{0}",sw.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture)));
}

2012年4月9日 星期一

解決SQL SERVER 2008 昇級SQL SERVER 2012 後無法使用 Visual Studio 2010 開啟 SQL SERVER 資料庫專案


近期將SQL SERVER 2008 昇級到SQL SERVER 2012之後,
卻發生無法使用 Visual Studio 2010 開啟 SQL SERVER 資料庫專案的問題。
一開啟SQL SERVER 資料庫專案,Visual Studio 2010 即提示
無法載入檔案或組件 'Microsoft.SqlServer.Management.SqlParser, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' 或其相依性的其中之一。系統找不到指定的檔案。
Could not load file or assembly 'Microsoft.SqlServer.Management.SqlParser, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. the system cannot find the file specified.
經查,應是 Visual Studio 2010 需要 Microsoft.SqlServer.Management.SqlParser V.10 版,但昇級 SQL SERVER 2012 後的更新版本為V.11  , 造成專案找不到該dll 無法開啟,解決方法如下︰

先至安裝SQL SERVER 2008版的主機上取出下面二個檔案(C:\Windows\assembly)。

1.Microsoft.SqlServer.Management.SqlParser.dll
2.Microsoft.SqlServer.Management.SqlParser.Resources.dll
重新註冊一次後,問題即可解決

C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\gacutil /i C:\Microsoft.SqlServer.Management.SqlParser.dll
C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\gacutil /i C:\Microsoft.SqlServer.Management.SqlParser.Resources.dll

PS.每個人的  gacutil  檔案位置會隨著安裝的 Visual Studio 版本、安裝路徑而有不同的結果,請先自行尋找 gacutil  檔案的位置,上列指令採 Visual Studio 2010 ;安裝路徑為預設值。

2009年2月7日 星期六

發送文件類型及編碼 Header 在IE中變檔案下載

今天被這個Header發送搞了一個小時多
從伺服器發給Browser 一個文件類型及編碼的Header
指令為 header('Content-Type: text/html ; charset=utf-8');
Firefox及Chrome都可以正確運行
一遇上IE就變成檔案下載...
最後才發現在 text/html 之後多了一個空格
將空格移除後,就正常了 ^^"
header('Content-Type: text/html; charset=utf-8');

順道補上其他語言的文件類型及編碼Header設定
Java
resource.setContentType ("text/html; charset=utf-8");
JSP
<%@ page contenttype="text/html; charset=utf-8"%>
.Net
Response.ContentType = "text/html; charset=utf-8";
Asp
<%Response.charset="utf-8"%>

2008年10月20日 星期一

檢驗公司統一編號是否正確 C#

程式碼如下︰

C# 3.5
public static bool checkCompanyNo(string arg_CompanyNo)
{
var LOGIC = new[] { 1, 2, 1, 2, 1, 2, 4, 1 };
var intSum = 0;

for (var i = 0; i < LOGIC.Length; i++)
{
var intMultiply = int.Parse(arg_CompanyNo.Substring(i,1)) * LOGIC[i];
var intAddition = ((intMultiply / 10) + (intMultiply % 10));
intSum += (intAddition == 10) ? 1 : intAddition;
}

return (intSum % 10 == 0);
}

完整的程式縮排請至
http://mamba.zapto.org/bbs/showthread.php?t=692

2008年5月6日 星期二

C# 讀取 Excel

最近需要將Excel格式的資料匯進資料中
上網找了一下
順手記錄下來

連結字串中的HDR=YES,代表略過第一欄資料

//引用OleDb命名空間
using System.Data.OleDb;

string path = System.Windows.Forms.Application.StartupPath + @"\a.xls " ;
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + path + ";Extended Properties='Excel 8.0;HDR=YES'";
OleDbConnection objConn = new OleDbConnection(strCon);
string strCom = " SELECT * FROM [Sheet1$] ";
objConn.Open();

OleDbDataAdapter objCmd = new OleDbDataAdapter(strCom, objConn);
DataSet objDS = new DataSet();
objCmd.Fill(objDS);
objConn.Close();

for (int i = 0; i < objDS.Tables[0].Rows.Count;i++ )
{
MessageBox.Show(objDS.Tables[0].Rows[i][1].ToString());
}

完整的程式縮排可至
http://mamba.zapto.org/bbs/showthread.php?p=1577#post1577

2008年2月8日 星期五

AzDG可逆加密演算法 for C#

年節感冒,又逢下雨,閒著就再將AzDG可逆加密演算法轉成C#版
相較於Java版本,C#版本已含有MD5及Base64加解密函式
另外也改成靜態方法,不用建構即可使用
使用方式
AzDGCrypt.Crypt("中文測試", "私匙","字元集");
AzDGCrypt.Crypt("中文測試", "私匙"); //使用預設字元集Big5
AzDGCrypt.Crypt("中文測試"); //使用預設私匙及字元集Big5
//記得加入System.Web參考
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Security;

namespace jIAn.Crypt
{
public class AzDGCrypt
{
static string strCharSet = "big5";
static string strPrivateKey = "abcdefghijk";

public static byte[] PrivateKeyCrypt(byte[] arg_abteSource)
{
byte bteCRCLength = 0;
byte[] abteEncryptKey = Encoding.GetEncoding(strCharSet).GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(strPrivateKey, "MD5").ToLower());
byte[] abteReturn = new byte[arg_abteSource.Length];
for (int i = 0; i < arg_abteSource.Length; ++i)
{
bteCRCLength = (bteCRCLength > 31) ? (byte) 0 : bteCRCLength;
abteReturn[i] = (byte) (arg_abteSource[i] ^ abteEncryptKey[bteCRCLength++]);
}
return abteReturn;
}


public static byte[] DoEncrypt(byte[] arg_strSource)
{
DateTime dttCurrentTime = DateTime.Now;
long lngTimeInMillis = dttCurrentTime.Ticks;
byte bteCRCLength = 0;
byte[] abteCRCKey = Encoding.GetEncoding(strCharSet).GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(lngTimeInMillis.ToString(), "MD5").ToLower());
byte[] abteReturn = new byte[arg_strSource.Length * 2];
for (int i = 0, j = 0; i < arg_strSource.Length; ++i, ++j)
{
bteCRCLength = (bteCRCLength > 31) ? (byte) 0 : bteCRCLength;
abteReturn[j] = abteCRCKey[bteCRCLength];
++j;
abteReturn[j] = (byte)(arg_strSource[i] ^ abteCRCKey[bteCRCLength++]);
}
return PrivateKeyCrypt(abteReturn);
}


public static String Crypt(String arg_strSource)
{
return Convert.ToBase64String(DoEncrypt(Encoding.GetEncoding(strCharSet).GetBytes(arg_strSource)));
}


public static String Crypt(String arg_strSource, String arg_strPrivateKey)
{
strPrivateKey = arg_strPrivateKey;
return Crypt(arg_strSource);
}


public static String Crypt(String arg_strSource, String arg_strPrivateKey, String arg_strCharset)
{
strCharSet = arg_strCharset;
return Crypt(arg_strSource, arg_strPrivateKey);
}

public static byte[] DoDecrypt(byte[] arg_strSource)
{
arg_strSource = PrivateKeyCrypt(arg_strSource);
byte[] abteReturn = new byte[(int) (arg_strSource.Length / 2)];
for (int i = 0, j = 0; i < arg_strSource.Length; ++i, ++j)
{
abteReturn[j] = (byte) (arg_strSource[i] ^ arg_strSource[++i]);
}
return abteReturn;
}


public static String DeCrypt(String arg_strSource)
{
byte[] abteSourceText = Convert.FromBase64String(arg_strSource);
return Encoding.GetEncoding(strCharSet).GetString(DoDecrypt(abteSourceText));
}


public static String DeCrypt(String arg_strSource, String arg_strPrivateKey)
{
strPrivateKey = arg_strPrivateKey;
return DeCrypt(arg_strSource);
}

public static String DeCrypt(String arg_strSource, String arg_strPrivateKey, String arg_strCharset)
{
strCharSet = arg_strCharset;
return DeCrypt(arg_strSource, arg_strPrivateKey);
}
}
}