zoukankan      html  css  js  c++  java
  • C#字符串加密与解密

    1.引用:

    using System.Security.Cryptography;
    using System.Text;

    2.代码

    static string encryptKey = "abcd";//字符串加密密钥(注意:密钥只能是4位)

    public string Encrypt(string str)
    {//加密字符串

    try
    {
    byte[] key = Encoding.Unicode.GetBytes(encryptKey);//密钥
    byte[] data = Encoding.Unicode.GetBytes(str);//待加密字符串

    DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();//加密、解密对象
    MemoryStream MStream = new MemoryStream();//内存流对象

    //用内存流实例化加密流对象
    CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write);
    CStream.Write(data, 0, data.Length);//向加密流中写入数据
    CStream.FlushFinalBlock();//将数据压入基础流
    byte[] temp = MStream.ToArray();//从内存流中获取字节序列
    CStream.Close();//关闭加密流
    MStream.Close();//关闭内存流

    return Convert.ToBase64String(temp);//返回加密后的字符串
    }
    catch
    {
    return str;
    }
    }

    public string Decrypt(string str)
    {//解密字符串

    try
    {
    byte[] key = Encoding.Unicode.GetBytes(encryptKey);//密钥
    byte[] data = Convert.FromBase64String(str);//待解密字符串

    DESCryptoServiceProvider descsp = new DESCryptoServiceProvider();//加密、解密对象
    MemoryStream MStream = new MemoryStream();//内存流对象

    //用内存流实例化解密流对象
    CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write);
    CStream.Write(data, 0, data.Length);//向加密流中写入数据
    CStream.FlushFinalBlock();//将数据压入基础流
    byte[] temp = MStream.ToArray();//从内存流中获取字节序列
    CStream.Close();//关闭加密流
    MStream.Close();//关闭内存流

    return Encoding.Unicode.GetString(temp);//返回解密后的字符串
    }
    catch
    {
    return str;
    }
    }

    参考:https://www.cnblogs.com/nb08611033/p/9183198.html

  • 相关阅读:
    微服务架构设计和应用
    Jenkins持续部署
    Jenkins服务器维护
    Jenkins管理插件(备份插件)
    Jenkins安全
    Jenkins分布式构建
    Jenkins报表 代码 指标分析
    Jenkins远程测试
    Jenkins邮件通知
    Jenkins自动化测试
  • 原文地址:https://www.cnblogs.com/nn1314/p/10893743.html
Copyright © 2011-2022 走看看