標籤:
C#對字串的簡單加密解密過程C#的SQL資料庫登陸密碼的加密解密加密還原直接複製代碼使用即可
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Security.Cryptography; using System.IO; namespace PDAPrint{ class ClassSecurityString { public static string encryptKey = "www.hanma-scan.com"; //定義密鑰 public static string Encrypt(string str) { DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //執行個體化加/解密類對象 byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定義位元組數組,用來儲存體金鑰 byte[] data = Encoding.Unicode.GetBytes(str);//定義位元組數組,用來儲存要加密的字串 MemoryStream MStream = new MemoryStream(); //執行個體化記憶體流對象 //使用記憶體流執行個體化加密流對象 CryptoStream CStream = new CryptoStream(MStream, descsp.CreateEncryptor(key, key), CryptoStreamMode.Write); CStream.Write(data, 0, data.Length); //向加密流中寫入資料 CStream.FlushFinalBlock(); //釋放加密流 return Convert.ToBase64String(MStream.ToArray());//返回加密後的字串 } /// <summary> /// 解密字串 /// </summary> /// <param name="str">要解密的字串</param> /// <returns>解密後的字串</returns> public static string Decrypt(string str) { DESCryptoServiceProvider descsp = new DESCryptoServiceProvider(); //執行個體化加/解密類對象 byte[] key = Encoding.Unicode.GetBytes(encryptKey); //定義位元組數組,用來儲存體金鑰 byte[] data = Convert.FromBase64String(str);//定義位元組數組,用來儲存要解密的字串 MemoryStream MStream = new MemoryStream(); //執行個體化記憶體流對象 //使用記憶體流執行個體化解密流對象 CryptoStream CStream = new CryptoStream(MStream, descsp.CreateDecryptor(key, key), CryptoStreamMode.Write); CStream.Write(data, 0, data.Length); //向解密流中寫入資料 CStream.FlushFinalBlock(); //釋放解密流 return Encoding.Unicode.GetString(MStream.ToArray()); //返回解密後的字串 } }}
private void button10_Click(object sender, EventArgs e)
{
string str = "123"; //記錄輸入的字串
string strNew =ClassSecurityString.Encrypt(str); //加密字串
string strOld = ClassSecurityString.Decrypt(strNew);
MessageBox.Show("【加密:" + strNew + @"】" + "【解密:" + strOld + @"】");
}
漢碼盤點機原創,轉載請註明出處。
漢碼盤點機——專註於傻瓜式的倉庫條碼管理,國內倉庫條碼管理整體解決方案領導品牌。
(官網:www.hanma-scan.com)
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
C#對字串的簡單加密解密過程C#的SQL資料庫登陸密碼的加密解密加密還原直接複製代碼使用即可