Java encryption Technology (II) symmetric encryption algorithm Des&aes

Source: Internet
Author: User

Next we introduce symmetric encryption algorithm, the most common is the DES Data encryption algorithm.
DES
Des-data Encryption Standard, namely data encryption algorithm. It was IBM's research success in 1975 and published publicly. The DES algorithm has three entry parameters: Key, Data, Mode. Where key is 8 bytes A total of 64 bits, is the working key of the DES algorithm, data is 8 bytes 64 bits, is to be encrypted or decrypted; Mode is the way des works, there are two kinds: encryption or decryption.
The des algorithm turns the 64-bit plaintext input block into a 64-bit ciphertext output block that uses a key that is also 64 bits.

 

The Java code is implemented as follows:

Import Java.security.invalidkeyexception;import Java.security.key;import java.security.NoSuchAlgorithmException; Import Java.security.securerandom;import Java.security.spec.invalidkeyspecexception;import java.util.Arrays; 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.secretkeyspec;import Org.apache.commons.codec.binary.base64;import org.apache.commons.codec.binary.hex;/** Symmetric Cryptographic algorithm Des&aes * @ Description:todo * @author Somnus * Date April 8, 2015 PM 2:10:44 */public Class Desutil {/** * algorithm algorithm <b      R> * can be replaced by any of the following algorithms, while the size of the key value changes accordingly. * * <pre> * DES key size must equal to * Desede (TripleDES) key size must B e equal to 168 * AES key size must is equal to, 192 or 256,but 192 and the bits may not B E available * Blowfish key size muST is multiple of 8, and can only range from + 448 (inclusive) * RC2 key size must be between 40 and 1024x768 bits * RC4 (arcfour) key size must be between and 1024x768 bits * </pre> * in K The following code is used in the EY keygenerator (byte[] key) method * <code>secretkey Secretkey = new Secretkeyspec (key, algorithm); </code& Gt      Replacement * <code> * deskeyspec deskey = new Deskeyspec (key);      * Secretkeyfactory keyfactory = secretkeyfactory.getinstance (algorithm);      * Secretkey Secretkey = Keyfactory.generatesecret (Deskey);    * </code> * public static final String algorithm = "DES"; Algorithm name/encryption mode/Fill mode//des A total of four modes of operation--&GT;&GT;ECB: Electronic cipher mode, CBC: Encrypted packet link mode, CFB: Cryptographic feedback mode, OFB: Output feedback mode public static final String C    Ipher_algorithm = "des/ecb/nopadding"; /** * * Generate key Key object * @param keystr key String * @return Key Object * @throws InvalidKeyException * @th Rows NoSuchAlgorithmException * @throws INVAlidkeyspecexception * @throws Exception * * * private static Secretkey Keygenerator (byte[] key) throws Except        Ion {Deskeyspec Deskey = new Deskeyspec (key);        Create a key factory and use it to convert Deskeyspec to secretkeyfactory keyfactory = secretkeyfactory.getinstance (algorithm);                Secretkey SecureKey = Keyfactory.generatesecret (Deskey); /* When using other symmetric encryption algorithms, such as AES, Blowfish and other algorithms, replace the above three lines of code with the following code *//*secretkey Secretkey = new Secretkeyspec (Keystr.getbytes (), key_a    LGORITHM); */return SecureKey; /** * Encrypt data * @param data to be encrypted * @param key key * @return Encrypted data * * public static String ENCR        Ypt (String data, String keystr) throws Exception {Key Deskey = Keygenerator (base64.decodebase64 (KEYSTR));        Instantiates the Cipher object, which is used to complete the actual cryptographic operation Cipher Cipher = cipher.getinstance (algorithm);        Initialize the Cipher object, set to cryptographic mode Cipher.init (Cipher.encrypt_mode, Deskey);        byte[] Buff = cipher.dofinal (Data.getbytes ());System.out.println (arrays.tostring (buff)); Performs a cryptographic operation.    The result of the encryption is usually transmitted with BASE64 encoding return hex.encodehexstring (buff); /** * Decrypt Data * @param data to be decrypted * @param key key * @return decrypted data */public static String D        Ecrypt (String data, String keystr) throws Exception {Key Deskey = Keygenerator (base64.decodebase64 (KEYSTR));        Cipher Cipher = cipher.getinstance (algorithm);        Initializes the cipher object, set to decryption mode Cipher.init (Cipher.decrypt_mode, Deskey);        Perform decryption operation byte[] buff = cipher.dofinal (Hex.decodehex (Data.tochararray ()));        System.out.println (arrays.tostring (buff));    return new String (buff); /** * Generate key * @return * @throws Exception */public static String Initkey () throws Exception      {return initkey (null); /** * Generate key * @param seed * @return * @throws Exception */public static String Initkey (stri Ng Seed) throws Exception {SecureraNdom securerandom = null;         if (seed! = null) {SecureRandom = new SecureRandom (base64.decodebase64 (Seed));         } else {securerandom = new securerandom ();         } keygenerator kg = keygenerator.getinstance (algorithm);         Kg.init (SecureRandom);         Secretkey Secretkey = Kg.generatekey ();    Return base64.encodebase64string (secretkey.getencoded ());        public static void Main (string[] args) throws Exception {String key = Initkey ();                System.out.println (key+ "Size:" +base64.decodebase64 (key). length);        String Source = "Somnus";                System.out.println ("Original:" + source);        String EncryptData = Encrypt (source, key);                SYSTEM.OUT.PRINTLN ("After encryption:" + EncryptData);        String Decryptdata = Decrypt (encryptData, key);    System.out.println ("After decryption:" + decryptdata); }}

The resulting output reads as follows:

5umcaynx9oy=size:8 Original: somnus[40, 72, 46, 74, 49, 99, 10, 119] After encryption: 28482E4A31630A77[83, 111, 109, 110, 117, 115] after decryption: Somnus

With the output from the console, we are able to match the results of encryption and decryption. This is a simple encryption and decryption method with only one key.
In fact des has a lot of brothers, such as Desede (TripleDES), AES, Blowfish, RC2, RC4 (Arcfour). Here is not too much elaboration, similar, as long as the replacement of algorithm for the corresponding value, at the same time do a code substitutionSecretkey Secretkey = new Secretkeyspec (key, algorithm);you can, and the key length is different.

Java code
  1. /**
  2. * DES key size must be equal to
  3.  * desede (TripleDES)  key size must be equal to 112  or 168  
  4.  * aes          key size  Must be equal to 128, 192 or 256,but 192 and 256 bits  may not be available  
  5.  * blowfish     key size must be multiple  of 8, and can only range from 32 to 448  (inclusive)  
  6.  * rc2          key size  Must be between 40 and 1024 bits  
  7. * RC4 (arcfour) key size must be between and 1024x768 bits
  8.  **/

Java encryption Technology (II) symmetric encryption algorithm Des&aes

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.