Java two-dimensional code login process implementation code (contains a short address generation, including part of the code) _java

Source: Internet
Author: User
Tags bitwise int size md5 unique id

In recent years, the use of two-dimensional code more and more wind, the author recently on hand also encountered a need to use two-dimensional code to scan the site's live, so the study of this set of mechanisms, and code to achieve the entire process, and then we chat about two-dimensional code login and those things.

Two-dimensional code principle

Two-dimensional code is a micro-letter to get up, the same year micro-scan code two-dimensional code to login to the Web site micro-letter, the feeling is very magical, however, we understand its principle, it is not so magical. The two-dimensional code actually contains a URL request information through a black and white dot matrix. Sweep code on the end, request URL, do the corresponding operation.

Principle of general sweep code operation

Micro-letter login, pay treasure Sweep code payment is this principle:

1. Request two dimensional code

The desktop side initiates a request for a two-dimensional code to the server.

2. Generate a two-dimensional code that contains a unique ID

The desktop side randomly generates a id,id that uniquely identifies the two-dimensional code for subsequent operations.

3. Sweep code on end

Moving end-sweep code two-dimensional code, the solution Chu out of two-dimensional code in the URL request.

4. Mobile end Send request to server

The mobile end sends a URL request to the server, which contains two information, which code is scanned by the unique ID identifier, and the specific cookie or header parameter in the browser will be identified by which user to sweep the code.

5. Server-side notification sweep code success

When the server receives the URL request of the information in the two-dimensional code, the notification side has already swept the code successfully, and adds the necessary information such as the login cookie. There are generally a few ways to notify: WebSocket, rotation hold to live the request until the timeout, a few seconds rotation.

The art of URL in two-dimensional code

How to achieve the different performance of own client and other client scan code (such as micro-letter)

For example, in a business, you might want to do this, if your company's two-dimensional code is scanned by other apps (such as micro-mail), you want to jump to a hint page, you can have an app download link on the page, and then respond directly to the request when scanned by your own app.

In this case, you can do this, all the links in the two-dimensional code are encrypted one layer, and then unified with another link to deal with.

such as: Www.test.com/qr?p=xxxxxx,p parameter contains the server and the client agreed to add decryption algorithm (can be symmetrical or asymmetric), the end of the sweep code to this particular path, directly with the decryption algorithm to solve p parameters, get www.testqr.com/ Qrcode?key=s1arv, so that you can initiate a request to the server, and other clients because they do not know this rule, can only go directly to request WWW.TEST.COM/QR?P=XXXXXX, the request returned to the prompt page.

How to make a two-dimensional code simpler

A lot of times, and the horse run, cake. If you want a two-dimensional code with a lot of parameters, but do not want the two-dimensional code too complex, difficult to be swept out of the code. At this point, you need to consider how to make the two-dimensional code simpler without impacting the business.

    • With the end of the Convention rules: for example, the definition of encoding information in the I parameter to 1,2,3 represents a different URI, the end of the match encountered a different I parameters to request which interface
    • Simplify everything to simplify: Simplify the URI, simplify the key in the parameter, value. such as Www.a.com/q?k=s1arV is much simpler than www.abc.def.adfg.edu.com.cn/qrcode/scan?k=77179574e98a7c860007df62a5dbd98b, The resulting two-dimensional code is much better swept.
    • Simplify unique ID parameter: The parameter value in the previous request in the previous one is only 5 bits, and the parameter value in the last request is the generated 32-bit MD5 value. It is important to generate one-side key.

Sample code

Generate two-dimensional code (remove white edges, increase the logo in the middle)

Need to import jar package: Zxing Core-2.0.jar

Import Java.awt.BasicStroke;
Import Java.awt.Color;
Import Java.awt.Graphics;
Import Java.awt.Graphics2D;
Import Java.awt.Image;
Import Java.awt.Shape;
Import Java.awt.geom.RoundRectangle2D;
Import Java.awt.image.BufferedImage;
Import Java.io.ByteArrayOutputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.util.HashMap;

Import Java.util.Map;
Import Javax.imageio.ImageIO;
Import Com.google.zxing.BarcodeFormat;
Import Com.google.zxing.EncodeHintType;
Import Com.google.zxing.MultiFormatWriter;
Import Com.google.zxing.common.BitMatrix;

