1、KEY和IV分别赋值
//默认密钥向量 private static byte[] Iv= { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; /// <summary> /// DES加密字符串 /// </summary> /// <param name="encryptString">待加密的字符串</param> /// <param name="encryptKey">加密密钥,要求为8位</param> /// <returns>加密成功返回加密后的字符串,失败返回源串</returns> public static string EncryptDES(string encryptString, string encryptKey) { try { byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); byte[] rgbIV = Iv; byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); var mStream = new MemoryStream(); var cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey,rgbIV), CryptoStreamMode.Write); cStream.Write(inputByteArray, 0, inputByteArray.Length); cStream.FlushFinalBlock(); return Convert.ToBase64String(mStream.ToArray()); } catch { return encryptString; } }
2、根据8位密钥,建立KEY和IV
public static string Encrypt(string pToEncrypt, string sKey) { var des = new DESCryptoServiceProvider(); //把字符串放到byte数组中 byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); //建立加密对象的密钥和偏移量 des.Key = Encoding.ASCII.GetBytes(sKey); des.IV = Encoding.ASCII.GetBytes(sKey); var ms = new MemoryStream(); var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); return Encoding.UTF8.GetString(ms.ToArray()); }
3、KEY和IV为空,调用 GenerateKey 方法以创建新的随机key ,调用 GenerateIV 方法以创建新的随机 IV
using System;
using System.Security.Cryptography;
using System.Text;
class EncryptorExample
{
private static string quote =
"Things may come to those who wait, but only the " +
"things left by those who hustle. -- Abraham Lincoln";
public static void Main()
{
AesCryptoServiceProvider aesCSP = new AesCryptoServiceProvider();
aesCSP.GenerateKey();
aesCSP.GenerateIV();
byte[] encQuote = EncryptString(aesCSP, quote);
Console.WriteLine("Encrypted Quote:\n");
Console.WriteLine(Convert.ToBase64String(encQuote));
Console.WriteLine("\nDecrypted Quote:\n");
Console.WriteLine(DecryptBytes(aesCSP, encQuote));
}
public static byte[] EncryptString(SymmetricAlgorithm symAlg, string inString)
{
byte[] inBlock = UnicodeEncoding.Unicode.GetBytes(inString);
ICryptoTransform xfrm = symAlg.CreateEncryptor();
byte[] outBlock = xfrm.TransformFinalBlock(inBlock, 0, inBlock.Length);
return outBlock;
}
public static string DecryptBytes(SymmetricAlgorithm symAlg, byte[] inBytes)
{
ICryptoTransform xfrm = symAlg.CreateDecryptor();
byte[] outBlock = xfrm.TransformFinalBlock(inBytes, 0, inBytes.Length);
return UnicodeEncoding.Unicode.GetString(outBlock);
}
}
另外:一般DES加密完的字符串大概长这样:U2FsdGVkX1+PX0/VZiqtq/fOMdgdX7mTQh3RNACgods=
因为有一些特殊符号,如果拼在querystring中不便于传输,可以考虑这样写:
var str= new StringBuilder(); foreach (byte b in ms.ToArray()) { str.AppendFormat("{0:X2}", b); } return str.ToString();
来代替直接返回 return Encoding.UTF8.GetString(ms.ToArray());
这样加密后的字符串长这样:4BD2B330AA45FFAD57109EE56D34E21B7E3858BA45A096220EB6634A5B779E80