Android: JAVA and C # 3DES encryption and decryption)

Source: Internet
Author: User
Tags pkcs7
Android: JAVA and C # 3DES encryption and decryption

The latest project. net calls JAVA WEB
SERVICE, data is encrypted with 3DES, which involves the consistency of 3DES in two languages,
Share the following information,
The keys are Base64 encoded and distributed, because the Byte range of Java is-128 to 127, and the Byte range of c # is 0-255.
The core is to determine the Mode and Padding. You can search for articles related to the 3DES algorithm.
One is C # using CBC
Mode, PKCS7 Padding, Java adopts CBC Mode, PKCS5Padding,
The other is C # using ECB
Mode, PKCS7 Padding, Java uses ECB Mode, PKCS5Padding
Padding,
Java ECB mode does not require IV
When encrypting characters, both sides adopt UTF-8 Encoding

Below is the C # code

 

/// <Summary>
/// DES3 encryption and decryption
/// </Summary>
Public class Des3
{
# Region CBC mode **

/// <Summary>
/// DES3 CBC mode Encryption
/// </Summary>
/// <Param name = "key"> key </param>
/// <Param name = "iv"> IV </param>
/// <Param name = "data"> plaintext byte array </param>
/// <Returns> ciphertext byte array </returns>
Public static byte [] Des3EncodeCBC (byte [] key, byte [] iv, byte [] data)
{
// Copy to MSDN

Try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream ();

TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider ();
Tdsp. Mode = CipherMode. CBC; // Default Value
Tdsp. Padding = PaddingMode. PKCS7; // Default Value

// Create a CryptoStream using the MemoryStream
// And the passed key and initialization vector (IV ).
CryptoStream cStream = new CryptoStream (mStream,
Tdsp. CreateEncryptor (key, iv ),
CryptoStreamMode. Write );

// Write the byte array to the crypto stream and flush it.
CStream. Write (data, 0, data. Length );
CStream. FlushFinalBlock ();

// Get an array of bytes from
// MemoryStream that holds
// Encrypted data.
Byte [] ret = mStream. ToArray ();

// Close the streams.
CStream. Close ();
MStream. Close ();

// Return the encrypted buffer.
Return ret;
}
Catch (CryptographicException e)
{
Console. WriteLine ("A Cryptographic error occurred: {0}", e. Message );
Return null;
}
}

/// <Summary>
/// DES3 CBC mode decryption
/// </Summary>
/// <Param name = "key"> key </param>
/// <Param name = "iv"> IV </param>
/// <Param name = "data"> ciphertext byte array </param>
/// <Returns> plaintext byte array </returns>
Public static byte [] Des3DecodeCBC (byte [] key, byte [] iv, byte [] data)
{
Try
{
// Create a new MemoryStream using the passed
// Array of encrypted data.
MemoryStream msDecrypt = new MemoryStream (data );

TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider ();
Tdsp. Mode = CipherMode. CBC;
Tdsp. Padding = PaddingMode. PKCS7;

// Create a CryptoStream using the MemoryStream
// And the passed key and initialization vector (IV ).
CryptoStream csDecrypt = new CryptoStream (msDecrypt,
Tdsp. CreateDecryptor (key, iv ),
CryptoStreamMode. Read );

// Create buffer to hold the decrypted data.
Byte [] fromEncrypt = new byte [data. Length];

// Read the decrypted data out of the crypto stream
// And place it into the temporary buffer.
CsDecrypt. Read (fromEncrypt, 0, fromEncrypt. Length );

// Convert the buffer into a string and return it.
Return fromEncrypt;
}
Catch (CryptographicException e)
{
Console. WriteLine ("A Cryptographic error occurred: {0}", e. Message );
Return null;
}
}

# Endregion

# Region ECB Mode

/// <Summary>
/// DES3 ECB mode Encryption
/// </Summary>
/// <Param name = "key"> key </param>
/// <Param name = "iv"> IV (when the mode is ECB, IV is useless) </param>
/// <Param name = "str"> byte array in plaintext </param>
/// <Returns> ciphertext byte array </returns>
Public static byte [] Des3EncodeECB (byte [] key, byte [] iv, byte [] data)
{
Try
{
// Create a MemoryStream.
MemoryStream mStream = new MemoryStream ();

TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider ();
Tdsp. Mode = CipherMode. ECB;
Tdsp. Padding = PaddingMode. PKCS7;
// Create a CryptoStream using the MemoryStream
// And the passed key and initialization vector (IV ).
CryptoStream cStream = new CryptoStream (mStream,
Tdsp. CreateEncryptor (key, iv ),
CryptoStreamMode. Write );

// Write the byte array to the crypto stream and flush it.
CStream. Write (data, 0, data. Length );
CStream. FlushFinalBlock ();

// Get an array of bytes from
// MemoryStream that holds
// Encrypted data.
Byte [] ret = mStream. ToArray ();

// Close the streams.
CStream. Close ();
MStream. Close ();

// Return the encrypted buffer.
Return ret;
}
Catch (CryptographicException e)
{
Console. WriteLine ("A Cryptographic error occurred: {0}", e. Message );
Return null;
}

}

