JAVA and C # 3DES encryption and decryption __java

Source: Internet
Author: User
Tags flush pkcs7 java web knowledge base

A recent project. NET to invoke Java Web SERVICE, the data using 3DES encryption, involving two languages 3DES consistency problem,
Share the following,
The key here is BASE64 encoded and distributed, because the byte range of Java is 128 to 127,c# is 0-255
The core is OK Mode and Padding, about the meaning of these two can search 3DES algorithm related article one is C # using CBC MODE,PKCS7 Padding,java using CBC mode,pkcs5padding Padding , and the other is C # using ECB MODE,PKCS7 Padding,java to use the ECB mode,pkcs5padding Padding,

The Java ECB model does not require IV

When encrypting a character, both sides are using UTF-8 encoding

The following is the C # code

<summary>///DES3 Encryption decryption///</summary> public class Des3 {#region CBC mode * *///&LT;SUMMARY&GT 
    ; DES3 CBC mode encryption///</summary>///<param name= "key" > Key </param>///<param "IV" & gt;iv</param>///<param name= "Data" > plaintext byte array </param>///<returns> ciphertext byte array </return  
        s> public static byte[] DES3ENCODECBC (byte[] key, byte[] IV, byte[] data {//replicated in MSDN try 
            {//Create a MemoryStream. 
            MemoryStream mstream = new MemoryStream (); 
            TripleDESCryptoServiceProvider TDSP = new TripleDESCryptoServiceProvider (); TDSP.             Mode = CIPHERMODE.CBC; The default value is 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 a 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; The 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 byteArray </param>///<returns> plaintext byte array </returns> public static byte[] DES3DECODECBC (byte[) key, by  
            Te[] 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; The 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" &GT;IV (when the mode is ECB, IV useless) </param>///< param name= "str" > PlainText byte array </param>///<returns> ciphertext byte array </returns> public static byte[] De 
            S3ENCODEECB (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 a 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" &GT;IV (when the mode is ECB, IV useless) </param>///<param name= "str" > Cipher byte array </p  aram>///<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; The catch (Cryptographicexception e) {Console.WriteLine ("A Cryptographic error occurred: 
            {0} ", e.message); 
        return null; }} #endregion///<summary>///class <a href= "Http://lib.csdn.net/base/softwaretest" class= ' Repl Ace_word ' title= ' software testing Knowledge base "target= ' _blank ' style= ' color: #df3434; Font-weight:bold; ' > Test </a>///</summary> public static void Test () {SyStem. 
        text.encoding UTF8 = System.Text.Encoding.UTF8;  The key is a abcdefghijklmnopqrstuvwx Base64 encoding byte[] key = Convert.frombase64string ("Ywjjzgvmz2hpamtsbw5vchfyc3r1dnd4" 
        );      Byte[] IV = new byte[] {1, 2, 3, 4, 5, 6, 7, 8}; When the model 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 ();   } 
}

Followed by Java code

Package com.mes.util;
Import Java.security.Key;
Import Java.util.HashMap;

Import Java.util.Map;
Import Javax.crypto.Cipher;
Import Javax.crypto.SecretKeyFactory;
Import Javax.crypto.spec.DESedeKeySpec;

Import Javax.crypto.spec.IvParameterSpec;

