RC4加密演算法在C#中的實現

l_serein發表於2013-01-23

這次的RC4有個基類CryptoBase,這個基類,是為了為多種加密演算法提供統一介面而設計的,我這裡實現了RC4、DES、RSA三種演算法。和C++中一樣,C#這裡也要有一個十六進位制字串轉換函式來編碼解碼。

經過測試,客戶端C++的RC4能夠很好的和服務端C#中的RC4結合工作,也就是說,一端加密的資料,另一端完全可以解密。很遺憾,實在找不到能和C#中的RSA演算法對應的C++實現的RSA演算法,希望得到高人指點……

程式碼檔案有兩個:

CryptoBase.cs檔案:

 

以下是程式碼片段:

using System;
using System.Collections.Generic;
using System.Text;

namespace NewLife.Cryptography
{
    /// <summary>
    /// 加密類基類
    /// </summary>
    public class CryptoBase
    {
        /// <summary>
        /// 編碼轉換器,用於位元組碼和字串之間的轉換,預設為本機編碼
        /// </summary>
        static public Encoding Encode = Encoding.Default;
        public enum EncoderMode { Base64Encoder, HexEncoder };

        /// <summary>
        /// 帶編碼模式的字串加密
        /// </summary>
        /// <param name="data">要加密的資料</param>
        /// <param name="pass">密碼</param>
        /// <param name="em">編碼模式</param>
        /// <returns>加密後經過編碼的字串</returns>
        public String Encrypt(String data, String pass, CryptoBase.EncoderMode em)
        {
            if (data == null || pass == null) return null;
            if (em == EncoderMode.Base64Encoder)
                return Convert.ToBase64String(EncryptEx(Encode.GetBytes(data), pass));
            else
                return ByteToHex(EncryptEx(Encode.GetBytes(data), pass));
        }

        /// <summary>
        /// 帶編碼模式的字串解密
        /// </summary>
        /// <param name="data">要解密的資料</param>
        /// <param name="pass">密碼</param>
        /// <param name="em">編碼模式</param>
        /// <returns>明文</returns>
        public String Decrypt(String data, String pass, CryptoBase.EncoderMode em)
        {
            if (data == null || pass == null) return null;
            if (em == EncoderMode.Base64Encoder)
                return Encode.GetString(DecryptEx(Convert.FromBase64String(data), pass));
            else
                return Encode.GetString(DecryptEx(HexToByte(data), pass));
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data">要加密的資料</param>
        /// <param name="pass">密碼</param>
        /// <returns>加密後經過預設編碼的字串</returns>
        public String Encrypt(String data, String pass)
        {
            return Encrypt(data, pass, EncoderMode.Base64Encoder);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data">要解密的經過編碼的資料</param>
        /// <param name="pass">密碼</param>
        /// <returns>明文</returns>
        public String Decrypt(String data, String pass)
        {
            return Decrypt(data, pass, EncoderMode.Base64Encoder);
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data">要加密的資料</param>
        /// <param name="pass">金鑰</param>
        /// <returns>密文</returns>
        virtual public Byte[] EncryptEx(Byte[] data, String pass) { return null; }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data">要解密的資料</param>
        /// <param name="pass">密碼</param>
        /// <returns>明文</returns>
        virtual public Byte[] DecryptEx(Byte[] data, String pass) { return null; }

        static public Byte[] HexToByte(String szHex)
        {
            // 兩個十六進位制代表一個位元組
            Int32 iLen = szHex.Length;
            if (iLen <= 0 || 0 != iLen % 2)
            {
                return null;
            }
            Int32 dwCount = iLen / 2;
            UInt32 tmp1, tmp2;
            Byte[] pbBuffer = new Byte[dwCount];
            for (Int32 i = 0; i < dwCount; i++)
            {
                tmp1 = (UInt32)szHex[i * 2] - (((UInt32)szHex[i * 2] >= (UInt32)'A') ? (UInt32)'A' - 10 : (UInt32)'0');
                if (tmp1 >= 16) return null;
                tmp2 = (UInt32)szHex[i * 2 + 1] - (((UInt32)szHex[i * 2 + 1] >= (UInt32)'A') ? (UInt32)'A' - 10 : (UInt32)'0');
                if (tmp2 >= 16) return null;
                pbBuffer[i] = (Byte)(tmp1 * 16 + tmp2);
            }
            return pbBuffer;
        }

        static public String ByteToHex(Byte[] vByte)
        {
            if (vByte == null || vByte.Length < 1) return null;
            StringBuilder sb = new StringBuilder(vByte.Length * 2);
            for (int i = 0; i < vByte.Length; i++)
            {
                if ((UInt32)vByte[i] < 0) return null;
                UInt32 k = (UInt32)vByte[i] / 16;
                sb.Append((Char)(k + ((k > 9) ? 'A' - 10 : '0')));
                k = (UInt32)vByte[i] % 16;
                sb.Append((Char)(k + ((k > 9) ? 'A' - 10 : '0')));
            }
            return sb.ToString();
        }
    }

    interface ICrypto
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="data">要加密的資料</param>
        /// <param name="pass">金鑰</param>
        /// <returns>密文</returns>
        Byte[] EncryptEx(Byte[] data, String pass);

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="data">要解密的資料</param>
        /// <param name="pass">密碼</param>
        /// <returns>明文</returns>
        Byte[] DecryptEx(Byte[] data, String pass);
    }
}

 

RC4.cs檔案:

以下是程式碼片段:

using System;
using System.Collections.Generic;
using System.Text;

namespace NewLife.Cryptography
{
    public class RC4Crypto : CryptoBase
    {
        static public RC4Crypto RC4 = new RC4Crypto();

        public override Byte[] EncryptEx(Byte[] data, String pass)
        {
            if (data == null || pass == null) return null;
            Byte[] output = new Byte[data.Length];
            Int64 i = 0;
            Int64 j = 0;
            Byte[] mBox = GetKey(Encode.GetBytes(pass), 256);

            // 加密
            for (Int64 offset = 0; offset < data.Length; offset++)
            {
                i = (i + 1) % mBox.Length;
                j = (j + mBox[i]) % mBox.Length;
                Byte temp = mBox[i];
                mBox[i] = mBox[j];
                mBox[j] = temp;
                Byte a = data[offset];
                //Byte b = mBox[(mBox[i] + mBox[j] % mBox.Length) % mBox.Length];
                // mBox[j] 一定比 mBox.Length 小,不需要在取模
                Byte b = mBox[(mBox[i] + mBox[j]) % mBox.Length];
                output[offset] = (Byte)((Int32)a ^ (Int32)b);
            }

            return output;
        }

        public override Byte[] DecryptEx(Byte[] data, String pass)
        {
            return EncryptEx(data, pass);
        }

        /// <summary>
        /// 打亂密碼
        /// </summary>
        /// <param name="pass">密碼</param>
        /// <param name="kLen">密碼箱長度</param>
        /// <returns>打亂後的密碼</returns>
        static private Byte[] GetKey(Byte[] pass, Int32 kLen)
        {
            Byte[] mBox = new Byte[kLen];

            for (Int64 i = 0; i < kLen; i++)
            {
                mBox[i] = (Byte)i;
            }
            Int64 j = 0;
            for (Int64 i = 0; i < kLen; i++)
            {
                j = (j + mBox[i] + pass[i % pass.Length]) % kLen;
                Byte temp = mBox[i];
                mBox[i] = mBox[j];
                mBox[j] = temp;
            }
            return mBox;
        }
    }
}

相關文章