Java encryption!

Source: Internet
Author: User

// Default key vector

Private static byte [] Keys = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };

///

/// DES encrypted string

///

/// String to be encrypted

/// Encryption key, which must be 8 bits

/// The encrypted string is returned successfully. If the encrypted string fails, the source string is returned.

Public static string EncryptDES (string encryptString, string encryptKey)

{

Try

{

Byte [] rgbKey = Encoding. UTF8.GetBytes (encryptKey. Substring (0, 8 ));

Byte [] rgbIV = Keys;

Byte [] inputByteArray = Encoding. UTF8.GetBytes (encryptString );

DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider ();

MemoryStream mStream = new MemoryStream ();

CryptoStream 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;

}

}

///

/// DES decryption string

///

/// String to be decrypted

/// Decrypt the key, which must be 8 bits and the same as the encryption key

/// After successful decryption, the decrypted string is returned, and the source string fails to be returned.

Public static string DecryptDES (string decryptString, string decryptKey)

{

Try

{

Byte [] rgbKey = Encoding. UTF8.GetBytes (decryptKey );

Byte [] rgbIV = Keys;

Byte [] inputByteArray = Convert. FromBase64String (decryptString );

DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider ();

MemoryStream mStream = new MemoryStream ();

CryptoStream cStream = new CryptoStream (mStream, DCSP. CreateDecryptor (rgbKey, rgbIV), CryptoStreamMode. Write );

CStream. Write (inputByteArray, 0, inputByteArray. Length );

CStream. FlushFinalBlock ();

Return Encoding. UTF8.GetString (mStream. ToArray ());

}

Catch

{

Return decryptString;

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.