Java des plus decryption

Source: Internet
Author: User
Tags decrypt

Package Com.des.test;import Java.security.nosuchalgorithmexception;import Java.security.securerandom;import Javax.crypto.cipher;import Javax.crypto.keygenerator;import Javax.crypto.secretkey;import Javax.crypto.secretkeyfactory;import Javax.crypto.spec.deskeyspec;import Javax.crypto.spec.IvParameterSpec; public class des {/** * * * * @return des algorithm key */public static byte[] GenerateKey () {try {//des algorithm requires a trustworthy random number source Secureran Dom sr = new SecureRandom ();//generates a DES algorithm Keygenerator object keygenerator kg = keygenerator.getinstance ("DES"); Kg.init (SR); /Generate key Secretkey Secretkey = Kg.generatekey ();//Get Key data byte[] key = secretkey.getencoded (); return key;} catch (NoSuchAlgorithmException e) {System.err.println ("des algorithm, error generating key!"); E.printstacktrace ();} return null;} /** * * Encryption Function * * * * * * * * * @param data * * * * * * * @param key * * Key * * * @return go to encrypted data */publi C Static byte[] Encrypt (byte[] data, byte[] key) {try {//des algorithm requires a trustworthy random number source SecureRandom sr = new SecureRandom ();//From the original key number According to the treeStand Deskeyspec object Deskeyspec DKs = new Deskeyspec (key);//Set up a key factory and use it to convert deskeyspec to//a Secretkey object secretkeyfactory Keyfactory = Secretkeyfactory.getinstance ("DES"); Secretkey Secretkey = Keyfactory.generatesecret (DKS);//Using DES in ECB modecipher cipher = cipher.getinstance ("des/ecb/ Pkcs5padding ");//Key Primitive Cipher object Cipher.init (Cipher.encrypt_mode, Secretkey, SR);//Perform cryptographic operation byte encrypteddata[] = Cipher.dofinal (data); return EncryptedData;} catch (Exception e) {System.err.println ("des algorithm, error encrypting data!"); E.printstacktrace ();} return null;} C Static byte[] Decrypt (byte[] data, byte[] key) {try {//des algorithm requires a trustworthy random number source SecureRandom sr = new SecureRandom ();//Byte R Awkeydata[] =/* Get raw key data in some way */;//set a Deskeyspec object from the original key data deskeyspec DKs = new Deskeyspec (key);//Set up a key factory, Then use it to convert the Deskeyspec object to//a Secretkey object secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES"); Secretkey SecreTKey = Keyfactory.generatesecret (DKS);//Using DES in ECB modecipher cipher = cipher.getinstance ("des/ecb/pkcs5padding") ;//Cipher Object Cipher.init (Cipher.decrypt_mode, Secretkey, SR) with a cryptographic key;//formally perform decryption operation byte decrypteddata[] = Cipher.dofinal ( data); return decrypteddata;} catch (Exception e) {System.err.println ("Des algorithm, decryption error. "); E.printstacktrace ();} return null;} /** * * Encryption Function * * * * * * * * * @param data * * * * * * * @param key * * Key * * * @return go to encrypted data */publi C Static byte[] Cbcencrypt (byte[] data, byte[] key, byte[] iv) {try {//from the original key data set Deskeyspec object Deskeyspec DKs = new DESKEYSP EC (key);//Set up a key factory and use it to convert deskeyspec to//a Secretkey object secretkeyfactory keyfactory = Secretkeyfactory.getinstance (" DES "); Secretkey Secretkey = Keyfactory.generatesecret (DKS);//Cipher Object Practice complete cryptographic operation cipher cipher = cipher.getinstance ("des/cbc/ Pkcs5padding ");//If the Nopadding method is used, the data length must be multiples of 8//Cipher Cipher = cipher.getinstance (" des/cbc/nopadding ");// Cipher object Ivparameterspec param = new ivparameterspec with the key primitive (iv); Cipher.init (Cipher.encrypt_mode, Secretkey, param);//Perform cryptographic operation byte encrypteddata[] = cipher.dofinal (data); return EncryptedData;} catch (Exception e) {System.err.println ("des algorithm, error encrypting data!"); E.printstacktrace ();} return null;} C Static byte[] Cbcdecrypt (byte[] data, byte[] key, byte[] iv) {try {//from the original key data set a Deskeyspec object Deskeyspec DKs = new Deskey Spec (key);//Set up a key factory and use it to convert the Deskeyspec object to//a Secretkey object secretkeyfactory keyfactory = Secretkeyfactory.getinstance ("DES"); Secretkey Secretkey = Keyfactory.generatesecret (DKS);//Using DES in CBC modecipher cipher = cipher.getinstance ("des/cbc/ Pkcs5padding ");//If the Nopadding method is used, the data length must be multiples of 8//Cipher Cipher = cipher.getinstance (" des/cbc/nopadding ");// Cipher object Ivparameterspec param = new Ivparameterspec (iv), Cipher.init (Cipher.decrypt_mode, Secretkey, param) with the key primitive;// Formally perform decryption operation byte decrypteddata[] = cipher.dofinal (data); return decryptEddata;} catch (Exception e) {System.err.println ("Des algorithm, decryption error. "); E.printstacktrace ();} return null;} Convert to hexadecimal string public static string Byte2hex (byte[] b) {string hs = ""; String stmp = ""; for (int n = 0; n < b.length; n++) {stmp = (java.lang.Integer.toHexString (b[n] & 0XFF)), if (stmp.length () = = 1) HS = HS + "0" + Stmp;elsehs = hs + St Mp;if (n < b.length-1) HS = HS + ":";} return Hs.touppercase ();} public static void Main (string[] args) {try {byte[] key = "12345678". GetBytes (); byte[] IV = "11111111". GetBytes (); byte[] D ATA = Des.encrypt ("Hello world!".            GetBytes (), key); System.out.println ("ECB encstr:" +byte2hex (data)); System.out.print ("===========ecb mode============"); System.out.println (New String (Des.decrypt (data, key))); System.out.print ("=============CBC mode===========");d ata = DES. Cbcencrypt ("Hello world!". GetBytes (), key, iv); System.out.println (New String (DES. Cbcdecrypt (data, key, iv)));} catch (Exception e) {e.printstacktrace ();}}}

Several ways to fill des:

Des is an encryption algorithm for 64-bit data, such as a multiple of 64 bits of data bits, which need to be populated and supplemented to a multiple of 64 bits.

Nopadding

The API or algorithm itself does not handle the data, and encrypted data is agreed to fill the algorithm by both sides of the encryption. For example, if the string data to perform encryption and decryption, you can add the space, and then trim

Pkcs5padding

Before encryption: Data byte length to 8, the remainder of M, if m>0, the complement of 8-m bytes, the byte value is 8-m, that is, the difference of multiple bytes to fill multiple bytes, the byte value is the number of supplementary bytes, if 0 is supplemented by 8 bytes of 8

After decryption: Take the beginning of a byte, the value is m, then delete the M bytes from the end of the data, the remaining data is the original text before the encryption

Because DES is a block cipher, a block to 8 bytes, so to encrypt things to dividend 8 bytes of integer times, the lack of padding.

Pkcs5padding this padding, the filled bytes represent the total number of bytes filled:

For example, three bytes to fill in a @@@@@333

7 bytes to fill @7777777

Fill in 88888888 without any difference.


Java des plus decryption

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.