Java 3DES encryption/decryption Demo__java

Source: Internet
Author: User
Tags base64 decrypt static class stringbuffer
1. Process
Symmetric encryption algorithm is able to decrypt the data. Encrypt the data with the key, and decrypt the data using the same key when decrypting.

  des is an algorithm proposed by the National Institute of Standards in the United States. Because the decrypted data security is proportional to the key length. Des's 56-bit key has become a security risk and is rarely adopted after 1998 years. But some old systems are still in use. Because the DES algorithm has not been published by the United States Standards Board all the algorithms, we all agree that the back door was left behind. So it was eliminated slowly.

  later, the DES algorithm was improved with the Triple DES algorithm (Desede). For the DES algorithm, the key length is shorter and the number of iterations is less, and the security intensity is improved. But the Desede algorithm processing speed is slow, the key computation time is long, the encryption efficiency is not high the question makes the symmetric encryption algorithm the development not to be optimistic.

The DES algorithm provides four models of CBC, OFB, CFB, and ECB, and the MAC is based on ECB implementations.

"Java uses 3DES encryption to decrypt the process"
    ① incoming common agreed key (keybytes) and algorithm (algorithm) to build Secretkey Key Object
        Secretkey Deskey = new Secretkeyspec (keybytes, algorithm);    
    ② instantiate the Cipher object based on the algorithm. It is responsible for encrypting/decrypting
        Cipher c1 = cipher.getinstance (algorithm);    
    ③ incoming encryption/decryption mode and Secretkey Key object, instantiating Cipher object
        c1.init (Cipher.encrypt_mode, deskey);    
    ④ the passed-in byte array, calls the Cipher.dofinal () method, implements encryption/decryption, and returns a byte array
        c1.dofinal (SRC);
2. Code

Des type Encryption decryption:

Package com.tianxin.itfin.core.helper;
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.DESedeKeySpec;
Import Javax.crypto.spec.IvParameterSpec;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import java.io.UnsupportedEncodingException;
Import Java.security.Key;

