A Java des Plus decryption class converted to C #

Source: Internet
Author: User
Tags base64 decrypt key string

Original: A Java des plus decryption class converted to C #

A Java DES encryption decryption code is as follows:

Package Com.visionsky.util;import Java.security.*;//import Java.util.regex.pattern;//import java.util.Hashtable; Import Javax.crypto.*;import javax.crypto.spec.*;import sun.misc.*;/** * des encryption Decrypt */public class Desplus {private Stati C String strdefaultkey = "PLFP"; Default key private static final byte[] IV = {0x12, 0x34, 0x56, 0x78, (Byte) 0x90, (Byte) 0xAB, (Byte) 0xCD, (byte) 0xef};// Des vector private static base64encoder enc = new Base64encoder ();//Convert byte[] to string private static Base64decoder Dec = New Base64decoder ();            Convert string to byte[]/** * Encrypted byte array * * @param ARRB * byte array to be encrypted * @param key * Key * @return Encrypted byte array * @throws Exception */public static byte[] Encrypt (byte[] ARRB, String key) throws        Exception {Deskeyspec Deskeyspec = new Deskeyspec (Key.getbytes ());        Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");      Secretkey Secretkey = Keyfactory.generatesecret (Deskeyspec);  Ivparameterspec IVP = new Ivparameterspec (DESPLUS.IV);        Cipher Encryptcipher = cipher.getinstance ("des/cbc/pkcs5padding");        Encryptcipher.init (Cipher.encrypt_mode, Secretkey, IVP);    Return encryptcipher.dofinal (ARRB); }/** * Encrypt String * * @param XML * String to be encrypted * @param key * key * @return Encryption After the string * @throws Exception */public static string encrypt (string XML, String key) throws Exception {//r     Eturn DESPlus.enc.encode (Encrypt (xml.getbytes (), key); return new String (Encrypt (xml.getbytes (), key)); /** * Use default public key to encrypt string * @param XML string to encrypt * @return encrypted String * @throws Exception * *    String Encrypt (string xml) throws Exception {return encrypt (XML, Strdefaultkey);  }/** * Decrypt byte array * * @param ARRB * required to decrypt byte array * @param key * key * @return Decrypted byte array * @throws Exception */public static byte[] DecrypT (byte[] ARRB, String key) throws Exception {Deskeyspec Deskeyspec = new Deskeyspec (Key.getbytes ());        Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");        Secretkey Secretkey = Keyfactory.generatesecret (Deskeyspec);        Ivparameterspec IVP = new Ivparameterspec (DESPLUS.IV);        Cipher Decryptcipher = cipher.getinstance ("des/cbc/pkcs5padding");        Decryptcipher.init (Cipher.decrypt_mode, Secretkey, IVP);    Return decryptcipher.dofinal (ARRB); /** * Decrypt String * * @param XML * The string to be decrypted * @param key * key * @return decrypted After the string * @throws Exception */public static string decrypt (string XML, String key) throws Exception {RET    Urn New String (Decrypt (DESPlus.dec.decodeBuffer (XML), key)); /** * Decrypts the string with the default public key * @param the string that the XML needs to decrypt * @return decrypted String * @throws Exception * * String decrypt (String xml) throws Exception {return decrypt (XML,Strdefaultkey);  }/** * Generates a key from the specified string, the required byte array length for the key is 8 bits less than 8 bits when the back is 0, beyond the 8 bits to take the first 8 bits * * @param arrbtmp * The byte array that makes up the string *  @return generated key * @throws java.lang.Exception */private key GetKey (byte[] arrbtmp) throws Exception {//        Create an empty 8-byte array (default is 0) byte[] arrb = new Byte[8]; Converts the original byte array to 8-bit for (int i = 0; i < arrbtmp.length && i < arrb.length; i++) {arrb[i] = AR        Rbtmp[i];        }//Generate key Key key = new Javax.crypto.spec.SecretKeySpec (ARRB, "DES");    Return key;    }/** * Gets the default key * @return */public static String Getdeskey () {return desplus.strdefaultkey;            } public static void Main (string[] args) {try {//test key String key = "BOC_PLFP"; 004 Trade Case String XML = "<?xml version=\" 1.0\ "encoding=\" utf-8\ "? ><root>

