Use DES symmetrical encryption code to support Chinese

xiaoxiao2021-03-06  59

// Name Space

Using system;

Using system.security.cryptography;

Using system.io;

Using system.text;

//method

// encryption method

Public String Encrypt (String Ptoencrypt, String Skey)

{

DescryptoServiceProvider des = New DescryptoServiceProvider ();

// put the string in the BYTE array

/ / The UTF8 encoding used, I changed to Unicode encoded, no

BYTE [] INPUTBYTEARRAY = Encoding.default.getbytes (ptoencrypt);

// Byte [] INPUTBYTEARRAY = Encoding.unicode.getBytes (PToEncrypt);

/ / Establish the key and offset of the encryption object

// original text uses the getBytes method of the ASCIENCODING.ASCII method

// Make Enter the password must enter English text

DES.key = asciiencoding.ascii.getbytes (SKEY);

DES.IV = asciiencoding.ascii.getbytes (SKEY);

MemoryStream MS = New MemoryStream ();

CryptostReam Cs = New CryptostReam (MS, DES.CREATEENCRYPTOR (), CRYPTOSTREAMMODE.WRITE);

// Write the Byte Array Into The Crypto Street

// (IT WILL End Up in The Memory Stream)

CS.Write (InputByteArray, 0, InputByteaRray.Length);

cs.flushfinalblock ();

// Get The Data Back from the memory stream, and into a string

StringBuilder Ret = new stringbuilder ();

Foreach (byte b in ms.toarray ())

{

// Format As Hex

RET.APpendFormat ("{0: X2}", B);

}

Ret.toString ();

Return Ret.toString ();

}

// Decryption method

Public String Decrypt (String Ptodecrypt, String SKey)

{

DescryptoServiceProvider des = New DescryptoServiceProvider ();

// put the input string ion inte array

Byte [] InputByteArray = new byte [ptodecrypt.length / 2];

For (int x = 0; x

{

INT i = (Convert.Toint 32 (Ptodecrypt.Substring (x * 2, 2), 16);

INPUTBYTEARRAY [X] = (Byte) i;

}

/ / Establish the key and offset of the encryption object, this value is important, can not be modified

DES.key = asciiencoding.ascii.getbytes (SKEY);

DES.IV = asciiencoding.ascii.getbytes (SKEY);

MemoryStream ms = new memorystream (); cryptostream cs = new cryptostream (ms, des.createdecryptor (), cryptostreammode.write;

// Flush The Data Throgh The Crypto Street Into The Memory Stream INTO THE

CS.Write (InputByteArray, 0, InputByteaRray.Length) and the INPUTBYTEARRAY.LEngth;

cs.flushfinalblock ();

// Get The Decrypted Data Back from The Memory Stream

// Establish a StringBuild object, create the stream object, must turn the decrypted text into the flow object

StringBuilder Ret = new stringbuilder ();

Return system.text.Encoding.default.getstring (ms.toArray ());

}

// ------- Code is complete --------------------

Note: When SKEY enters a password, you must use the English characters, which is case sensitive, and the number of characters is 8, and it cannot be more, otherwise it is wrong.

I use Windows2000 Server .NET Framework SP3, VS.NET is used under ASP.NET, and the encryption is normal!

转载请注明原文地址:https://www.9cbs.com/read-87552.html

New Post(0)