using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { public interface IEncrypt { string Encrypt(EncryptInfo model); string Dencrypt(EncryptInfo model); string Check(EncryptInfo model); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { public class EncryptInfo { public EncryptInfo(string source) { this.Source = source; this.Encode = Encoding.Default; } public EncryptInfo(string source, Encoding encode) { this.Source = source; this.Encode = encode; } public string Source { get; set; } public string Key { get; set; } public string Iv { get; set; } public Encoding Encode { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { /// <summary> /// key的长度必须为24位 /// </summary> public class Encrypt3DES : IEncrypt { public string Encrypt(EncryptInfo model) { TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Key = model.Encode.GetBytes(model.Key); DES.Mode = CipherMode.ECB; ICryptoTransform DESEncrypt = DES.CreateEncryptor(); byte[] Buffer = model.Encode.GetBytes(model.Source); return Convert.ToBase64String(DESEncrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); } public string Dencrypt(EncryptInfo model) { TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider(); DES.Key = model.Encode.GetBytes(model.Key); DES.Mode = CipherMode.ECB; DES.Padding = System.Security.Cryptography.PaddingMode.PKCS7; ICryptoTransform DESDecrypt = DES.CreateDecryptor(); byte[] Buffer = Convert.FromBase64String(model.Source); return model.Encode.GetString(DESDecrypt.TransformFinalBlock(Buffer, 0, Buffer.Length)); } public string Check(EncryptInfo model) { StringBuilder sb = new StringBuilder(); if (string.IsNullOrEmpty(model.Key)) sb.Append("秘钥不能为空"); else if (model.Key.Length != 24) sb.Append("秘钥长度必须为24"); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { /// <summary> /// 原名Rijndael /// key 为8 16 24 32位 /// IV 为16位 /// </summary> public class EncryptAES : IEncrypt { public string Encrypt(EncryptInfo model) { //Rijndael rijndael = Rijndael.Create(); //rijndael.IV = model.Encode.GetBytes(model.Iv); //rijndael.Key = model.Encode.GetBytes(model.Key); //Byte[] bytes = model.Encode.GetBytes(model.Source); //string result = ""; //using (ICryptoTransform transform = rijndael.CreateEncryptor()) //{ // byte[] output = transform.TransformFinalBlock(bytes, 0, bytes.Length); // result = Convert.ToBase64String(output); //} //return result; Byte[] plainBytes = model.Encode.GetBytes(model.Source); Byte[] bKey = new Byte[32]; Array.Copy(model.Encode.GetBytes(model.Key.PadRight(bKey.Length)), bKey, bKey.Length); Byte[] bVector = new Byte[16]; Array.Copy(model.Encode.GetBytes(model.Iv.PadRight(bVector.Length)), bVector, bVector.Length); Byte[] Cryptograph = null; Rijndael Aes = Rijndael.Create(); using (MemoryStream Memory = new MemoryStream()) { using (CryptoStream Encryptor = new CryptoStream(Memory, Aes.CreateEncryptor(bKey, bVector), CryptoStreamMode.Write)) { Encryptor.Write(plainBytes, 0, plainBytes.Length); Encryptor.FlushFinalBlock(); Cryptograph = Memory.ToArray(); } } return Convert.ToBase64String(Cryptograph); } public string Dencrypt(EncryptInfo model) { //Rijndael rijndael = Rijndael.Create(); //rijndael.Key = model.Encode.GetBytes(model.Key); //rijndael.IV = model.Encode.GetBytes(model.Iv); //byte[] bytes = model.Encode.GetBytes(model.Source); //using (ICryptoTransform transform2 = rijndael.CreateDecryptor()) //{ // byte[] decryption = transform2.TransformFinalBlock(bytes, 0, bytes.Length); // return model.Encode.GetString(decryption); //} Byte[] encryptedBytes = Convert.FromBase64String(model.Source); Byte[] bKey = new Byte[32]; Array.Copy(model.Encode.GetBytes(model.Key.PadRight(bKey.Length)), bKey, bKey.Length); Byte[] bVector = new Byte[16]; Array.Copy(model.Encode.GetBytes(model.Iv.PadRight(bVector.Length)), bVector, bVector.Length); Byte[] original = null; Rijndael Aes = Rijndael.Create(); using (MemoryStream Memory = new MemoryStream(encryptedBytes)) { using (CryptoStream Decryptor = new CryptoStream(Memory, Aes.CreateDecryptor(bKey, bVector), CryptoStreamMode.Read)) { using (MemoryStream originalMemory = new MemoryStream()) { Byte[] Buffer = new Byte[1024]; Int32 readBytes = 0; while ((readBytes = Decryptor.Read(Buffer, 0, Buffer.Length)) > 0) { originalMemory.Write(Buffer, 0, readBytes); } original = originalMemory.ToArray(); } } } return model.Encode.GetString(original); } public string Check(EncryptInfo model) { StringBuilder sb = new StringBuilder(); if (string.IsNullOrEmpty(model.Key)) sb.Append("秘钥不能为空,"); else if (model.Key.Length != 32) sb.Append("秘钥长度必须为32,"); if (!string.IsNullOrEmpty(model.Iv) && model.Iv.Length != 16) sb.Append("向量长度必须为16,"); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { public class EncryptBase64 : IEncrypt { public string Encrypt(EncryptInfo model) { return Convert.ToBase64String(model.Encode.GetBytes(model.Source)); } public string Dencrypt(EncryptInfo model) { return model.Encode.GetString(Convert.FromBase64String(model.Source)); } public string Check(EncryptInfo model) { return ""; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { /// <summary> /// key 为8位 /// IV 为8位 /// </summary> public class EncryptDES : IEncrypt { public string Encrypt(EncryptInfo model) { string result = ""; byte[] byKey = model.Encode.GetBytes(model.Key); byte[] byIV = model.Encode.GetBytes(model.Iv); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); int i = cryptoProvider.KeySize; using (MemoryStream ms = new MemoryStream()) using (CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write)) using (StreamWriter sw = new StreamWriter(cst)) { sw.Write(model.Source); sw.Flush(); cst.FlushFinalBlock(); sw.Flush(); result = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); } return result; } public string Dencrypt(EncryptInfo model) { string result = ""; byte[] byKey = model.Encode.GetBytes(model.Key); byte[] byIV = model.Encode.GetBytes(model.Iv); byte[] byEnc = Convert.FromBase64String(model.Source); DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); using (MemoryStream ms = new MemoryStream(byEnc)) using (CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read)) using (StreamReader sr = new StreamReader(cst)) result = sr.ReadToEnd(); return result; } public string Check(EncryptInfo model) { StringBuilder sb = new StringBuilder(); if (string.IsNullOrEmpty(model.Key)) sb.Append("秘钥不能为空,"); else if (model.Key.Length != 8) sb.Append("秘钥长度必须为8,"); if (!string.IsNullOrEmpty(model.Iv) && model.Iv.Length != 8) sb.Append("向量长度必须为8,"); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace EncryptBLL { public class EncryptEncode : IEncrypt { public string Encrypt(EncryptInfo model) { return HttpUtility.UrlEncode(model.Source, model.Encode); } public string Dencrypt(EncryptInfo model) { return HttpUtility.UrlDecode(model.Source, model.Encode); } public string Check(EncryptInfo model) { return ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { public class EncryptMD5_16 : IEncrypt { public string Encrypt(EncryptInfo model) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); string result = BitConverter.ToString(md5.ComputeHash(model.Encode.GetBytes(model.Source)), 4, 8); result = result.Replace("-", ""); return result; } public string Dencrypt(EncryptInfo model) { throw new Exception("该方法没有实现方式"); } public string Check(EncryptInfo model) { return ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { public class EncryptMD5_32 : IEncrypt { public string Encrypt(EncryptInfo model) { byte[] result = model.Encode.GetBytes(model.Source); MD5 md5 = new MD5CryptoServiceProvider(); byte[] output = md5.ComputeHash(result); return BitConverter.ToString(output).Replace("-", ""); } public string Dencrypt(EncryptInfo model) { throw new Exception("该方法没有实现方式"); } public string Check(EncryptInfo model) { return ""; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { /// <summary> /// IV为8位 /// key为5-16位 /// </summary> public class EncryptRC2 : IEncrypt { public string Encrypt(EncryptInfo model) { byte[] bytesIV = model.Encode.GetBytes(model.Iv); RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); byte[] bytesInput = model.Encode.GetBytes(model.Source); using (MemoryStream ms = new MemoryStream()) using (CryptoStream cs = new CryptoStream(ms, rc2.CreateEncryptor(model.Encode.GetBytes(model.Key), bytesIV), CryptoStreamMode.Write)) { cs.Write(bytesInput, 0, bytesInput.Length); cs.FlushFinalBlock(); var result = Convert.ToBase64String(ms.ToArray()); return result; } } public string Dencrypt(EncryptInfo model) { byte[] bytesIV = model.Encode.GetBytes(model.Iv); RC2CryptoServiceProvider rc2 = new RC2CryptoServiceProvider(); byte[] bytesInput = Convert.FromBase64String(model.Source); using (MemoryStream ms = new MemoryStream()) using (CryptoStream cs = new CryptoStream(ms, rc2.CreateDecryptor(Encoding.Default.GetBytes(model.Key), bytesIV), CryptoStreamMode.Write)) { cs.Write(bytesInput, 0, bytesInput.Length); cs.FlushFinalBlock(); string result = model.Encode.GetString(ms.ToArray()); return result; } } public string Check(EncryptInfo model) { StringBuilder sb = new StringBuilder(); if (string.IsNullOrEmpty(model.Key)) sb.Append("秘钥不能为空,"); else if (model.Key.Length < 5 || model.Key.Length > 16) sb.Append("秘钥长度必须为5-16之间,"); if (!string.IsNullOrEmpty(model.Iv) && model.Iv.Length != 8) sb.Append("向量长度必须为8,"); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { /// <summary> /// 生成的密文每次都会不同 /// </summary> public class EncryptRSA : IEncrypt { public string Encrypt(EncryptInfo model) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(model.Key); cipherbytes = rsa.Encrypt(model.Encode.GetBytes(model.Source), false); return Convert.ToBase64String(cipherbytes); } public string Dencrypt(EncryptInfo model) { RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); byte[] cipherbytes; rsa.FromXmlString(model.Key); cipherbytes = rsa.Decrypt(Convert.FromBase64String(model.Source), false); return model.Encode.GetString(cipherbytes); } public string Check(EncryptInfo model) { return ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace EncryptBLL { public class EncryptSHA1 : IEncrypt { public string Encrypt(EncryptInfo model) { SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] bytes = model.Encode.GetBytes(model.Source); byte[] output = sha1.ComputeHash(bytes); string result = BitConverter.ToString(output).Replace("-", ""); return result; } public string Dencrypt(EncryptInfo model) { throw new Exception("该方法没有实现方式"); } public string Check(EncryptInfo model) { return ""; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EncryptBLL; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EncryptBLL.Tests { [TestClass()] public class EncryptRSATests { [TestMethod()] public void EncryptTest() { IEncrypt encrypt = new EncryptRSA(); EncryptInfo pwd = new EncryptInfo("123456", Encoding.UTF8); //pwd.Key = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; //var result = encrypt.Encrypt(pwd); //var result1 = new EncryptSHA1().Encrypt(pwd); //pwd.Source = "us=张三&xin=113"; //var result2 = new EncryptEncode().Encrypt(pwd); //Assert.AreEqual("us%3d%e5%bc%a0%e4%b8%89%26xin%3d113", result2); //Assert.AreEqual("7c4a8d09ca3762af61e59520943dc26494f8941b", result1.ToLower()); pwd.Key = "12345678901234567890ab"; pwd.Iv = "1234567890abcd"; var temp = new EncryptAES().Encrypt(pwd); pwd.Source = temp; var temp2 = new EncryptAES().Dencrypt(pwd); } [TestMethod()] public void DencryptTest() { IEncrypt encrypt = new EncryptRSA(); EncryptInfo pwd = new EncryptInfo("QNKz7wMTPJt0UVfOtat0e/az3DrBs00kybYWaC2dhPn+dGATC7xkyBPXitiZfJHxcefunio4aW1Oc3BlC3QIggo/XT2cRE3lRsClOOxyrrTHWmynYkF4pSKr/xIl64fdjm+taOAJHjdeg6iW5V4AMEpnYLNwLoIQCwzNU5+o5yM=", Encoding.UTF8); pwd.Key = @"<RSAKeyValue><Modulus>5m9m14XH3oqLJ8bNGw9e4rGpXpcktv9MSkHSVFVMjHbfv+SJ5v0ubqQxa5YjLN4vc49z7SVju8s0X4gZ6AzZTn06jzWOgyPRV54Q4I0DCYadWW4Ze3e+BOtwgVU1Og3qHKn8vygoj40J6U85Z/PTJu3hN1m75Zr195ju7g9v4Hk=</Modulus><Exponent>AQAB</Exponent><P>/hf2dnK7rNfl3lbqghWcpFdu778hUpIEBixCDL5WiBtpkZdpSw90aERmHJYaW2RGvGRi6zSftLh00KHsPcNUMw==</P><Q>6Cn/jOLrPapDTEp1Fkq+uz++1Do0eeX7HYqi9rY29CqShzCeI7LEYOoSwYuAJ3xA/DuCdQENPSoJ9KFbO4Wsow==</Q><DP>ga1rHIJro8e/yhxjrKYo/nqc5ICQGhrpMNlPkD9n3CjZVPOISkWF7FzUHEzDANeJfkZhcZa21z24aG3rKo5Qnw==</DP><DQ>MNGsCB8rYlMsRZ2ek2pyQwO7h/sZT8y5ilO9wu08Dwnot/7UMiOEQfDWstY3w5XQQHnvC9WFyCfP4h4QBissyw==</DQ><InverseQ>EG02S7SADhH1EVT9DD0Z62Y0uY7gIYvxX/uq+IzKSCwB8M2G7Qv9xgZQaQlLpCaeKbux3Y59hHM+KpamGL19Kg==</InverseQ><D>vmaYHEbPAgOJvaEXQl+t8DQKFT1fudEysTy31LTyXjGu6XiltXXHUuZaa2IPyHgBz0Nd7znwsW/S44iql0Fen1kzKioEL3svANui63O3o5xdDeExVM6zOf1wUUh/oldovPweChyoAdMtUzgvCbJk1sYDJf++Nr0FeNW1RB1XG30=</D></RSAKeyValue>"; var result = encrypt.Dencrypt(pwd); Assert.AreEqual("123456", result); } } }
using EncryptBLL; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace EncryptFac { public partial class Form1 : Form { static List<string> encrypts = new List<string> { "3DES","AES","Base64","DES","Encode","MD5_16","MD5_32","RC2","RSA","SHA1" }; static List<string> encodes = new List<string> { "utf-8","gb2312","default","ascii" }; public Form1() { InitializeComponent(); this.cbxType.DataSource = encrypts; this.cbxEncode.DataSource = encodes; } private void btnEncrypt_Click(object sender, EventArgs e) { try { EncryptInfo encrypt = new EncryptInfo(this.txtSource.Text, Encoding.GetEncoding(this.cbxEncode.SelectedValue.ToString())); encrypt.Iv = this.txtIV.Text; encrypt.Key = this.txtKey.Text; IEncrypt obj = (IEncrypt)CreateInstance("EncryptBLL.Encrypt" + this.cbxType.SelectedValue); string checkeMsg = obj.Check(encrypt); if (string.Empty != checkeMsg) { MessageBox.Show(checkeMsg); return; } this.txtPassword.Text = obj.Encrypt(encrypt); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnDecrypt_Click(object sender, EventArgs e) { try { EncryptInfo encrypt = new EncryptInfo(this.txtSource.Text, Encoding.GetEncoding(this.cbxEncode.SelectedValue.ToString())); encrypt.Iv = this.txtIV.Text; encrypt.Key = this.txtKey.Text; IEncrypt obj = (IEncrypt)CreateInstance("EncryptBLL.Encrypt" + this.cbxType.SelectedValue); string checkeMsg = obj.Check(encrypt); if (string.Empty != checkeMsg) { MessageBox.Show(checkeMsg); return; } this.txtPassword.Text = obj.Dencrypt(encrypt); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void cbxType_SelectedIndexChanged(object sender, EventArgs e) { this.txtPassword.Text = ""; } public object CreateInstance(string fullTypeName, string assemblyPath = "") { Type type = assemblyPath == "" ? Type.GetType(fullTypeName) : Assembly.LoadFile(assemblyPath).GetType(fullTypeName); if (type == null) { FileInfo exeFile = new FileInfo(Assembly.GetExecutingAssembly().Location); FileInfo[] files = exeFile.Directory.GetFiles("*.dll"); foreach (FileInfo fi in files) { type = GetType(fi.FullName, fullTypeName); if (type != null) { break; } } } if (type == null) { return null; } return Activator.CreateInstance(type); } private Type GetType(string dllFile, string fullTypeName) { Type type = Assembly.LoadFile(dllFile).GetType(fullTypeName); return type; } } }