c# 自定义加密解密工具,避免MD5加密不可逆或者DES对称加密容易被破解问题。

不多说,直接上代码。。。↓↓↓↓↓↓↓↓↓↓↓↓↓↓

1、定义8位的加密秘钥

    /// 
    /// 加密密钥(8位)
    /// 
    public static string KEY_64 = "00000000";

2、定义8位的初始化向量

    /// 
    /// 加密初始化向量(8位)
    /// 
    public static string IV_64 = "88888888";

3、通过初始化向量与加密秘钥生成加密内容

    /// 
    /// 加密
    /// 
    /// 
    /// 
    public static string Encode(string data)
    {
        byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
        byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
        int i = cryptoProvider.KeySize;
        MemoryStream ms = new MemoryStream();
        CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);

        StreamWriter sw = new StreamWriter(cst);
        sw.Write(data);
        sw.Flush();
        cst.FlushFinalBlock();
        sw.Flush();
        return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length).Replace("=", "φ");

    }

4、通过初始化向量与加密秘钥对加密内容进行解密

    /// 
    /// 解密
    /// 
    /// 
    /// 
    public static string Decode(string data)
    {
        try
        {
            byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
            byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);

            byte[] byEnc;
            try
            {
                byEnc = Convert.FromBase64String(data.Replace("φ", "="));
            }
            catch
            {
                return null;
            }

            DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
            MemoryStream ms = new MemoryStream(byEnc);
            CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cst);
            return sr.ReadToEnd();
        }
        catch
        { return ""; }
    }

5、到这里就大功告成啦!

你可能感兴趣的:(工具软件,C#)