JAVA and. net des encryption and decryption

Source: Internet
Author: User
Tags decrypt

[To] original address: http://www.cnblogs.com/prince3245/archive/2010/03/23/1692630.html

JAVA and. net des encryption and decryption

A project was created a few days ago, which requires DES encryption between the two systems. One system is developed for JAVA, and the other one is developed for. Net.

I found a lot of writing methods on the Internet, but the encrypted data cannot be matched between the two systems,

I can use it after making a small modification and have tested it.

JAVA version

Import javax. crypto. Cipher;
Import javax. crypto. SecretKey;
Import javax. crypto. SecretKeyFactory;
Import javax. crypto. spec. DESKeySpec;
Import javax. crypto. spec. IvParameterSpec;


Public class Des {
Private byte [] cipher ey;


// Decrypt data
Public static String decrypt (String message, String key) throws Exception {

Byte [] bytesrc = convertHexString (message );
Cipher cipher = Cipher. getInstance ("DES/CBC/PKCS5Padding ");
DESKeySpec desKeySpec = new DESKeySpec (key. getBytes ("UTF-8 "));
SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES ");
SecretKey secretKey = keyFactory. generateSecret (desKeySpec );
IvParameterSpec iv = new IvParameterSpec (key. getBytes ("UTF-8 "));

Cipher. init (Cipher. DECRYPT_MODE, secretKey, iv );

Byte [] retByte = cipher. doFinal (bytesrc );
Return new String (retByte );
}

Public static byte [] encrypt (String message, String key)
Throws Exception {
Cipher cipher = Cipher. getInstance ("DES/CBC/PKCS5Padding ");

DESKeySpec desKeySpec = new DESKeySpec (key. getBytes ("UTF-8 "));

SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES ");
SecretKey secretKey = keyFactory. generateSecret (desKeySpec );
IvParameterSpec iv = new IvParameterSpec (key. getBytes ("UTF-8 "));
Cipher. init (Cipher. ENCRYPT_MODE, secretKey, iv );

Return cipher. doFinal (message. getBytes ("UTF-8 "));
}

Public static byte [] convertHexString (String ss)
{
Byte digest [] = new byte [ss. length ()/2];
For (int I = 0; I <digest. length; I ++)
{
String byteString = ss. substring (2 * I, 2 * I + 2 );
Int byteValue = Integer. parseInt (byteString, 16 );
Digest [I] = (byte) byteValue;
}

Return digest;
}


Public static void main (String [] args) throws Exception {
String key = "12345678 ";
String value = "test1234 ";
String jiami = java.net. URLEncoder. encode (value, "UTF-8"). toLowerCase ();

System. out. println ("encrypted data:" + jiami );
String a = toHexString (encrypt (jiami, key). toUpperCase ();


System. out. println ("encrypted data:" + );
String B = java.net. URLDecoder. decode (decrypt (a, key), "UTF-8 ");
System. out. println ("decrypted data:" + B );

}


Public static String toHexString (byte B []) {
StringBuffer hexString = new StringBuffer ();
For (int I = 0; I <B. length; I ++ ){
String plainText = Integer. toHexString (0xff & B [I]);
If (plainText. length () <2)
PlainText = "0" + plainText;
HexString. append (plainText );
}

Return hexString. toString ();
}

}

 

. NET version

Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Data. SqlClient;
Using System. Security. Cryptography;
Using System. IO;
Using System. Text;
Public class TestDes {
// Cookies encryption key
Public static string DES_Key = "12345678 ";
 
# Region DESEnCode DES encryption
Public static string DESEnCode (string pToEncrypt, string sKey)
{
PToEncrypt = HttpContext. Current. Server. UrlEncode (pToEncrypt );
DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
Byte [] inputByteArray = Encoding. GetEncoding ("UTF-8"). GetBytes (pToEncrypt );


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

Cs. Write (inputByteArray, 0, inputByteArray. Length );
Cs. FlushFinalBlock ();

StringBuilder ret = new StringBuilder ();
Foreach (byte B in ms. ToArray ())
{
Ret. AppendFormat ("{0: X2}", B );
}
Ret. ToString ();
Return ret. ToString ();
}
# Endregion
 
# Region DESDeCode DES decryption
Public static string DESDeCode (string pToDecrypt, string sKey)
{
// HttpContext. Current. Response. Write (pToDecrypt + "<br>" + sKey );
// HttpContext. Current. Response. End ();
DESCryptoServiceProvider des = new DESCryptoServiceProvider ();

Byte [] inputByteArray = new byte [pToDecrypt. Length/2];
For (int x = 0; x <pToDecrypt. Length/2; x ++)
{
Int I = (Convert. ToInt32 (pToDecrypt. Substring (x * 2, 2), 16 ));
InputByteArray [x] = (byte) I;
}

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 );
Cs. Write (inputByteArray, 0, inputByteArray. Length );
Cs. FlushFinalBlock ();

StringBuilder ret = new StringBuilder ();

Return HttpContext. Current. Server. UrlDecode (System. Text. Encoding. Default. GetString (ms. ToArray ()));
}
# Endregion

Public TestDes ()
{
//
// TODO: add the constructor logic here
//
}
}

 

