熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

小技巧:用C#實現Des加密和解密

2022-06-13   來源: .NET編程 

  using System;
  using SystemIO;
  using SystemSecurityCryptography;
  
  namespace Vavic
  {
  /// <summary>
  /// Security 的摘要說明
  /// </summary>
  public class Security
  {
  const string KEY_ = VavicApp;
  const string IV_ = VavicApp; //注意了個字符
  
  public Security()
  {
  //
  // TODO: 在此處添加構造函數邏輯
  //
  }
  
  public static string Encode(string data)
  {
  byte[] byKey = SystemTextASCIIEncodingASCIIGetBytes(KEY_);
  byte[] byIV = SystemTextASCIIEncodingASCIIGetBytes(IV_);
  
  DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
  int i = cryptoProviderKeySize;
  MemoryStream ms = new MemoryStream();
  CryptoStream cst = new CryptoStream(mscryptoProviderCreateEncryptor(byKeybyIV)CryptoStreamModeWrite);
  
  StreamWriter sw = new StreamWriter(cst);
  swWrite(data);
  swFlush();
  cstFlushFinalBlock();
  swFlush();
  return ConvertToBaseString(msGetBuffer()(int)msLength);
  
  }
  
  public static string Decode(string data)
  {
  byte[] byKey = SystemTextASCIIEncodingASCIIGetBytes(KEY_);
  byte[] byIV = SystemTextASCIIEncodingASCIIGetBytes(IV_);
  
  byte[] byEnc;
  try
  {
  byEnc = ConvertFromBaseString(data);
  }
  catch
  {
  return null;
  }
  
  DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
  MemoryStream ms = new MemoryStream(byEnc);
  CryptoStream cst = new CryptoStream(mscryptoProviderCreateDecryptor(byKeybyIV)CryptoStreamModeRead);
  StreamReader sr = new StreamReader(cst);
  return srReadToEnd();
  }
  }
  }
From:http://tw.wingwit.com/Article/program/net/201311/11773.html
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.