Go Java 3DES (Desede, TripleDES) encryption

Source: Internet
Author: User
Tags base64 decrypt key string asymmetric encryption



Turn from: here


talking about data security

      When you use online banking, are you worried that your card will be compromised?      are you worried that your privacy will be compromised when you chat with your friends on QQ?      as a developer, writing secure code is more important than writing elegant code, because security is the root of all applications! Data encryption/Decryption technology is used to ensure that data is not violated.     --excerpt from The Art of encryption and decryption in Java       so in order to ensure the security of data transmission and storage, we can use specific algorithms to Encrypt the data plaintext into complex ciphertext.      Many encryption methods can be divided into single-and two-way encryption. Single encryption refers to the data through the summary calculation to generate ciphertext, cipher text irreversible push and restore, such as Base64, MD5, SHA, etc. bidirectional encryption, in contrast, means that ciphertext can be reversed into plaintext, in which two-way encryption is divided into symmetric and asymmetric encryption. Symmetric encryption means that the data consumer must have the same key to encrypt and decrypt, as we have agreed a set of signals, symmetric encryption means DES, 3DES, AES, Idea, RC4, RC5, etc., while asymmetric encryption does not need to have the same set of keys relative to symmetric encryption, It is a "key exchange protocol for information disclosure". Asymmetric encryption requires the public key and private key two sets of keys, the public key and the private key is paired together, that is, the use of public key for data encryption, only the corresponding private key to decrypt. This kind of encryption means RSA, DSA and so on.                                                                                                  "Cryptography Common terminology "     plaintext: Unencrypted data      redaction: PlainText encrypted data      encryption: The process of converting plaintext to ciphertext      decryption: The process of converting ciphertext to plaintext          encryption algorithm: conversion algorithm to convert plaintext to ciphertext               decryption algorithm: Convert ciphertext to plaintext conversion algorithm      Encryption key: The key      decryption key used by cryptographic algorithms for cryptographic operations: The key used to decrypt the algorithm for decryption operations      

 First Knowledge 3DES

3DES, also known as 3DESede or TripleDES, is a triple data encryption, and can be inverse of an algorithm scheme.    In 1975, IBM successfully researched and released DES encryption algorithm, but des cipher length was easily brute force, through the improvement of DES algorithm, three times des encryption for each data block, namely 3DES encryption algorithm.    But because the 3DES algorithm is public, so the algorithm itself has no secret, mainly rely on the unique key to ensure the security of data encryption and decryption. One might ask, is the 3DES safe?! So far, no one has cracked 3DES, so if you can hack it, it's enough to shock the entire information security community ..."Java uses 3DES encryption to decrypt the process"① Pass in the common contract key (Keybytes) as well as the algorithm (algorithm) to build the Secretkey Key object Secretkey Deskey = new Secretkeyspec (keybytes, algorithm); ② instantiates cipher objects based on the algorithm.        It is responsible for encrypting/decrypting Cipher C1 = cipher.getinstance (algorithm);        ③ incoming encryption/decryption mode and Secretkey Key object, instantiate Cipher object C1.init (Cipher.encrypt_mode, Deskey); ④ incoming byte array, calls the Cipher.dofinal () method, implements encryption/decryption, and returns a byte byte array c1.dofinal (SRC);

3DES Case

-secretutils.java (3DES Cryptographic Decryption Tool Class)-
Package my3des;
 
Import java.io.UnsupportedEncodingException;
 
Import javax.crypto.Cipher;
Import javax.crypto.SecretKey;
Import javax.crypto.spec.SecretKeySpec;
 
 
/**
 * SecretUtils {3DES encryption and decryption tools }
 * @author William
 * @date 2013-04-19
 */
Public class SecretUtils {
 
    / / Define the encryption algorithm, there are DES, DESede (ie 3DES), Blowfish
    Private static final String Algorithm = "DESede";
    Private static final String PASSWORD_CRYPT_KEY = "2012PinganVitality075522628888ForShenZhenBelter075561869839";
    
    
    /**
     * Encryption method
     * @param src byte array of source data
     * @return
     */
    Public static byte[] encryptMode(byte[] src) {
        Try {
             SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm); //Generate key
             Cipher c1 = Cipher.getInstance(Algorithm); // Instantiate the Cipher tool class responsible for encryption/decryption
             C1.init(Cipher.ENCRYPT_MODE, deskey); //Initialize to encryption mode
             Return c1.doFinal(src);
         } catch (java.security.NoSuchAlgorithmException e1) {
             e1.printStackTrace();
         } catch (javax.crypto.NoSuchPaddingException e2) {
             e2.printStackTrace();
         } catch (java.lang.Exception e3) {
             e3.printStackTrace();
         }
         Return null;
     }
    
    
    /**
     * Decryption function
     * @param src Byte array of ciphertext
     * @return
     */
    Public static byte[] decryptMode(byte[] src) {
        Try {
            SecretKey deskey = new SecretKeySpec(build3DesKey(PASSWORD_CRYPT_KEY), Algorithm);
            Cipher c1 = Cipher.getInstance(Algorithm);
            C1.init(Cipher.DECRYPT_MODE, deskey); //Initialize to decrypt mode
            Return c1.doFinal(src);
        } catch (java.security.NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        } catch (javax.crypto.NoSuchPaddingException e2) {
            e2.printStackTrace();
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();
        }
        Return null;
     }
    
    
    /*
     * Generate a key byte array from a string
     * @param keyStr key string
     * @return
     * @throws UnsupportedEncodingException
     */
    Public static byte[] build3DesKey(String keyStr) throws UnsupportedEncodingException{
        Byte[] key = new byte[24]; //Declare a 24-bit byte array, the default is 0
        Byte[] temp = keyStr.getBytes("UTF-8"); //convert the string to a byte array
        
        /*
         * Perform an array copy
         * System.arraycopy (source array, where to copy from the source array, target array, how many bits to copy)
         */
        If(key.length > temp.length){
            / / If temp is not enough 24 bits, copy the entire length of the temp array into the key array
            System.arraycopy(temp, 0, key, 0, temp.length);
        }else{
            / / If temp is greater than 24 bits, copy the contents of the temp array 24 lengths into the key array
            System.arraycopy(temp, 0, key, 0, key.length);
        }
        Return key;
    }
}




-main.java (test Class)-

Package my3des;
 
Public class Main {
 
     /**
      * @param args
      */
     Public static void main(String[] args) {
         String msg = "3DES encryption and decryption case";
         System.out.println("[Before Encryption]:" + msg);
        
         //encryption
         Byte[] secretArr = SecretUtils.encryptMode(msg.getBytes());
         System.out.println("[encrypted]:" + new String(secretArr));
        
         //decrypt
         Byte[] myMsgArr = SecretUtils.decryptMode(secretArr);
         System.out.println("[after decryption]:" + new String(myMsgArr));
     }
} 




Additional Information the 3DES key must be a 24-bit byte arrayTake a string.getbytes () is not possible, will report the following error Java.security.InvalidKeyException:Invalid key length:59 bytes Solution There are many, ① by key fixed The length of the string is redefined, ② the string with Base64 or MD5, and then intercepts the fixed-length character into a byte array, the ③ string is converted to a byte array, modified for the array, and if the length is too long, only one part is truncated, if the length is not enough 0 • Encryption results are encoded in the same wayThere are generally two ways to convert from a byte array to a string, base64 processing and hexadecimal processing. • References3DES Online test Tool: http://www.seacha.com/tools/3des.php
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.