role-based Privilege Management System--front-end login data JS encrypted back-end decryption (DES) __js

Source: Internet
Author: User
Tags base64 decrypt uuid

Implementation of the front-end data encryption after the transmission, the back-end of the encrypted data to decrypt, and then to the database comparison. The symmetric encryption algorithm is used for decryption. Do not discuss which symmetric encryption algorithm is good, here using DES, in the process of implementation found to find a JS version of DES encryption, and Java can des decryption is really not easy. Add and Decrypt ideas

Because it is symmetric encryption, the encryption key that is decrypted is very important. The UUID is used as the decryption key, and the UUID generated each time the page is requested is different, guaranteeing that each key is not known.

See the back-end generation key process

@RequestMapping (value = "/login.html", method = requestmethod.get) public
String Login (model model, HttpSession session) {
    logger.info ("login page");
    Session.setattribute (Sessionparam.login_key, Uuidgenerator.getuuid ());
    Model.addattribute ("title", "User Login");
    return "Admin/login";
}

When you enter the login page, the generated UUID is placed in the session.

Password two times md5
var passwordMd5 = cryptojs.md5 (password);
PasswordMd5 = CRYPTOJS.MD5 (PASSWORDMD5);
Console.info ("MD5:" + passwordMd5);
$ (this). Val ("Logging in ...");
$ (this). attr ("Disabled", true);
User name des encryption
username = encryptbydes (username, key);
Populate the form and submit the form
$ ("#postUsername"). Val (username);
$ (' #postPassword '). Val (passwordMd5);
$ (' #postForm '). Submit ();

DES encryption
function encryptbydes (message, key) {
    var keyhex = CryptoJS.enc.Utf8.parse (key);
    var encrypted = CryptoJS.DES.encrypt (message, Keyhex, {
        Mode:CryptoJS.mode.ECB,
        padding: CRYPTOJS.PAD.PKCS7
    });
    return encrypted.tostring ();
}

When the form is ready, the password is MD5 two times, the username is des encrypted, and the encrypted key is the UUID saved in the session.

The backend then decrypts the passed user name, because the database is stored in the password two times MD5 value, so only the user name encryption, because even if the password is obtained, do not know what.

Back-end processes

Get encryption Key
Logger.info ("-----raw Data: username:{} password:{}-----", username, password);
String key = Session.getattribute (Sessionparam.login_key) + "";
Logger.info ("-----Plus decryption key:{}-----", key);
try {
    username = desutil.decryption (username, key);
} catch (Exception e) {
    logger.info ("-----decryption error: {}----- ", E.getmessage ());
}
Logger.info ("After decryption: username:{} password:{}", username, password);

Screenshots

JAVA DES

Share a JS front-end encryption, Java back-end encryption applet

Package com.jrbac.util;
Import java.security.InvalidKeyException;
Import java.security.NoSuchAlgorithmException;

Import java.security.spec.InvalidKeySpecException;
Import javax.crypto.BadPaddingException;
Import Javax.crypto.Cipher;
Import javax.crypto.IllegalBlockSizeException;
Import javax.crypto.NoSuchPaddingException;
Import Javax.crypto.SecretKey;
Import Javax.crypto.SecretKeyFactory;