/// <Summary>
/// DES3 ECB mode decryption
/// </Summary>
/// <Param name = "key"> key </param>
/// <Param name = "iv"> IV (when the mode is ECB, IV is useless) </param>
/// <Param name = "str"> ciphertext byte array </param>
/// <Returns> plaintext byte array </returns>
Public static byte [] Des3DecodeECB (byte [] key, byte [] iv, byte [] data)
{
Try
{
// Create a new MemoryStream using the passed
// Array of encrypted data.
MemoryStream msDecrypt = new MemoryStream (data );

TripleDESCryptoServiceProvider tdsp = new TripleDESCryptoServiceProvider ();
Tdsp. Mode = CipherMode. ECB;
Tdsp. Padding = PaddingMode. PKCS7;

// Create a CryptoStream using the MemoryStream
// And the passed key and initialization vector (IV ).
CryptoStream csDecrypt = new CryptoStream (msDecrypt,
Tdsp. CreateDecryptor (key, iv ),
CryptoStreamMode. Read );

// Create buffer to hold the decrypted data.
Byte [] fromEncrypt = new byte [data. Length];

// Read the decrypted data out of the crypto stream
// And place it into the temporary buffer.
CsDecrypt. Read (fromEncrypt, 0, fromEncrypt. Length );

// Convert the buffer into a string and return it.
Return fromEncrypt;
}
Catch (CryptographicException e)
{
Console. WriteLine ("A Cryptographic error occurred: {0}", e. Message );
Return null;
}
}

# Endregion

/// <Summary>
/// Class test
/// </Summary>
Public static void Test ()
{
System. Text. Encoding utf8 = System. Text. Encoding. UTF8;

// The key is the Base64 encoding of abcdefghijklmnopqrstuvwx.
Byte [] key = Convert. FromBase64String ("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4 ");
Byte [] iv = new byte [] {1, 2, 3, 4, 5, 6, 7, 8}; // when the mode is ECB, IV is useless
Byte [] data = utf8.GetBytes ("China ABCabc123 ");

System. Console. WriteLine ("ECB mode :");
Byte [] str1 = Des3.Des3EncodeECB (key, iv, data );
Byte [] str2 = Des3.Des3DecodeECB (key, iv, str1 );
System. Console. WriteLine (Convert. ToBase64String (str1 ));
System. Console. WriteLine (System. Text. Encoding. UTF8.GetString (str2 ));

System. Console. WriteLine ();

System. Console. WriteLine ("CBC mode :");
Byte [] str3 = Des3.Des3EncodeCBC (key, iv, data );
Byte [] str4 = Des3.Des3DecodeCBC (key, iv, str3 );
System. Console. WriteLine (Convert. ToBase64String (str3 ));
System. Console. WriteLine (utf8.GetString (str4 ));

System. Console. WriteLine ();

}

}

 

 

Followed by the Java code

 

Import java. security. Key;

Import javax. crypto. Cipher;
Import javax. crypto. SecretKeyFactory;
Import javax. crypto. spec. DESedeKeySpec;
Import javax. crypto. spec. IvParameterSpec;

Import sun. misc. BASE64Decoder;
Import sun. misc. BASE64Encoder;

