熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

使用DES對稱加密代碼,支持中文

2022-06-13   來源: .NET編程 
//名稱空間
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 下在下使用成功加密解密正常!
From:http://tw.wingwit.com/Article/program/net/201311/13609.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.