DES 对称加密(C#实现加密,Java可解密)

分类:C#     发布:2020-04-24     来源:本站     浏览:311 次
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

/// <summary>
///     DES3加密解密
/// </summary>
public class Des3
{
    public static void Main()
    {

        byte[] key = Convert.FromBase64String("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4"); //key为abcdefghijklmnopqrstuvwx的Base64编码
        byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
        var data = Encoding.UTF8.GetBytes("中国ABCabc123:{}");

        Console.WriteLine("ECB模式:");//当模式为ECB时,IV无用
        var encode = Des3EncodeECB(key, iv, data);
        var decode = Des3DecodeECB(key, iv, encode);
        Console.WriteLine("加密:" + Convert.ToBase64String(encode));
        Console.WriteLine("解密:" + Encoding.UTF8.GetString(decode));
        Console.WriteLine();

        Console.WriteLine("CBC模式:");
        encode = Des3EncodeCBC(key, iv, data);
        decode = Des3DecodeCBC(key, iv, encode);
        Console.WriteLine("加密:" + Convert.ToBase64String(encode));
        Console.WriteLine("解密:" + Encoding.UTF8.GetString(decode));
        Console.WriteLine();

        Console.Read();
    }

    #region CBC模式**

    /// <summary>
    ///     DES3 CBC模式加密
    /// </summary>
    /// <param name="key">密钥</param>
    /// <param name="iv">IV</param>
    /// <param name="data">明文的byte数组</param>
    /// <returns>密文的byte数组</returns>
    public static byte[] Des3EncodeCBC(byte[] key, byte[] iv, byte[] data)
    {
        try
        {
            byte[] bytes;
            using (var memoryStream = new MemoryStream())
            {
                var provider = new TripleDESCryptoServiceProvider { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
                using (var stream = new CryptoStream(memoryStream, provider.CreateEncryptor(key, iv), CryptoStreamMode.Write))
                {
                    stream.Write(data, 0, data.Length);
                    stream.FlushFinalBlock();
                    bytes = memoryStream.ToArray();
                    stream.Close();
                }
                memoryStream.Close();
            }
            return bytes;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }

    /// <summary>
    ///     DES3 CBC模式解密
    /// </summary>
    /// <param name="key">密钥</param>
    /// <param name="iv">IV</param>
    /// <param name="data">密文的byte数组</param>
    /// <returns>明文的byte数组</returns>
    public static byte[] Des3DecodeCBC(byte[] key, byte[] iv, byte[] data)
    {
        try
        {
            var memoryStream = new MemoryStream(data);
            var provider = new TripleDESCryptoServiceProvider { Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 };
            byte[] bytes;
            using (var stream = new CryptoStream(memoryStream, provider.CreateDecryptor(key, iv), CryptoStreamMode.Read))
            {
                bytes = new byte[data.Length];
                stream.Read(bytes, 0, bytes.Length);
            }
            return bytes;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }

    #endregion

    #region ECB模式

    /// <summary>
    ///     DES3 ECB模式加密
    /// </summary>
    /// <param name="key">密钥</param>
    /// <param name="iv">IV(当模式为ECB时,IV无用)</param>
    /// <param name="data">明文的byte数组</param>
    /// <returns>密文的byte数组</returns>
    public static byte[] Des3EncodeECB(byte[] key, byte[] iv, byte[] data)
    {
        try
        { 
            var memoryStream = new MemoryStream();
            var provider = new TripleDESCryptoServiceProvider {Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};
            byte[] bytes;
            using (var stream = new CryptoStream(memoryStream, provider.CreateEncryptor(key, iv), CryptoStreamMode.Write))
            {
                stream.Write(data, 0, data.Length);
                stream.FlushFinalBlock(); 
                bytes = memoryStream.ToArray(); 
                stream.Close();
            }
            memoryStream.Close(); 
            return bytes;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }

    /// <summary>
    ///     DES3 ECB模式解密
    /// </summary>
    /// <param name="key">密钥</param>
    /// <param name="iv">IV(当模式为ECB时,IV无用)</param>
    /// <param name="data">密文的byte数组</param>
    /// <returns>明文的byte数组</returns>
    public static byte[] Des3DecodeECB(byte[] key, byte[] iv, byte[] data)
    {
        try
        { 
            var memoryStream = new MemoryStream(data);
            var provider = new TripleDESCryptoServiceProvider {Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7};
            byte[] bytes;
            using (var stream = new CryptoStream(memoryStream, provider.CreateDecryptor(key, iv), CryptoStreamMode.Read))
            {
                bytes = new byte[data.Length]; 
                stream.Read(bytes, 0, bytes.Length);
            }
            return bytes;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
    }
    #endregion
}
        

如果觉得文章对您有帮助,您可以对我进行打赏 ¥0.57 元(金额随机^_^,每次刷新金额不同)。

请使用支付宝扫码支付

留言评论

*称  呼:
*联系方式: 方便与您取得联系,推荐使用邮箱。
*内  容:

已有评论

暂无数据

上一篇:SQLServer 移除HTML函数

下一篇:DES 对称加密(Java实现加密,C#可解密)