首页 > 编程语言 >C# DES AES 加密解密

C# DES AES 加密解密

时间:2023-04-03 16:34:58浏览次数:52  
标签:aes string C# DES AES 密钥 key using byte

/// <summary>
/// 加密解密帮助类
/// </summary>
public static class EncryptHelper
{
    #region des实现
    /// <summary>
    /// Des默认密钥向量
    /// </summary>
    public static byte[] DesIv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
    /// <summary>
    /// Des加解密钥必须8位
    /// </summary>
    public const string DesKey = "deskey8w";
    /// <summary>
    /// 获取Des8位密钥
    /// </summary>
    /// <param name="key">Des密钥字符串</param>
    /// <returns>Des8位密钥</returns>
    public static byte[] GetDesKey(string key)
    {
        if (string.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException("key", "Des密钥不能为空");
        }
        if (key.Length > 8)
        {
            key = key.Substring(0, 8);
        }
        if (key.Length < 8)
        {
            // 不足8补全
            key = key.PadRight(8, '0');
        }
        return Encoding.UTF8.GetBytes(key);
    }
    /// <summary>
    /// Des加密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="key">des密钥,长度必须8位</param>
    /// <param name="iv">密钥向量</param>
    /// <returns>加密后的字符串</returns>
    public static string DesEncrypt(string source, string key, byte[] iv)
    {
        using (DES des = DES.Create())
        {
            byte[] rgbKeys = GetDesKey(key),
            rgbIvs = iv,
            inputByteArray = Encoding.UTF8.GetBytes(source);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cryptoStream.FlushFinalBlock();
                    // 1.第一种
                    return Convert.ToBase64String(memoryStream.ToArray());

                    // 2.第二种
                    //StringBuilder result = new StringBuilder();
                    //foreach (byte b in memoryStream.ToArray())
                    //{
                    // result.AppendFormat("{0:X2}", b);
                    //}
                    //return result.ToString();
                }
            }
        }
    }
    /// <summary>
    /// Des解密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="key">des密钥,长度必须8位</param>
    /// <param name="iv">密钥向量</param>
    /// <returns>解密后的字符串</returns>
    public static string DesDecrypt(string source, string key, byte[] iv)
    {
        using (DES des = DES.Create())
        {
            byte[] rgbKeys = GetDesKey(key),
            rgbIvs = iv,
            inputByteArray = Convert.FromBase64String(source);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (CryptoStream cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(rgbKeys, rgbIvs), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                    cryptoStream.FlushFinalBlock();
                    return Encoding.UTF8.GetString(memoryStream.ToArray());
                }
            }
        }
    }
    #endregion
    #region aes实现
    /// <summary>
    /// Aes加解密钥必须32位
    /// </summary>
    public const string AesKey = "asekey32w";
    /// <summary>
    /// 获取Aes32位密钥
    /// </summary>
    /// <param name="key">Aes密钥字符串</param>
    /// <returns>Aes32位密钥</returns>
    public static byte[] GetAesKey(string key)
    {
        if (string.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException("key", "Aes密钥不能为空");
        }
        if (key.Length < 32)
        {
            // 不足32补全
            key = key.PadRight(32, '0');
        }
        if (key.Length > 32)
        {
            key = key.Substring(0, 32);
        }
        return Encoding.UTF8.GetBytes(key);
    }
    /// <summary>
    /// Aes加密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="key">aes密钥,长度必须32位</param>
    /// <returns>加密后的字符串</returns>
    public static string AesEncrypt(string source, string key)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = GetAesKey(key);
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            using (ICryptoTransform cryptoTransform = aes.CreateEncryptor())
            {
                byte[] inputBuffers = Encoding.UTF8.GetBytes(source);
                byte[] results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                aes.Clear();
                aes.Dispose();
                return Convert.ToBase64String(results, 0, results.Length);
            }
        }
    }
    /// <summary>
    /// Aes解密
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="key">aes密钥,长度必须32位</param>
    /// <returns>解密后的字符串</returns>
    public static string AesDecrypt(string source, string key)
    {
        using (Aes aes = Aes.Create())
        {
            aes.Key = GetAesKey(key);
            aes.Mode = CipherMode.ECB;
            aes.Padding = PaddingMode.PKCS7;
            using (ICryptoTransform cryptoTransform = aes.CreateDecryptor())
            {
                byte[] inputBuffers = Convert.FromBase64String(source);
                byte[] results = cryptoTransform.TransformFinalBlock(inputBuffers, 0, inputBuffers.Length);
                aes.Clear();
                return Encoding.UTF8.GetString(results);
            }
        }
    }
    #endregion
}

 