Import Com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  public class Qrcodeutil {private static final int black = Color.black.getRGB ();
  private static final int white = Color.WHITE.getRGB ();
  private static final int default_qr_size = 183;
  private static final String Default_qr_format = "png";
  
  private static final byte[] Empty_bytes = new Byte[0]; public static byte[] Createqrcode (String content, int size, String extension) {return Createqrcode (content, size, extension, null); /** * Generate two-dimensional code with pictures * @param content two-dimensional code to include information * @param size * @param extension file format extension * @param insert IMG Center Logo Picture * @return/public static byte[] Createqrcode (string content, int size, string extension, Image ins
    ERTIMG) {if (size <= 0) {throw new IllegalArgumentException ("size (" + size + ") cannot be <= 0");
    } Bytearrayoutputstream BAOs = null;
      try {map<encodehinttype, object> hints = new Hashmap<encodehinttype, object> ();
      Hints.put (Encodehinttype.character_set, "utf-8");

      Hints.put (Encodehinttype.error_correction, ERRORCORRECTIONLEVEL.M);
      
      Uses information to generate the specified size dot matrix bitmatrix m = new Multiformatwriter (). Encode (content, barcodeformat.qr_code, size, size, hints);
      
      Remove White side m = updatebit (m, 0);
      int width = m.getwidth ();
      
      int height = m.getheight (); Set the information in Bitmatrix to BUFferdimage, the formation of black-and-white picture bufferedimage image = new BufferedImage (width, height, bufferedimage.type_int_rgb); for (int i = 0; i < width; i++) {for (int j = 0; j < height; j) {Image.setrgb (I, J, M.get (I, J ) ?
        Black:white);
      } if (insertimg!= null) {//Insert logo picture in the middle insertimage (image, Insertimg, M.getwidth ());
      ///will enlarge the image to be smaller because of going white edge image = Zoominimage (image, size, size);
      BAOs = new Bytearrayoutputstream ();
      
      Imageio.write (image, extension, BAOs);
    return Baos.tobytearray ();
        The catch (Exception e) {} finally {if (BAOs!= null) try {baos.close ();
        catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
  } return empty_bytes; /** * Custom two-dimensional code white-edge Width * @param matrix * @param margin * @return/private static Bitmatrix Updatebit (B
   Itmatrix Matrix, int margin) { int tempm = margin * 2; int[] rec = Matrix.getenclosingrectangle ();
    Gets the properties of the two-dimensional code pattern int reswidth = rec[2] + tempm;
    int resheight = rec[3] + tempm; Bitmatrix Resmatrix = new Bitmatrix (reswidth, resheight);
    Generates a new Bitmatrix resmatrix.clear () according to the custom border; for (int i = margin I < Reswidth-margin i++) {//loops, drawing two-dimensional code patterns into the new Bitmatrix for (int j = margin; J < Reshei Ght-margin;
        J + +) {if (Matrix.get (I-margin + rec[0], J-margin + rec[1])) {Resmatrix.set (i, j);
  }} return Resmatrix; //Picture Zoom out public static BufferedImage Zoominimage (bufferedimage originalimage, int width, int height) {Buffe
    Redimage newimage = new BufferedImage (width, height, originalimage.gettype ());
    Graphics g = newimage.getgraphics ();
    G.drawimage (originalimage, 0, 0, width, height, null);
    G.dispose ();
  return newimage; private static void Insertimage (BufferedImage source, Image insertimg, int size) {try{int width = insertimg.getwidth (null);
      int height = insertimg.getheight (null); width = width > size/6? SIZE/6: Width; One-sixth Size height = height > SIZE/6 with the logo set to two-dimensional code
      SIZE/6: Height;
      Graphics2D graph = source.creategraphics ();
      int x = (size-width)/2;
      int y = (size-height)/2;
      Graph.drawimage (insertimg, x, y, width, height, null);
      Shape shape = new Roundrectangle2d.float (x, y, Width, width, 6, 6);
      Graph.setstroke (New Basicstroke (3f));
      Graph.draw (Shape);
    Graph.dispose ();
    catch (Exception e) {e.printstacktrace (); } public static byte[] Createqrcode (String content) {return Createqrcode (content, Default_qr_size, default_qr_
  FORMAT);
      public static void Main (string[] args) {try {fileoutputstream fos = new FileOutputStream ("Ab.png");
      Fos.write (Createqrcode ("Test"));
    Fos.close (); catch (Exception e) {//TODO auto-generated catch blOck E.printstacktrace ();

 }
    
  }
  
}

Generate Short Links

Basic ideas:

The theory of short URL mapping algorithm:

1. The long web site plus random number with the MD5 algorithm to generate 32-bit signature string, divided into 4 paragraphs, 8 characters per paragraph

2. For the 4-segment loop, take 8 characters per paragraph and consider him as a bit of the 16-in-string and 0X3FFFFFFF (30-bit 1) with operations, over 30-bit ignore processing

3. The 30 bits obtained in each paragraph are divided into 6 segments, each 5 digit number is taken as the index of the alphabet to obtain a specific character and the 6-bit string is obtained sequentially;

4. Such a MD5 string can be obtained from 4 6-bit strings, whichever of them can be used as the short URL of this long URL.

5. It is best to use a Key-value database storage, in case of collision for one, if four have collided, regenerate MD5 (because there are random numbers, will generate a different MD5)

public class Shorturlutil {/** * Incoming 32-bit MD5 value * @param MD5 * @return/public static string[] Shorturl (St Ring MD5) {///to use the character that generates the URL string[] chars = new string[] {"A", "B", "C", "D", "E", "F", "G", "H", "I", 
        "J", "K", "L", "M", "N", "O", "P", "Q", "R", "s", "T", "U", "V", "w", "X", "Y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q",
    
    "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}; 
    
    string[] Resurl = new String[4]; for (int i = 0; i < 4; i++) {//Encrypt characters are bitwise and 0X3FFFFFFF in 8-bit group 16-digit, over 30-bit ignored String stempsubstring = m

      D5.substring (i * 8, I * 8 + 8); This needs to be converted using a long type, because Inteper. parseint () can only handle 31 bits, the first is the sign bit, and if you don't use long, you will cross the line long Lhexlong = 0x3fffffff & Lon
      G.parselong (stempsubstring, 16);
      String outchars = ""; for (int j = 0; J < 6; J + +) {//the resulting value with 0x0000003d The bitwise and the operation, obtains the character array chars index long indexed = 0x0000003d & Lhexlong;
        Add the acquired character Outchars + + = chars[(int) index];
      5-bit Lhexlong = Lhexlong >> 5 per loop-Bitwise RIGHT SHIFT
    (///////////= Resurl[i] = Outchars to the output array of the corresponding index;
  return resurl;
    public static void Main (String [] args) {string[] test = Shorturl ("Fdf8d941f23680be79af83f921b107ac");
    for (string string:test) {System.out.println (string);

 }
  }
  
}

Description: The core code is not original, draw on the code of others, thanks!

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.