Public class Des3 {
Public static void main (String [] args) throws Exception {

Byte [] key = new BASE64Decoder (). decodeBuffer ("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4 ");
Byte [] keyiv = {1, 2, 3, 4, 5, 6, 7, 8 };

Byte [] data = "ABCabc123". getBytes ("UTF-8 ");

System. out. println ("ECB encryption and decryption ");
Byte [] str3 = des3EncodeECB (key, data );
Byte [] str4 = ees3DecodeECB (key, str3 );
System. out. println (new BASE64Encoder (). encode (str3 ));
System. out. println (new String (str4, "UTF-8 "));

System. out. println ();

System. out. println ("CBC encryption and decryption ");
Byte [] str5 = des3EncodeCBC (key, keyiv, data );
Byte [] str6 = des3DecodeCBC (key, keyiv, str5 );
System. out. println (new BASE64Encoder (). encode (str5 ));
System. out. println (new String (str6, "UTF-8 "));

}

/**
* ECB encryption, not IV
* @ Param key
* @ Param data plaintext
* @ Return Base64 encoded ciphertext
* @ Throws Exception
*/
Public static byte [] des3EncodeECB (byte [] key, byte [] data)
Throws Exception {

Key Required ey = null;
DESedeKeySpec spec = new DESedeKeySpec (key );
SecretKeyFactory keyfactory = SecretKeyFactory. getInstance ("desede ");
Secret ey = keyfactory. generateSecret (spec );

Cipher cipher = Cipher. getInstance ("desede" + "/ECB/PKCS5Padding ");

Cipher. init (Cipher. ENCRYPT_MODE, cipher ey );
Byte [] bOut = cipher. doFinal (data );

Return bOut;
}

/**
* ECB decryption, not IV
* @ Param key
* @ Param data Base64 encoded ciphertext
* @ Return plaintext
* @ Throws Exception
*/
Public static byte [] ees3DecodeECB (byte [] key, byte [] data)
Throws Exception {

Key Required ey = null;
DESedeKeySpec spec = new DESedeKeySpec (key );
SecretKeyFactory keyfactory = SecretKeyFactory. getInstance ("desede ");
Secret ey = keyfactory. generateSecret (spec );

Cipher cipher = Cipher. getInstance ("desede" + "/ECB/PKCS5Padding ");

Cipher. init (Cipher. DECRYPT_MODE, cipher ey );

Byte [] bOut = cipher. doFinal (data );

Return bOut;

}

/**
* CBC encryption
* @ Param key
* @ Param keyiv
* @ Param data plaintext
* @ Return Base64 encoded ciphertext
* @ Throws Exception
*/
Public static byte [] des3EncodeCBC (byte [] key, byte [] keyiv, byte [] data)
Throws Exception {

Key Required ey = null;
DESedeKeySpec spec = new DESedeKeySpec (key );
SecretKeyFactory keyfactory = SecretKeyFactory. getInstance ("desede ");
Secret ey = keyfactory. generateSecret (spec );

Cipher cipher = Cipher. getInstance ("desede" + "/CBC/PKCS5Padding ");
IvParameterSpec ips = new IvParameterSpec (keyiv );
Cipher. init (Cipher. ENCRYPT_MODE, cipher ey, ips );
Byte [] bOut = cipher. doFinal (data );

Return bOut;
}

/**
* CBC decryption
* @ Param key
* @ Param keyiv
* @ Param data Base64 encoded ciphertext
* @ Return plaintext
* @ Throws Exception
*/
Public static byte [] des3DecodeCBC (byte [] key, byte [] keyiv, byte [] data)
Throws Exception {

Key Required ey = null;
DESedeKeySpec spec = new DESedeKeySpec (key );
SecretKeyFactory keyfactory = SecretKeyFactory. getInstance ("desede ");
Secret ey = keyfactory. generateSecret (spec );

Cipher cipher = Cipher. getInstance ("desede" + "/CBC/PKCS5Padding ");
IvParameterSpec ips = new IvParameterSpec (keyiv );

Cipher. init (Cipher. DECRYPT_MODE, cipher ey, ips );

Byte [] bOut = cipher. doFinal (data );

Return bOut;

}

}

 

The running result is as follows:

ECB mode:
RmWB4 + r9Ug93WI0KAEuMig =
ABCabc123, China

CBC mode:
4aabWF8UFour/vNfnzJrjw =
ABCabc123, China

 

In addition, to use 3DES in android, you can consider replacing BASE64Encoder with Base64.

The Code is as follows:

 

Public static void main (String [] args) throws Exception {

Byte [] key = Base64.decode ("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4". getBytes (), Base64.DEFAULT );
Byte [] keyiv = {1, 2, 3, 4, 5, 6, 7, 8 };

Byte [] data = "ABCabc123". getBytes ("UTF-8 ");

System. out. println ("ECB encryption and decryption ");
Byte [] str3 = des3EncodeECB (key, data );
Byte [] str4 = ees3DecodeECB (key, str3 );
System. out. println (new String (Base64.encode (str3, Base64.DEFAULT), "UTF-8 "));
System. out. println (new String (str4, "UTF-8 "));

System. out. println ();

System. out. println ("CBC encryption and decryption ");
Byte [] str5 = des3EncodeCBC (key, keyiv, data );
Byte [] str6 = des3DecodeCBC (key, keyiv, str5 );
System. out. println (new String (Base64.encode (str5, Base64.DEFAULT), "UTF-8 "));
System. out. println (new String (str6, "UTF-8 "));
}

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.