Java des encryption and decryption

Source: Internet
Author: User

Java des encryption and decryption

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 The method requires a trusted random number source SecureRandom sr = new SecureRandom (); // generate a KeyGenerator object KeyGenerator kg = KeyGenerator of the DES algorithm. getInstance ("DES"); kg. init (sr); // generate SecretKey secretKey = kg. generateKey (); // obtain the key Data byte [] key = secretKey. getEncoded (); return key;} catch (NoSuchAlgorithmException e) {System. err. println ("DES algorithm, an error occurred while generating the key! "); E. printStackTrace ();} return null ;} /***** encryption function ***** @ param data ** data Encryption ** @ param key ** @ return to encrypted data */public static byte [] encrypt (byte [] data, byte [] key) {try {// DES algorithm requires a trusted random number source SecureRandom sr = new SecureRandom (); // set up the DESKeySpec object DESKeySpec dks = new DESKeySpec (key) from the original key data; // set up a key factory, then use it to convert DESKeySpec into a // SecretKey object SecretKeyFactory keyFactory = SecretKeyFactory. getIn Stance ("DES"); SecretKey secretKey = keyFactory. generateSecret (dks); // using DES in ECB modeCipher cipher = Cipher. getInstance ("DES/ECB/PKCS5Padding"); // use the key to initialize the Cipher object cipher. init (Cipher. ENCRYPT_MODE, secretKey, sr); // execute the encryption operation byte encryptedData [] = cipher. doFinal (data); return encryptedData;} catch (Exception e) {System. err. println ("DES algorithm, data encryption error! "); E. printStackTrace ();} return null ;} /***** decryption function ***** @ param data ** decrypts data ** @ param key ** @ return to decrypted data */public static byte [] decrypt (byte [] data, byte [] key) {try {// DES algorithm requires a trusted random number source SecureRandom sr = new SecureRandom (); // byte rawKeyData [] =/* obtain the original key data in a certain way */; // set up a keyspec object named DESKeySpec dks = new DESKeySpec (key) from the original key data ); // set up a key factory, and then use it to convert the keyspec object to // A SecretKey object secrere TKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES"); SecretKey secretKey = keyFactory. generateSecret (dks); // using DES in ECB modeCipher cipher = Cipher. getInstance ("DES/ECB/PKCS5Padding"); // use the key to initialize the Cipher object cipher. init (Cipher. DECRYPT_MODE, secretKey, sr); // perform the 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 ** data Encryption ** @ param key ** @ return to encrypted data */public static byte [] CBCEncrypt (byte [] data, byte [] key, byte [] iv) {try {// from the original key data, establish the DESKeySpec object DESKeySpec dks = new DESKeySpec (key); // set up a key factory, then use it to convert DESKeySpec into a // SecretKey object SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES"); SecretKey secretKey = keyFacto Ry. generateSecret (dks); // The Cipher object implements the encryption operation Cipher cipher = Cipher. getInstance ("DES/CBC/PKCS5Padding"); // If NoPadding is used, the data length must be a multiple of 8. // Cipher cipher = Cipher. getInstance ("DES/CBC/NoPadding"); // use the key to initialize the Cipher object IvParameterSpec param = new IvParameterSpec (iv); cipher. init (Cipher. ENCRYPT_MODE, secretKey, param); // execute the encryption operation byte encryptedData [] = cipher. doFinal (data); return encryptedData;} catch (Exception E) {System. err. println ("DES algorithm, data encryption error! "); E. printStackTrace ();} return null ;} /***** decryption function ***** @ param data ** decrypts data ** @ param key ** @ return to decrypted data */public static byte [] CBCDecrypt (byte [] data, byte [] key, byte [] iv) {try {// set up a DESKeySpec object named DESKeySpec dks = new DESKeySpec (key) from the original key data; // set up a key factory, then it is used to convert the receiveyspec object into a // SecretKey object SecretKeyFactory keyFactory = SecretKeyFactory. getInstance ("DES"); SecretKey secretKey = keyF Acloud. generateSecret (dks); // using DES in CBC modeCipher cipher = Cipher. getInstance ("DES/CBC/PKCS5Padding"); // If NoPadding is used, the data length must be a multiple of 8. // Cipher cipher = Cipher. getInstance ("DES/CBC/NoPadding"); // use the key to initialize the Cipher object IvParameterSpec param = new IvParameterSpec (iv); cipher. init (Cipher. DECRYPT_MODE, secretKey, param); // perform the 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 the 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 + stmp; if (n <B. length-1) hs = hs + ":";} return hs. toUpperCase ();} public static void main (String [] args) {try {byte [] key = "1234567 8 ". getBytes (); byte [] iv =" 11111111 ". getBytes (); byte [] data = 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 ==========="); data = DES. CBCEncrypt ("hello world! ". GetBytes (), key, iv); System. out. println (new String (DES. CBCDecrypt (data, key, iv);} catch (Exception e) {e. printStackTrace ();}}}

DES fill methods:

DES is an encryption algorithm for 64-bit data. If the number of data digits lacks a multiple of 64-bit, it must be filled with a multiple of 64-bit.

NoPadding

The API or algorithm itself does not process the data, and the encrypted data is managed by the encryption algorithm on both sides. For example, if you perform encryption and decryption on string data, you can add \ 0 or space and trim

PKCS5Padding

Before encryption: the length of data bytes is 8 bytes, and the remainder is m. If m is greater than 0, 8-m bytes are supplemented. The value of the byte is 8-m, that is, if the difference is between multiple bytes, the number of bytes is the number of bytes added. If the value is 0, the number of 8 bytes is added.

After decryption: Take the first byte and the value is m. Then, delete m bytes from the end of the data. The remaining data is the original text before encryption.

Because DES is a block cipher, a block requires 8 bytes, so the encryption should be an integer multiple of 8 bytes. If it is lacking, it should be filled.

PKCS5Padding indicates the total number of entered bytes:

For example, if the difference is three bytes, enter @ 333.

If the difference is 7 bytes, enter @ 7777777.

Enter 88888888 if there is no difference


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.