Import Java.security.SecureRandom; /** * 3DES Encryption Tool Class */public class Encryptutils {//key (during DES encryption and decryption, the key length must be multiples of 8) private final static String Secre

    TKey = "Ucserver";

    Encryption and decryption unified use of the encoding method private final static String encoding = "Utf-8"; /** * 3DES Encryption * * @param plaintext Plain text * @return * @throws Exception/public static St Ring encode (String plaintext) throws Exception {//des algorithm requires a trustworthy random number source SecureRandom sr = new SecureRandom (
        ); Create Deskeyspec object from raw key data DEskeyspec DKs = new Deskeyspec (Secretkey.getbytes ()); Create a key factory and then use it to convert deskeyspec to//a Secretkey object secretkeyfactory keyfactory = secretkeyfactory.getinstance
        ("DES"); in the process of//des encryption and decryption, the key length must be a multiple of 8 secretkey Secretkey = Keyfactory.generatesecret (DKS);
        Using DES in ECB mode Cipher Cipher = cipher.getinstance ("des/ecb/pkcs5padding");
        Initializes the cipher object with the key Cipher.init (Cipher.encrypt_mode, Secretkey, SR);
        Perform cryptographic operations byte[] EncryptData = cipher.dofinal (plaintext.getbytes (encoding));
    Return Base64.encode (encryptdata); /** * 3DES Decryption * * @param encrypttext Encrypted text * @return * @throws Exception * * Public static string decode (String encrypttext) throws Exception {//des algorithm requires a trustworthy random number source SecureRandom sr = new Se
        Curerandom ();
        Creates a Deskeyspec object from the original key data deskeyspec DKs = new Deskeyspec (Secretkey.getbytes ()); Create a key factory and then use it to convert the Deskeyspec objectinto//A Secretkey object secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");
        Secretkey Secretkey = Keyfactory.generatesecret (DKS);

        Using DES in ECB mode Cipher Cipher = cipher.getinstance ("des/ecb/pkcs5padding");
        Initializes the cipher object with the key Cipher.init (Cipher.decrypt_mode, Secretkey, SR);
        Official execution of decryption operation byte[] Decryptdata = cipher.dofinal (Base64.decode (Encrypttext));
    return new String (Decryptdata, encoding);
        public static string padding (String str) {byte[] oldbytearray;
            try {Oldbytearray = str.getbytes ("UTF8");
            int numbertopad = 8-oldbytearray.length% 8;
            byte[] Newbytearray = new Byte[oldbytearray.length + Numbertopad];
            System.arraycopy (Oldbytearray, 0, Newbytearray, 0, oldbytearray.length);
 for (int i = Oldbytearray.length i < newbytearray.length; ++i) {newbytearray[i] = 0;           Return to New String (Newbytearray, "UTF8"); 
        catch (Unsupportedencodingexception e) {System.out.println ("crypter.padding unsupportedencodingexception");
    return null; /** * BASE64 Coding Tool Class * * public static class Base64 {private static final char[] Legalchars = "A

        Bcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789-_ ". ToCharArray ();
            public static String encode (byte[] Data {int start = 0;
            int len = data.length;

            StringBuffer buf = new StringBuffer (data.length * 3/2);
            int end = Len-3;
            int i = start;

            int n = 0; while (I <= end) {int d = (((((int) data[i]) & 0x0ff) << 16 | ((((((int) Data[i + 1]) & 0X0FF) << 8) |
                (((int) Data[i + 2]) & 0X0FF);
                Buf.append (legalchars[(d >> a) & 63]); Buf.append (legalchars[(D >>) & 63]);
                Buf.append (legalchars[(d >> 6) & 63]);
                Buf.append (Legalchars[d & 63]);
                i + 3;
                    if (n++ >=) {n = 0;
                Buf.append (""); } if (i = = start + len-2) {int d = ((((int) data[i]) & 0x0ff) << 16 ) |
                ((((int) Data[i + 1]) & 255) << 8);
                Buf.append (legalchars[(d >> a) & 63]);
                Buf.append (legalchars[(d >>) & 63]);
                Buf.append (legalchars[(d >> 6) & 63]);
            Buf.append ("=");
                else if (i = = start + len-1) {int d = ((int) data[i]) & 0X0FF) << 16;
                Buf.append (legalchars[(d >> a) & 63]);
                Buf.append (legalchars[(d >>) & 63]);
            Buf.append ("= ="); Return Buf.tosTring (); private static int decode (char c) {if (c >= ' A ' && C <= ' Z ') return (
            (int) c)-65;
            else if (c >= ' a ' && c <= ' z ') return ((int) c)-97 + 26;
            else if (c >= ' 0 ' && C <= ' 9 ') return ((int) c)-48 + 26 + 26;
                    else switch (c) {case ' – ': return 62;
                    Case ' _ ': return 63;
                    Case ' = ': return 0;
                Default:throw new RuntimeException ("Unexpected code:" + C); }/** * Decodes the given BASE64 encoded String to a new byte array.
         The byte array holding the decoded data is returned. */public static byte[] Decode (String s) {bytearrayoutputstream bos = new Bytearrayoutputstream ();
            try {decode (s, BOS);
            catch (IOException e) {throw new RuntimeException ();
            } byte[] Decodedbytes = Bos.tobytearray ();
                try {bos.close ();
            BOS = NULL;
            The catch (IOException ex) {System.err.println ("Error while decoding BASE64:" + ex.tostring ());
        return decodedbytes;
            } private static void Decode (String s, OutputStream os) throws IOException {int i = 0;
            int len = S.length ();
                while (true) {while (I < Len && S.charat (i) <= ') i++;
                if (i = = len) break;  int tri = (decode (S.charat (i)) <<) + (decode (S.charat (i + 1)) << (Decode (S.charat (i + 2)) << 6)
                + (Decode (S.charat (i + 3)));
Os.write ((Tri >>) & 255);                if (S.charat (i + 2) = = ' = ') break;
                Os.write ((Tri >> 8) & 255);
                if (S.charat (i + 3) = = ' = ') break;
                Os.write (Tri & 255);
            i + 4; }} public static void Main (string[] args) throws Exception {String plaintext = "[{\" user\ ": \"
        402892ee59b6e6930159b6e849740000\ ", \" mobile\ ": \" 18205189527\ "}]";
        String Encrypttext = Encryptutils.encode (plaintext). Replace ("", "");
        System.out.println (Encrypttext);
    System.out.println (Encryptutils.decode (Encrypttext)); }
}

Run Result:

Pjft-1k_8t9aiblrljwo1iiy3p55ygmorpdxdb4jev2fxqwzvumxfyj4mfyx bbtsdwdptq2ttavyr3q5csbitec94zfgc8mn
[{User]: "402892ee59b6e6930159b6e849740000", "mobile": "18205189527"}]

Desede type encryption decryption only needs to modify the Encode/decode method:

public class EncryptUtils2 {//Key private final static String Secretkey = "Thismy3desdemotestsecretkey";
    Vector private final static String IV = "01234567";

    Encryption and decryption unified use of the encoding method private final static String encoding = "Utf-8"; /** * 3DES Encryption * * @param plaintext Plain text * @return * @throws Exception/public static St
        Ring encode (String plaintext) throws Exception {Key deskey = null;
        Desedekeyspec spec = new Desedekeyspec (Secretkey.getbytes ());
        Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede");

        Deskey = Keyfactory.generatesecret (spec);
        Cipher Cipher = cipher.getinstance ("desede/cbc/pkcs5padding");
        Ivparameterspec ips = new Ivparameterspec (Iv.getbytes ());
        Cipher.init (Cipher.encrypt_mode, Deskey, IPs);
        byte[] EncryptData = cipher.dofinal (plaintext.getbytes (encoding));
    Return Base64.encode (encryptdata); /** * 3DES Decryption * *@param encrypttext Encrypted text * @return * @throws Exception/public static string decode (String Encrypttext
        ) throws Exception {Key deskey = null;
        Desedekeyspec spec = new Desedekeyspec (Secretkey.getbytes ());
        Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("Desede");
        Deskey = Keyfactory.generatesecret (spec);
        Cipher Cipher = cipher.getinstance ("desede/cbc/pkcs5padding");
        Ivparameterspec ips = new Ivparameterspec (Iv.getbytes ());

        Cipher.init (Cipher.decrypt_mode, Deskey, IPs);

        byte[] Decryptdata = cipher.dofinal (Base64.decode (Encrypttext));
    return new String (Decryptdata, encoding); }
    }

Reference:
3DES encryption-java/oc
using des algorithm in Java
Online 3DES encryption and decryption, 3DES online encryption decryption

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.