Import Javax.crypto.spec.DESKeySpec; /** * des encryption and decryption tool class * * @author Cheng Gaowei * * @date June 15, 2016 a.m. 10:02:50/public class Desutil {private static final

    String des_algorithm = "DES";
     /** * DES encryption * * @param plaindata * Raw String * @param secretkey * Encryption key * @return Encrypted String * @throws Exception/public static string encryption (string Plaindata, String secretk
        EY) throws Exception {Cipher Cipher = null;
            try {cipher = cipher.getinstance (des_algorithm); Cipher.init (Cipher.encrypt_modE, GenerateKey (Secretkey));
        catch (NoSuchAlgorithmException e) {e.printstacktrace ();
        catch (Nosuchpaddingexception e) {e.printstacktrace ();  catch (InvalidKeyException e) {} try {//To prevent decryption times javax.crypto.IllegalBlockSizeException: Input length must//is multiple of 8 when decrypting with padded cipher exception,//cannot convert encrypted byte array directly to characters

            String byte[] buf = cipher.dofinal (Plaindata.getbytes ());

        Return Base64utils.encode (BUF);
            catch (Illegalblocksizeexception e) {e.printstacktrace ();
        throw new Exception ("Illegalblocksizeexception", e);
            catch (Badpaddingexception e) {e.printstacktrace ();
        throw new Exception ("Badpaddingexception", e);            }/** * des decryption * * @param secretdata * Password String * @param secretkey * Decryption key * @return Raw String * @throws Exception */public static string decryption (string secretdata, String secretkey) throws Exception {
        Cipher Cipher = null;
            try {cipher = cipher.getinstance (des_algorithm);

        Cipher.init (Cipher.decrypt_mode, GenerateKey (Secretkey));
            catch (NoSuchAlgorithmException e) {e.printstacktrace ();
        throw new Exception ("NoSuchAlgorithmException", e);
            catch (Nosuchpaddingexception e) {e.printstacktrace ();
        throw new Exception ("Nosuchpaddingexception", e);
            catch (InvalidKeyException e) {e.printstacktrace ();

        throw new Exception ("InvalidKeyException", e);

            try {byte[] buf = cipher.dofinal (Base64utils.decode (Secretdata.tochararray ()));

        return new String (BUF);
            catch (Illegalblocksizeexception e) {e.printstacktrace (); throw new Exception ("Illegalblocksizeexception", e);
            catch (Badpaddingexception e) {e.printstacktrace ();
        throw new Exception ("Badpaddingexception", e);
     }/** * Obtain secret key * * @param secretkey * @return * @throws nosuchalgorithmexception * @throws invalidkeyspecexception * @throws invalidkeyexception/private static Secretkey GenerateKey (Str ing Secretkey) throws NoSuchAlgorithmException, Invalidkeyspecexception, invalidkeyexception {SecretK
        Eyfactory keyfactory = secretkeyfactory.getinstance (des_algorithm);
        Deskeyspec Keyspec = new Deskeyspec (Secretkey.getbytes ());
        Keyfactory.generatesecret (KEYSPEC);
    Return Keyfactory.generatesecret (KEYSPEC); Static Private class Base64utils {static private char[] Alphabet = "Abcdefghijklmnopqrstuvwxyzabcdefghijk
        Lmnopqrstuvwxyz0123456789+/= ". ToCharArray ();

        Static private byte[] codes = new byte[256]; Static {for (int i = 0; i < 256 i++) Codes[i] =-1;
            for (int i = ' a '; I <= ' Z '; i++) codes[i] = (byte) (i-' a ');
            for (int i = ' a '; I <= ' z '; i++) codes[i] = (byte) (+ I-' a ');
            for (int i = ' 0 '; I <= ' 9 '; i++) codes[i] = (byte) (+ I-' 0 ');
            codes[' + '] = 62;
        codes['/'] = 63; /** * Encodes raw data as Base64 encoding/static private String encode (byte[] data) {Cha
            R[] out = new char[((Data.length + 2)/3) * 4];
                for (int i = 0, index = 0 I < data.length i + = 3, index + + 4) {Boolean quad = false;
                Boolean trip = false;
                int val = (0xFF & (int) data[i]);
                Val <<= 8;
                    if ((i + 1) < Data.length) {val |= (0xFF & (int) Data[i + 1]);
          Trip = true;      } Val <<= 8;
                    if ((i + 2) < Data.length) {val |= (0xFF & (int) Data[i + 2]);
                Quad = true; } Out[index + 3] = alphabet[(quad?)
                (Val & 0x3F): 64)];
                Val >>= 6; Out[index + 2] = alphabet[(trip?)
                (Val & 0x3F): 64)];
                Val >>= 6;
                Out[index + 1] = alphabet[val & 0x3F];
                Val >>= 6;
            Out[index + 0] = alphabet[val & 0x3F];
        Return to New String (out);
            /** * Decodes base64 encoded data into raw data */static private byte[] Decode (char[) data) {
            int len = ((data.length + 3)/4) * 3;
            if (data.length > 0 && data[data.length-1] = = ' = ')--len;
            if (Data.length > 1 && data[data.length-2] = = ' = ')--len; Byte[] out = new Byte[len];
            int shift = 0;
            int accum = 0;
            int index = 0;
                for (int ix = 0; ix < data.length; ix++) {int value = Codes[data[ix] & 0xFF];
                    if (value >= 0) {Accum <<= 6;
                    SHIFT + 6;
                    Accum |= value;
                        if (Shift >= 8) {shift = 8;
                    out[index++] = (byte) ((Accum >> shift) & 0xff);  }} if (index!= out.length) throw new Error ("miscalculated data
            Length! ");
        return out;
 }
    }
}

Cryptojs des and MD5

Download Address

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.