翻译

搜索

复制

标签:aes,string,C#,DES,AES,密钥,key,using,byte
From: https://www.cnblogs.com/smartnn/p/17283447.html

相关文章

  • myBatis报错org.apache.ibatis.ognl.NoSuchPropertyException
    跑批任务时mybatis报错org.apache.ibatis.ognl.NoSuchPropertyException,重跑未出现报错,百度发现是由于mybatis依赖的Ognl版本OgnlRuntime.getMethodValue在并发情况下会存在并发问题,错误地返回null引起报错 以下是搜索该问题时找到的资料:https://github.com/1993hzh/tho......
  • 【Struts框架】第一节Action-模块包含和defaultAction
    1.模块包含:struts.xml:里面可以这么写<includefile="login.xml"></include>说明在struts.xml包含了一个login.xml文件login.xml:<?xmlversion="1.0"encoding="GBK"?><!DOCTYPEstrutsPUBLIC"-//apacheSoftwareFound......
  • xcode4.2中使用xib来运行hello world (MainWindow.xib)
    xcode4.2推荐使用storyboard,但网上资料太少,书上讲的也都是基于xib的 花了2天时间,终于把xib的helloWorld写出来了。 注意,类名一定要大写,为了这个东西,我搞了2天,在配viewContorller时一直抛错。 新建EmptyApplication 添加一个object,添加一个ViewController,添加一个window,把Fi......
  • xcode 中使用手动管理内存要修改的地方
    出现error:AutomaticReferenceCountingIssue:ARCforbidsexplicitmessagesendof'release'xcode4.2中,修改 把Yes修改为NO。大小:18KB查看图片附件......
  • dxg:GridControl 单元格关联其他单元格的颜色设定
    列样式:<dxg:GridColumn.CellStyle><StyleTargetType="{x:Typedxg:LightweightCellEditor}"><Style.Triggers><DataTriggerValue="T......
  • Pycharm创建自定义代码片段
    简介PyCharm允许您创建自定义代码片段,也称为代码模板,以提高您的开发效率实现步骤1.添加代码模板打开PyCharm并导航到File->Settings,或者按快捷键ctrl+alt+s打开设置​按照如下序号步骤进行点击,点击“+”按钮以创建新的代码模板,选择LiveTemplate,此处可以看到很多pych......
  • Windows Service Wrapper(winsw.exe)
     用winsw让任何Windows程序都能运行为服务详解WindowsServiceWrapper(winsw.exe)及应用场景 ......
  • vue 项目启动报错opensslErrorStack ERR_OSSL_EVP_UNSUPPORTED
     错误裁图  原因:node升级版本过高 解决办法:windows中在vscode里在命令行输入命令修改环境变量:$env:NODE_OPTIONS="--openssl-legacy-provider"再执行:npmrunserve  linux中exportNODE_OPTIONS=--openssl-legacy-provider  ......
  • C++17:新特性之std::optional
    考虑一个问题,C++如何实现返回多个值?如何标记其中一个bool返回值用于记录函数运行状态?我们可以通过pair或tuple实现,有以下代码:#include<iostream>#include<string>usingnamespacestd;structss{ strings; intsize;};pair<bool,ss>func2(conststring&in){......
  • ansible 部署 docker
    准备工作创建roles目录#mkdir-pv/data/apps/ansible/roles/docker/{files,tasks,handlers,templates,vars}hosts[ubuntu]172.16.18.31ansible_ssh_port=22ansible_ssh_user=ubuntuhostname=app-01测试连通性#ansibleubuntu-mping172.16.18.247|SUCCESS=>{......