3Des encryption and decryption C # --- & gt; Java,

Source: Internet
Author: User
Tags pkcs7

3Des encryption and decryption C # ---> Java,

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.

C #

/// <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 the // MemoryStream that holds the // 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 useless) </param> /// <param name = "str"> plaintext byte array </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 the // MemoryStream that holds the // 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 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 abcdefghijklmnopqrstuvwx Base64 encoded byte [] key = Convert. fromBase64String ("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4"); byte [] iv = new byte [] {1, 2, 3, 4, 5, 6, 7, 8 }; // when the mode is ECB, IV 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 ();}}

Java

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 ("bytes"); byte [] keyiv = {1, 2, 3, 4, 5, 6, 7, 8}; byte [] data = "China 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 encrypted, do not IV * @ param key * @ param data plaintext * @ return Base64 encoded ciphertext * @ throws Exception */public static byte [] des3EncodeECB (byte [] key, byte [] data) throws Exception {Key secret ey = null; DESedeKeySpec spec = new DESedeKeySpec (key); SecretKeyFactory keyfactory = SecretKeyFactory. getInstance ("desede"); cipher 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, do not IV * @ param key * @ param data Base64 encoded ciphertext * @ return plaintext * @ throws Exception */public static byte [] ees3DecodeECB (byte [] key, byte [] data) throws Exception {Key secret ey = null; DESedeKeySpec spec = new DESedeKeySpec (key); SecretKeyFactory keyfactory = SecretKeyFactory. getInstance ("desede"); cipher 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 secret ey = null; DESedeKeySpec spec = new DESedeKeySpec (key); SecretKeyFactory keyfactory = SecretKeyFactory. getInstance ("desede"); cipher 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 IV * @ param data Base64 encoded ciphertext * @ return plaintext * @ throws Exception */public static byte [] des3DecodeCBC (byte [] key, byte [] keyiv, byte [] data) throws Exception {Key secret ey = null; DESedeKeySpec spec = new DESedeKeySpec (key); SecretKeyFactory keyfactory = SecretKeyFactory. getInstance ("desede"); cipher 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 ;}}

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.