ASP.NET MVC + DES – Single Sign On 方法
\Library\Encrypt.cs |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Text; using System.Security.Cryptography; using System.IO; namespace DES_SSO.Library { public class Encrypt { private string key; private byte[] bytes; public Encrypt(string key) { this.key = key.Substring(0, 8); this.bytes = ASCIIEncoding.ASCII.GetBytes(this.key); } public string encrypt(string originalString) { if (String.IsNullOrEmpty(originalString)) { throw new ArgumentNullException("The string which needs to be encrypted can not be null."); } DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(this.bytes, this.bytes), CryptoStreamMode.Write); StreamWriter writer = new StreamWriter(cryptoStream); writer.Write(originalString); writer.Flush(); cryptoStream.FlushFinalBlock(); writer.Flush(); return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length); } public string decrypt(string cryptedString) { if (String.IsNullOrEmpty(cryptedString)) { throw new ArgumentNullException("The string which needs to be decrypted can not be null."); } DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(cryptedString)); CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(this.bytes, this.bytes), CryptoStreamMode.Read); StreamReader reader = new StreamReader(cryptoStream); return reader.ReadToEnd(); } public bool validate(string plaintext, string hash) { return this.encrypt(plaintext).Equals(hash); } } } |
View |
@Html.ActionLink("SSO", "SSO", "Home", new { hash = ViewBag.Hash }, null) |
Controller |
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Configuration; using DES_SSO.Library; namespace DES_SSO.Controllers { public class HomeController : Controller { … … public ActionResult SSO(string hash) { string key = ConfigurationManager.AppSettings["Key"].ToString(); string plaintext = ConfigurationManager.AppSettings["PlainText"].ToString(); Encrypt en = new Encrypt(key); if(en.validate(plaintext, hash)) return View("Index"); else return View("Login"); } } } |