A project was created a few days ago, which requires DES encryption between the two systems. One system is developed for JAVA, and the other one is developed for. Net.

I found a lot of writing methods on the Internet, but the encrypted data cannot be matched between the two systems,

I can use it after making a small modification and have tested it.

JAVA version

Import javax. crypto. Cipher;
Import javax. crypto. SecretKey;
Import javax. crypto. SecretKeyFactory;
Import javax. crypto. spec. DESKeySpec;
Import javax. crypto. spec. IvParameterSpec;


Public class Des {
Private byte [] cipher ey;


// Decrypt data
Public static String decrypt (String message, String key) throws Exception {

Byte [] bytesrc = convertHexString (message );
Cipher cipher = Cipher. getInstance ("DES/CBC/PKCS5Padding ");
DESKeySpec desKeySpec = new DESKeySpec (key. getBytes ("UTF-8 "));
SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES ");
SecretKey secretKey = keyFactory. generateSecret (desKeySpec );
IvParameterSpec iv = new IvParameterSpec (key. getBytes ("UTF-8 "));

Cipher. init (Cipher. DECRYPT_MODE, secretKey, iv );

Byte [] retByte = cipher. doFinal (bytesrc );
Return new String (retByte );
}

Public static byte [] encrypt (String message, String key)
Throws Exception {
Cipher cipher = Cipher. getInstance ("DES/CBC/PKCS5Padding ");

DESKeySpec desKeySpec = new DESKeySpec (key. getBytes ("UTF-8 "));

SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES ");
SecretKey secretKey = keyFactory. generateSecret (desKeySpec );
IvParameterSpec iv = new IvParameterSpec (key. getBytes ("UTF-8 "));
Cipher. init (Cipher. ENCRYPT_MODE, secretKey, iv );

Return cipher. doFinal (message. getBytes ("UTF-8 "));
}

Public static byte [] convertHexString (String ss)
{
Byte digest [] = new byte [ss. length ()/2];
For (int I = 0; I <digest. length; I ++)
{
String byteString = ss. substring (2 * I, 2 * I + 2 );
Int byteValue = Integer. parseInt (byteString, 16 );
Digest [I] = (byte) byteValue;
}

Return digest;
}


Public static void main (String [] args) throws Exception {
String key = "12345678 ";
String value = "test1234 ";
String jiami = java.net. URLEncoder. encode (value, "UTF-8"). toLowerCase ();

System. out. println ("encrypted data:" + jiami );
String a = toHexString (encrypt (jiami, key). toUpperCase ();


System. out. println ("encrypted data:" + );
String B = java.net. URLDecoder. decode (decrypt (a, key), "UTF-8 ");
System. out. println ("decrypted data:" + B );

}


Public static String toHexString (byte B []) {
StringBuffer hexString = new StringBuffer ();
For (int I = 0; I <B. length; I ++ ){
String plainText = Integer. toHexString (0xff & B [I]);
If (plainText. length () <2)
PlainText = "0" + plainText;
HexString. append (plainText );
}

Return hexString. toString ();
}

}

 

. NET version

Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Data. SqlClient;
Using System. Security. Cryptography;
Using System. IO;
Using System. Text;
Public class TestDes {
// Cookies encryption key
Public static string DES_Key = "12345678 ";
 
# Region DESEnCode DES encryption
Public static string DESEnCode (string pToEncrypt, string sKey)
{
PToEncrypt = HttpContext. Current. Server. UrlEncode (pToEncrypt );
DESCryptoServiceProvider des = new DESCryptoServiceProvider ();
Byte [] inputByteArray = Encoding. GetEncoding ("UTF-8"). GetBytes (pToEncrypt );


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

Cs. Write (inputByteArray, 0, inputByteArray. Length );
Cs. FlushFinalBlock ();

StringBuilder ret = new StringBuilder ();
Foreach (byte B in ms. ToArray ())
{
Ret. AppendFormat ("{0: X2}", B );
}
Ret. ToString ();
Return ret. ToString ();
}
# Endregion
 
# Region DESDeCode DES decryption
Public static string DESDeCode (string pToDecrypt, string sKey)
{
// HttpContext. Current. Response. Write (pToDecrypt + "<br>" + sKey );
// HttpContext. Current. Response. End ();
DESCryptoServiceProvider des = new DESCryptoServiceProvider ();

Byte [] inputByteArray = new byte [pToDecrypt. Length/2];
For (int x = 0; x <pToDecrypt. Length/2; x ++)
{
Int I = (Convert. ToInt32 (pToDecrypt. Substring (x * 2, 2), 16 ));
InputByteArray [x] = (byte) I;
}

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 );
Cs. Write (inputByteArray, 0, inputByteArray. Length );
Cs. FlushFinalBlock ();

StringBuilder ret = new StringBuilder ();

Return HttpContext. Current. Server. UrlDecode (System. Text. Encoding. Default. GetString (ms. ToArray ()));
}
# Endregion

Public TestDes ()
{
//
// TODO: add the constructor logic here
//
}
}

 

Related Article

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.