3

C# – 簡單的加解密

 3 years ago
source link: https://fredxxx123.wordpress.com/2012/05/08/c-%e7%b0%a1%e5%96%ae%e7%9a%84%e5%8a%a0%e8%a7%a3%e5%af%86/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

C# – 簡單的加解密

有時候需要把文件進行一些保護,就需要來個加解密囉!

.NET裡面有提供各種演算法的類別可以使用,我挑選比較單純(安全性也較低就是)的DES(Data Encryption Standard=數據加密標準)演算法。

主角是System.Security.Cryptography底下的『DESCryptoServiceProvider

使用方式除了MSDN上的之外,也參考了『C# 使用 MD5, DES, RSA 演算法加解密

個人覺得後者比較簡單易懂啦~

string original = "要被加密的字串";
string key = "abcdefgh";
string iv = "12345678";

DESCryptoServiceProvider des = new DESCryptoServiceProvider();  
des.Key = Encoding.ASCII.GetBytes(key);  
des.IV = Encoding.ASCII.GetBytes(iv);  
byte[] s = Encoding.ASCII.GetBytes(original);  
ICryptoTransform desencrypt = des.CreateEncryptor();  
return BitConverter.ToString(desencrypt.TransformFinalBlock(s, 0, s.Length)).Replace("-", string.Empty);  

除了key&iv是一定要8個字(這裡會自動轉成ascii碼),比較重要的就是上面code中特別標明紅色粗體的ASCII。
這個地方是要根據你所使用的編碼決定,簡單來說,有中文之類的,就需要用UTF8或Unicode等等的。

string hexString = "被加密過的字串";
string key = "abcdefgh";
string iv = "12345678";

DESCryptoServiceProvider des = new DESCryptoServiceProvider();   
des.Key = Encoding.ASCII.GetBytes(key);
des.IV = Encoding.ASCII.GetBytes(iv);   
byte[] s = new byte[hexString.Length / 2];   
int j = 0;   
for (int i = 0; i < hexString.Length/2; i++)   
{   
  s[i] = Byte.Parse(hexString[j].ToString() + hexString[j + 1].ToString(), System.Globalization.NumberStyles.HexNumber);   
  j += 2;   
}   
ICryptoTransform desencrypt = des.CreateDecryptor();   
return Encoding.ASCII.GetString(desencrypt.TransformFinalBlock(s, 0, s.Length));

解密的部分就一樣注意編碼要相同才不會出事哪!

資料加密標準(DES,Data Encryption Standard) – Wiki

initialization vector (IV) – Wiki

WEP Cracking
原來WEP這麼不安全阿…幾秒鐘就能解了耶!!

正在載入...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK