• DES加密解密


     密鈅長度有規定,密文長度應該是無限定。註釋中寫的長度是爲了滿足以下需求:密文長度固定。
     1     ///<summary>
    2 ///DES 加密解密
    3 ///Rex Rao @2011-5-13
    4 ///</summary>
    5 public static class DES
    6 {
    7 ///<summary>
    8 /// DES加密
    9 ///</summary>
    10 ///<param name="content">8-15bytes明文</param>
    11 ///<param name="key">8bytes密鈅</param>
    12 ///<returns>32bytes密文</returns>
    13 public static string DESEncrypt(string content, string key)
    14 {
    15 byte[] data = Encoding.ASCII.GetBytes(content);
    16 DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
    17 DES.Key = ASCIIEncoding.ASCII.GetBytes(key);
    18 DES.IV = ASCIIEncoding.ASCII.GetBytes(key);
    19 MemoryStream ms = new MemoryStream(); //內存流。
    20 CryptoStream cs = new CryptoStream(ms, DES.CreateEncryptor(), CryptoStreamMode.Write);//內存流創建為加密轉換流
    21 cs.Write(data, 0, data.Length);
    22 cs.FlushFinalBlock(); //用缓冲区的当前状态更新基础数据源或储存库,随后清除缓
    23 StringBuilder ret = new StringBuilder();
    24 foreach (byte b in ms.ToArray())
    25 {
    26 ret.AppendFormat("{0:X2}", b);
    27 }
    28 return ret.ToString();
    29 }
    30
    31 ///<summary>
    32 /// DES解密
    33 ///</summary>
    34 ///<param name="content">32bytes密文</param>
    35 ///<param name="key">8bytes密鈅</param>
    36 ///<returns>8-15bytes明文</returns>
    37 public static string DESDecrypt(string content, string key)
    38 {
    39 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
    40
    41 //Put the input string into the byte array
    42 byte[] inputByteArray = new byte[content.Length / 2];
    43 for (int x = 0; x < content.Length; x += 2)
    44 {
    45 int i = Convert.ToInt32(content.Substring(x, 2), 16);
    46 inputByteArray[x / 2] = (byte)i;
    47 }
    48
    49 des.Key = ASCIIEncoding.ASCII.GetBytes(key);
    50 des.IV = ASCIIEncoding.ASCII.GetBytes(key);
    51 MemoryStream ms = new MemoryStream();
    52 CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
    53 //Flush the data through the crypto stream into the memory stream
    54 cs.Write(inputByteArray, 0, inputByteArray.Length);
    55 cs.FlushFinalBlock();
    56
    57 //Get the decrypted data back from the memory stream
    58 //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象
    59 StringBuilder ret = new StringBuilder();
    60
    61 return System.Text.Encoding.UTF8.GetString(ms.ToArray());
    62 }
    63 }



  • 相关阅读:
    SpringBoot2.x前后端分离跨域问题及Swagger不能访问
    SpirngBoot2.x整合Swagger2接口文档
    SpringBoot2.x整合Druid数据源
    SpringBoot2.x整合logback 实现自动打印日志
    docker 进入 mysql中的操作
    Intellij Springboot (子模块)访问jsp页面404
    运行rabbitmq 的docker
    mybatis拦截器修改sql重新set后不生效?
    oracle+mybatis如何在新增时返回主键(自增序列)的值?
    oracle+mybatis报“未找到要求的from关键字”错误?
  • 原文地址:https://www.cnblogs.com/sohobloo/p/2249550.html
Copyright © 2020-2023  润新知