總瀏覽量

2011年10月4日星期二

【筆記】C# DES 加/解密

DES(DES,Data Encryption Standard)是一種使用密鑰加密的塊密碼,1976年被美國聯邦政府的國家標準局確定為聯邦資料處理標準(FIPS)。因為它使用的56 bits 密鑰過短,現在已經不被視為一種安全的加密演算法。在2001年,DES 已經被 AES 所取代已經不再作為國家標準科技協會的一個標準。

加密:


//-- 檔案加密(DES) --//
private byte[] EncryptDES(byte[] bData)
{
    DES des = null;
    ICryptoTransform ict = null;
    MemoryStream ms = null;
    CryptoStream cs = null;
    BinaryWriter sw = null;
    byte[] byteResult = null;
    try
    {
        des = DES.Create();
        des.Key = ASCIIEncoding.ASCII.GetBytes(Global.DESKey.Substring(0, 8));
        des.IV = Global.DESIV;

        ict = des.CreateEncryptor(des.Key, des.IV);
        ms = new MemoryStream();
        cs = new CryptoStream(ms, ict, CryptoStreamMode.Write);
        sw = new BinaryWriter(cs);
        foreach (byte b in bData)
        {
            sw.Write(b);
        }
        sw.Close();
        cs.Close();
        byteResult = ms.ToArray();
        ms.Close();

        return byteResult;
    }
    catch (Exception e)
    {
        throw e;
    }
    finally
    {
        if (sw != null) sw.Close();
        if (cs != null) cs.Close();
        if (ms != null) ms.Close();
    }
}


解密:
//-- 檔案加解密(DES) --//
private byte[] DecryptDES(byte[] bData)
{
    DES des = null;
    ICryptoTransform ict = null;
    MemoryStream ms = null;
    CryptoStream cs = null;
    BinaryReader sr = null;
    byte[] bResult = new byte[Global.iFileLength];

    try
    {
        des = DES.Create();
        des.Key = ASCIIEncoding.ASCII.GetBytes(Global.DESKey.Substring(0, 8));
        des.IV = Global.DESIV;
        ict = des.CreateDecryptor(des.Key, des.IV);
        ms = new MemoryStream(bData);
        cs = new CryptoStream(ms, ict, CryptoStreamMode.Read);
        sr = new BinaryReader(cs);

        int i=0;
        byte getByte;
        while ((getByte = sr.ReadByte())!= 0x00) 
        {
            bResult[i++] = getByte;
        }
        sr.Close();
        cs.Close();
        ms.Close();
        return bResult;
    }
    catch (Exception e)
    {
        throw e;
    }
    finally
    {
        if (sr != null) sr.Close();
        if (cs != null) cs.Close();
        if (ms != null) ms.Close();
    }
}

加/解密都是以 “Byte”的方式進行,把要加/解密的資料以 byte[] 的型態丟進來就可以了。

0 意見:

張貼意見

文章列表

追蹤者