The result of the above operation is:

Key: BOC_PLFP
String before encryption: <?xml version= "1.0" encoding= "UTF-8"?><root>String length before encryption: 262
Encrypted string: BE5N44GJYFO3SDUS6/OHVG4I4L725S2VWCKBRXYOAD/EANYUADKXENNGVXJMJ3AJJZNDNTV364RH
Yw2bf33lmeabmu43hfs8dcxx7+qrcijp3mrk7ujdinhu4t4ohmeqetfzqu5oh2xy1sbbppdgegmf
/ogurvatblzl/ylkfc6c9bnnsd0iwl0ks7mi73+v76p+afdpgxqc7u4vkq8cd6+hgherbhbji729
Jpjkm5l2yaaw4q06oi4ymoeasdjyf7aa1x/fwqclszimsdb0okgoiuj857l94bm1zyl2rtwdxa9o
0beil4cbevksc3u3pydai0+mzbte0svkyp0sxtke7ifrwimg
String length after encryption: 360
Decrypted string: <?xml version= "1.0" encoding= "UTF-8"?><root>Decrypted string length: 262


Reference to http://www.lijingquan.net/des-c-php-java.html, modify the inside of the Des Vector IV, character encoding UTF8 default, etc., and finally
Rewrite the C # code as follows:

Using system;using system.collections.generic;using system.linq;using system.text;using System.security.cryptography;public class des{Private Const string Defaultkey = "BOC_PLFP";//default key private static B Yte[] IV = {0x12, 0x34, 0x56, 0x78, (Byte) 0x90, (Byte) 0xAB, (Byte) 0xCD, (byte) 0xef};//des vector///<s Ummary>//DES encryption//</summary>//<param name= "Ptoencrypt" > String to encrypt. </param>//<param name= "SKey" > key, and must be 8-bit. Default public key Encryption string defaultkey</param>//<returns> The encrypted string returned in BASE64 format. </returns> public static string Encrypt (String ptoencrypt, String sKey = Defaultkey) {using (Descrypto ServiceProvider des = new DESCryptoServiceProvider ()) {byte[] Inputbytearray = Encoding.Default.GetByte            S (ptoencrypt); Des.            Key = ASCIIEncoding.ASCII.GetBytes (SKey);  DES.IV = IV;            ASCIIEncoding.ASCII.GetBytes (SKey); System.IO.MemoryStream ms = new System.IO.MemoryStreAM (); using (CryptoStream cs = new CryptoStream (MS, Des. CreateEncryptor (), cryptostreammode.write)) {cs.                Write (Inputbytearray, 0, inputbytearray.length); Cs.                FlushFinalBlock (); Cs.            Close (); } string str = Convert.tobase64string (MS.            ToArray ()); Ms.            Close ();        return str; }}///<summary>//des decryption//</summary>//<param name= "Ptodecrypt" > to Decrypt With base64</param>//<param name= "SKey" > key, and must be 8 bits. The default public key decryption string defaultkey</param>//<returns> decrypted string. </returns> public static string Decrypt (String ptodecrypt, String sKey = Defaultkey) {byte[] Inputbyte        Array = convert.frombase64string (Ptodecrypt); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider ()) {des.            Key = ASCIIEncoding.ASCII.GetBytes (SKey); DES.IV = IV; ASCIIEncoding.ASCII.GetBytes (SKey);            System.IO.MemoryStream ms = new System.IO.MemoryStream (); using (CryptoStream cs = new CryptoStream (MS, Des. CreateDecryptor (), cryptostreammode.write)) {cs.                Write (Inputbytearray, 0, inputbytearray.length); Cs.                FlushFinalBlock (); Cs.            Close (); } string str = Encoding.Default.GetString (MS.            ToArray ()); Ms.            Close ();        return str; }    }}
Tested, the results of encryption and decryption are the same as in Java.


A Java des Plus decryption class converted to C #

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.