Standard DES encryption JAVA C # generic

Source: Internet
Author: User

// <summary>
// des encryption
// </summary>
/// <param name= "str" > Strings to be encrypted </param>
//<param name= "key" > key (8-bit) </param>
// <returns></returns>
Public static string Encode (String str, string key)
{
Try
{
DESCryptoServiceProvider Provider = new DESCryptoServiceProvider ();
provider. Key = Encoding.ASCII.GetBytes (key. Substring (0, 8));
PROVIDER.IV = Encoding.ASCII.GetBytes (key. Substring (0, 8));
byte[] bytes = encoding.getencoding ("GB2312"). GetBytes (str);
MemoryStream ms = new MemoryStream ();
CryptoStream cs = new CryptoStream (MS, provider. CreateEncryptor (), cryptostreammode.write);
cs. Write (bytes, 0, bytes. Length);
cs. FlushFinalBlock ();
StringBuilder builder = new StringBuilder ();
foreach (Byte num in Ms. ToArray ())
{
Builder. AppendFormat ("{0:x2}", num);
}
Ms. Close ();
return builder. ToString ();
}
catch (Exception) {return ' xxxx ';}
}

// <summary>
// des decryption
// </summary>
/// <param name= "str" > String to Decrypt </param>
//<param name= "key" > key (8-bit) </param>
// <returns></returns>
Public static string Decode (String str, string key)
{
Try
{
DESCryptoServiceProvider Provider = new DESCryptoServiceProvider ();
provider. Key = Encoding.ASCII.GetBytes (key. Substring (0, 8));
PROVIDER.IV = Encoding.ASCII.GetBytes (key. Substring (0, 8));
byte[] buffer = new BYTE[STR. LENGTH/2];
for (int i = 0; i < str. LENGTH/2); i++)
{
int num2 = Convert.ToInt32 (str. Substring (i * 2, 2), 0x10);
Buffer[i] = (byte) num2;
}
MemoryStream ms = new MemoryStream ();
CryptoStream cs = new CryptoStream (MS, provider. CreateDecryptor (), cryptostreammode.write);
cs. Write (buffer, 0, buffer. Length);
cs. FlushFinalBlock ();
Ms. Close ();
return encoding.getencoding ("GB2312"). GetString (Ms. ToArray ());
}
catch (Exception) {return "";}
}

Standard DES encryption JAVA C # generic

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.