Import Sun.misc.BASE64Decoder; @SuppressWarnings ("restriction") public class THREEDESCBC {/** * * @Description ECB encryption, do not IV * @param KE Y key * @param data plaintext * @return BASE64 encoded ciphertext * @throws Exception * @author Shindo * @date 2016 1 January 15 pm 4:42:56 */public static byte[] DES3ENCODEECB (byte[] key, byte[] data) throws Exception {Key des
        key = null;
        Desedekeyspec spec = new Desedekeyspec (key);
        Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede");
        Deskey = Keyfactory.generatesecret (spec);
        Cipher Cipher = cipher.getinstance ("Desede" + "/ecb/pkcs5padding");
        Cipher.init (Cipher.encrypt_mode, Deskey); byte[] BOut = cipher.dofinal(data);
    return bOut;
     /** * * @Description ECB decryption, do not IV * @param key key * @param data Base64 encoded ciphertext * @return plaintext * @throws Exception * @author Shindo * @date November 15, 2016 afternoon 5:01:23/public static byte[] Ees3deco
        DEECB (byte[] key, byte[] data throws Exception {key deskey = null;
        Desedekeyspec spec = new Desedekeyspec (key);
        Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede");
        Deskey = Keyfactory.generatesecret (spec);
        Cipher Cipher = cipher.getinstance ("Desede" + "/ecb/pkcs5padding");
        Cipher.init (Cipher.decrypt_mode, Deskey);
        byte[] BOut = cipher.dofinal (data);
    return bOut; /** * * @Description CBC Encryption * @param key key * @param keyiv IV * @param data plaintext * @retu RN BASE64 Encoded CIPHERTEXT * @throws Exception * @author Shindo * @date November 15, 2016 PM 5:26:46/Public Stat IC byte[] DES3ENCODECBC (byTe[] key, byte[] Keyiv, byte[] data throws Exception {key deskey = null;
        Desedekeyspec spec = new Desedekeyspec (key);
        Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede");
        Deskey = Keyfactory.generatesecret (spec);
        Cipher Cipher = cipher.getinstance ("Desede" + "/cbc/pkcs5padding");
        Ivparameterspec ips = new Ivparameterspec (KEYIV);
        Cipher.init (Cipher.encrypt_mode, Deskey, IPs);
        byte[] BOut = cipher.dofinal (data);
    return bOut;
     /** * * @Description CBC decryption * @param key key * @param keyiv IV * @param data Base64 encoded ciphertext * @return PlainText * @throws Exception * @author Shindo * @date November 16, 2016 morning 10:13:49/public STA
        Tic byte[] DES3DECODECBC (byte[] key, byte[] Keyiv, byte[] data throws Exception {key deskey = null;
        Desedekeyspec spec = new Desedekeyspec (key); Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("desEde ");
        Deskey = Keyfactory.generatesecret (spec);
        Cipher Cipher = cipher.getinstance ("Desede" + "/cbc/pkcs5padding");
        Ivparameterspec ips = new Ivparameterspec (KEYIV);
        Cipher.init (Cipher.decrypt_mode, Deskey, IPs);
        byte[] BOut = cipher.dofinal (data);
    return bOut; /** * * @Description PU FA Channel entrance 3DES decryption method * @param paras Encryption parameter * @param key 3DES key * @return decryption Clear text * @author Shindo * @throws Exception * @date November 22, 2016 a.m. 9:34:07 * * Public map<string, S Tring> PARASDECRYPTCBC (map<string, string> paras, String key) throws Exception {map<string, String&gt ;
        Map = new hashmap<string, string> ();
            try {byte[] Pf_3des_key = new Base64decoder (). Decodebuffer (key); 

            Byte[] Keyiv = {1, 2, 3, 4, 5, 6, 7, 8};//3DES Decrypt IV value String telephone = paras.get ("telephone");//Pufa New interface phone not encrypted byte[] Card = new Base64decoder (). DecodeBuffer (Controllerutils.urldecode) (Paras.get ("Cardno"));

            byte[] cert = new Base64decoder (). Decodebuffer (Controllerutils.urldecode ("Paras.get")); String Cardno = new String (DES3DECODECBC (Pf_3des_key, Keyiv, card), "UTF-8");/card number string certno = new String (
            DES3DECODECBC (Pf_3des_key, Keyiv, cert), "UTF-8");/certificate number Map.put ("Telephone", telephone);
            Map.put ("Cardno", Cardno);
        Map.put ("Certno", Certno);
        catch (Exception e) {throw new Exception ("Pu FA-owned channel entry parameters 3DES CBC decryption failed!");
    } return map; /** * * @Description Debugging Method * @param args * @throws Exception * @author Shindo * @dat E November 22, 2016 a.m. 9:28:22 */public static void main (string[] args) throws Exception {byte[] key = new BAS
        E64decoder (). Decodebuffer ("Ywjjzgvmz2hpamtsbw5vchfyc3r1dnd4");
Byte[] Keyiv = {1, 2, 3, 4, 5, 6, 7, 8}; byte[] data = "420106198203279258 ". 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")); */String STR7 = "uhrew7thp2tal2njpsjhf2mdfmp7bz1w";
        byte[] Str8 = new Base64decoder (). Decodebuffer (STR7);
        byte[] Str9 = DES3DECODECBC (key, Keyiv, STR8);

    System.out.println (New String (STR9, "UTF-8")); }

}
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.