//名称空间
using System;
using SystemSecurityCryptography;
using SystemIO;
using SystemText;
//方法
//加密方法
public string Encrypt(string pToEncrypt string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//把字符串放到byte数组中
//原来使用的UTF编码我改成Unicode编码了不行
byte[] inputByteArray = EncodingDefaultGetBytes(pToEncrypt);
//byte[] inputByteArray=EncodingUnicodeGetBytes(pToEncrypt);
//建立加密对象的密钥和偏移量
//原文使用ASCIIEncodingASCII方法的GetBytes方法
//使得输入密码必须输入英文文本
desKey = ASCIIEncodingASCIIGetBytes(sKey);
desIV = ASCIIEncodingASCIIGetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms desCreateEncryptor()CryptoStreamModeWrite);
//Write the byte array into the crypto stream
//(It will end up in the memory stream)
csWrite(inputByteArray inputByteArrayLength);
csFlushFinalBlock();
//Get the data back from the memory stream and into a string
StringBuilder ret = new StringBuilder();
foreach(byte b in msToArray())
{
//Format as hex
retAppendFormat({:X} b);
}
retToString();
return retToString();
}
//解密方法
public string Decrypt(string pToDecrypt string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//Put the input string into the byte array
byte[] inputByteArray = new byte[pToDecryptLength / ];
for(int x = ; x < pToDecryptLength / ; x++)
{
int i = (ConvertToInt(pToDecryptSubstring(x * ) ));
inputByteArray[x] = (byte)i;
}
//建立加密对象的密钥和偏移量此值重要不能修改
desKey = ASCIIEncodingASCIIGetBytes(sKey);
desIV = ASCIIEncodingASCIIGetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms desCreateDecryptor()CryptoStreamModeWrite);
//Flush the data through the crypto stream into the memory stream
csWrite(inputByteArray inputByteArrayLength);
csFlushFinalBlock();
//Get the decrypted data back from the memory stream
//建立StringBuild对象CreateDecrypt使用的是流对象必须把解密后的文本变成流对象
StringBuilder ret = new StringBuilder();
return SystemTextEncodingDefaultGetString(msToArray());
}
//代码完毕
注意sKey输入密码的时候必须使用英文字符区分大小写且字符数量是个不能多也不能少否则出错
本人使用Windows Framework SP 下在下使用成功加密解密正常!