Commonly used encryption

The project has been completed recently, so it will be relatively idle. I will summarize the encryption used for reference only.

1. First of all, md5 encryption is commonly used to encrypt passwords. We use md5 secondary encryption in the foreground (without using salt encryption) and transfer it to the background for verification. It is best to use salt encryption, you can Baidu , the relevant code is as follows:

public class MD5Util {
	/***
     * MD5 plus code generates 32-bit md5 code
     */  
    public static String string2MD5(String inStr){  
        MessageDigest md5 = null;  
        try{  
            md5 = MessageDigest.getInstance("MD5");  
        }catch (Exception e){  
            System.out.println(e.toString());  
            e.printStackTrace ();  
            return "";  
        }  
        char[] charArray = inStr.toCharArray();  
        byte[] byteArray = new byte[charArray.length];  
  
        for (int i = 0; i < charArray.length; i++)  
            byteArray[i] = (byte) charArray[i];  
        byte[] md5Bytes = md5.digest(byteArray);  
        StringBuffer hexValue = new StringBuffer ();  
        for (int i = 0; i < md5Bytes.length; i++){  
            int val = ((int) md5Bytes[i]) & 0xff;  
            if (val < 16)  
                hexValue.append("0");  
            hexValue.append (Integer.toHexString (val));  
        }  
        return hexValue.toString();  
  
    }  
  
    /**
     * The encryption and decryption algorithm performs one encryption and two decryptions
     */   
    public static String convertMD5(String inStr){  
  
        char[] a = inStr.toCharArray();  
        for (int i = 0; i < a.length; i++){  
            a[i] = (char) (a[i] ^ 't');  
        }  
        String s = new String(a);  
        return s;  
  
    }  
  
    // test the main function  
    public static void main(String args[]) {  
        String s = new String("111111");  
        System.out.println("原始:" + s);  
        System.out.println("MD5后:" + string2MD5(s));  
        System.out.println("After MD5 twice: " + string2MD5(string2MD5(s)));  
        System.out.println("Encrypted: " + convertMD5(s));  
        System.out.println("Decrypted: " + convertMD5("BBBBBB"));  
    }  
}

2.base64 encryption, we mainly use base64 for encrypted transmission when transmitting pictures

The relevant code is as follows:

public final class Base64 {

    static private final int     BASELENGTH           = 128;
    static private final int     LOOKUPLENGTH         = 64;
    static private final int     TWENTYFOURBITGROUP   = 24;
    static private final int     EIGHTBIT             = 8;
    static private final int     SIXTEENBIT           = 16;
    static private final int     FOURBYTE             = 4;
    static private final int     SIGN                 = -128;
    static private final char    PAD                  = '=';
    static private final boolean fDebug               = false;
    static final private byte[]  base64Alphabet       = new byte[BASELENGTH];
    static final private char[]  lookUpBase64Alphabet = new char[LOOKUPLENGTH];

    static {
        for (int i = 0; i < BASELENGTH; ++i) {
            base64Alphabet [i] = -1;
        }
        for (int i = 'Z'; i >= 'A'; i--) {
            base64Alphabet[i] = (byte) (i - 'A');
        }
        for (int i = 'z'; i >= 'a'; i--) {
            base64Alphabet[i] = (byte) (i - 'a' + 26);
        }

        for (int i = '9'; i >= '0'; i--) {
            base64Alphabet[i] = (byte) (i - '0' + 52);
        }

        base64Alphabet['+'] = 62;
        base64Alphabet['/'] = 63;

        for (int i = 0; i <= 25; i++) {
            lookUpBase64Alphabet[i] = (char) ('A' + i);
        }

        for (int i = 26, j = 0; i <= 51; i++, j++) {
            lookUpBase64Alphabet[i] = (char) ('a' + j);
        }

        for (int i = 52, j = 0; i <= 61; i++, j++) {
            lookUpBase64Alphabet[i] = (char) ('0' + j);
        }
        lookUpBase64Alphabet[62] = (char) '+';
        lookUpBase64Alphabet[63] = (char) '/';

    }

    private static boolean isWhiteSpace(char octect) {
        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
    }

    private static boolean isPad(char octect) {
        return (octect == PAD);
    }

    private static boolean isData(char octect) {
        return (octect < BASELENGTH && base64Alphabet[octect] != -1);
    }

    /** Encrypt
     * Encodes hex octects into Base64
     *
     * @param binaryData Array containing binaryData
     * @return Encoded Base64 array
     */
    public static String encode(byte[] binaryData) {

        if (binaryData == null) {
            return null;
        }

        int lengthDataBits = binaryData.length * EIGHTBIT;
        if (lengthDataBits == 0) {
            return "";
        }

        int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
        int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
        int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets;
        char encodedData[] = null;

        encodedData = new char[numberQuartet * 4];

        byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;

        int encodedIndex = 0;
        int dataIndex = 0;
        if (fDebug) {
            System.out.println("number of triplets = " + numberTriplets);
        }

        for (int i = 0; i < numberTriplets; i++) {
            b1 = binaryData[dataIndex++];
            b2 = binaryData[dataIndex++];
            b3 = binaryData[dataIndex++];

            if (fDebug) {
                System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);
            }

            l = (byte) (b2 & 0x0f);
            k = (byte) (b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);
            byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6) : (byte) ((b3) >> 6 ^ 0xfc);

            if (fDebug) {
                System.out.println("val2 = " + val2);
                System.out.println("k4   = " + (k << 4));
                System.out.println("vak  = " + (val2 | (k << 4)));
            }

            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];
        }

        // form integral number of 6-bit groups
        if (fewerThan24bits == EIGHTBIT) {
            b1 = binaryData[dataIndex];
            k = (byte) (b1 & 0x03);
            if (fDebug) {
                System.out.println("b1=" + b1);
                System.out.println("b1<<2 = " + (b1 >> 2));
            }
            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];
            encodedData[encodedIndex++] = PAD;
            encodedData[encodedIndex++] = PAD;
        } else if (fewerThan24bits == SIXTEENBIT) {
            b1 = binaryData[dataIndex];
            b2 = binaryData[dataIndex + 1];
            l = (byte) (b2 & 0x0f);
            k = (byte) (b1 & 0x03);

            byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2) : (byte) ((b1) >> 2 ^ 0xc0);
            byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4) : (byte) ((b2) >> 4 ^ 0xf0);

            encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];
            encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];
            encodedData[encodedIndex++] = PAD;
        }

        return new String(encodedData);
    }

    /** decrypt
     * Decodes Base64 data into octects
     *
     * @param encoded string containing Base64 data
     * @return Array containind decoded data.
     */
    public static byte[] decode(String encoded) {

        if (encoded == null) {
            return null;
        }

        char[] base64Data = encoded.toCharArray();
        // remove white spaces
        int len = removeWhiteSpace(base64Data);

        if (len % FOURBYTE != 0) {
            return null;//should be divisible by four
        }

        int numberQuadruple = (len / FOURBYTE);

        if (numberQuadruple == 0) {
            return new byte[0];
        }

        byte decodedData[] = null;
        byte b1 = 0, b2 = 0, b3 = 0, b4 = 0;
        char d1 = 0, d2 = 0, d3 = 0, d4 = 0;

        int i = 0;
        int encodedIndex = 0;
        int dataIndex = 0;
        decodedData = new byte[(numberQuadruple) * 3];

        for (; i < numberQuadruple - 1; i++) {

            if (! isData ((d1 = base64Data [dataIndex ++])) ||! isData ((d2 = base64Data [dataIndex ++]))
                || ! isData ((d3 = base64Data [dataIndex ++]))
                || ! isData ((d4 = base64Data [dataIndex ++]))) {
                return null;
            }//if found "no data" just return null

            b1 = base64Alphabet[d1];
            b2 = base64Alphabet[d2];
            b3 = base64Alphabet [d3];
            b4 = base64Alphabet [d4];

            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);
        }

        if (! isData ((d1 = base64Data [dataIndex ++])) ||! isData ((d2 = base64Data [dataIndex ++]))) {
            return null;//if found "no data" just return null
        }

        b1 = base64Alphabet[d1];
        b2 = base64Alphabet[d2];

        d3 = base64Data [dataIndex ++];
        d4 = base64Data [dataIndex ++];
        if (!isData((d3)) || !isData((d4))) {//Check if they are PAD characters
            if (isPad(d3) && isPad(d4)) {
                if ((b2 & 0xf) != 0)//last 4 bits should be zero
                {
                    return null;
                }
                byte[] tmp = new byte[i * 3 + 1];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
                return tmp;
            } else if (!isPad(d3) && isPad(d4)) {
                b3 = base64Alphabet [d3];
                if ((b3 & 0x3) != 0)//last 2 bits should be zero
                {
                    return null;
                }
                byte[] tmp = new byte[i * 3 + 2];
                System.arraycopy(decodedData, 0, tmp, 0, i * 3);
                tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
                tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
                return tmp;
            } else {
                return null;
            }
        } else { //No PAD e.g 3cQl
            b3 = base64Alphabet [d3];
            b4 = base64Alphabet [d4];
            decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);
            decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
            decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);

        }

        return decodedData;
    }

    /**
     * remove WhiteSpace from MIME containing encoded Base64 data.
     *
     * @param data  the byte array of base64 data (with WS)
     * @return      the new length
     */
    private static int removeWhiteSpace(char[] data) {
        if (data == null) {
            return 0;
        }

        // count characters that's not whitespace
        int newSize = 0;
        int len = data.length;
        for (int i = 0; i < len; i++) {
            if (!isWhiteSpace(data[i])) {
                data[newSize++] = data[i];
            }
        }
        return newSize;
    }
}

3.aes encryption: Advanced Encryption Standard (English: Advanced Encryption Standard , abbreviation: AES )

It is mainly used to decrypt the parameters passed by Android and ios when writing the interface. The code is as follows:

public class AesSecret {
	/*
     * The key used for encryption can be composed of 26 letters and numbers. The AES-128-CBC encryption mode is used here, and the key needs to be 16 bits.
     */
    private final static String sKey = "runshengxinjishu";  //密钥runshengxinjishu
    private final static String ivParameter = "2015040720150407"; //Vector offset -- using CBC mode, a vector iv is required, which can increase the strength of the encryption algorithm //2015040720150407
    
    /** Aes encryption algorithm
      * @Description AesSecret.java	
      * @param sSrc encrypted string
      * @return					
      * @author liz
      *@date May 23, 2017 at 7:07:33 PM
     */
    public static String encrypt(String sSrc) throws Exception{
    	Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());// When using CBC mode, a vector iv is required to increase the strength of the encryption algorithm
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        //return new BASE64Encoder().encode(encrypted);// BASE64 is used for transcoding here.
        return Base64.encodeBase64String(encrypted);//Use commons.codec to encrypt
       // return encrypted;
       
    }

    /** Aes decryption algorithm
      * @Description AesSecret.java	
      * @param sSrc // decrypt the string
      * @return					
      * @author liz
      *@date May 23, 2017 at 7:07:52 PM
     */
    public static String decrypt(String sSrc) throws Exception{
    	 byte[] raw = sKey.getBytes("ASCII");
         SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
         Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
         IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
         cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
         //byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);// Decrypt with base64 first
         byte[] encrypted1 = Base64.decodeBase64(new String(sSrc).getBytes());//Use commons.codec to encrypt  
         //byte[] encrypted1 =AesSecret.parseHexStr2Byte(sSrc);
         byte[] original = cipher.doFinal(encrypted1);
         String originalString = new String(original, "utf-8");
         return originalString;
    }
		
	/** Convert binary to hexadecimal
	 * @param buf
	 * @return
	 */  
	public static String parseByte2HexStr (byte buf []) {  
	        StringBuffer sb = new StringBuffer();  
	        for (int i = 0; i < buf.length; i++) {  
	                String hex = Integer.toHexString(buf[i] & 0xFF);  
	                if (hex.length() == 1) {  
	                        hex = '0' + hex;  
	                }  
	                sb.append(hex.toUpperCase());  
	        }  
	        return sb.toString();  
	}  
	
	/** Convert hexadecimal to binary
	 * @param hexStr
	 * @return
	 */  
	public static byte[] parseHexStr2Byte(String hexStr) {  
	        if (hexStr.length() < 1)  
	                return null;  
	        byte[] result = new byte[hexStr.length()/2];  
	        for (int i = 0;i< hexStr.length()/2; i++) {  
	                int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
	                int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);  
	                result[i] = (byte) (high * 16 + low);  
	        }  
	        return result;  
	}
	
	/** Get the encrypted parameters from the app and decrypt it into a json object
	  * @Description AesSecret.java	
	  * @param str //The encrypted string passed by the app
	  * @return					
	  * @author liz
	  *@date May 23, 2017 at 4:11:43 PM
	 */
	public static JSONObject getJson (String str) throws Exception{
		// decrypt  
			String DeString = decrypt(str);
			System.out.println("The decrypted string is: " + DeString);
			JSONObject json = new JSONObject(new String(DeString));
			return json;
	}
	
   public static void main(String[] args) throws Exception {
       // String to be encrypted
       String cSrc = "{userPhone:15555555555,passWord:111111}";
       
       // encrypt
       long lStart = System.currentTimeMillis();
       String enString = encrypt(cSrc);
       System.out.println("The encrypted string is: " + enString);

       long lUseTime = System.currentTimeMillis() - lStart;
       System.out.println("Encryption time: " + lUseTime + "milliseconds");
       // decrypt
       lStart = System.currentTimeMillis();
       String DeString = decrypt (enString);
       System.out.println("The decrypted string is: " + DeString);
       
       lUseTime = System.currentTimeMillis() - lStart;
       System.out.println("Decryption time: " + lUseTime + "milliseconds");
       
       //Directly test the encrypted string test
       String test = decrypt("6cDllG7cu7aF5ZAZ5hb2Mrpu2udrxxSF1ITfb0/4nvDuNj1D6m0QrIUrKHM+SKNC");
       System.out.println("The decrypted string is: " + test);
       JSONObject json = new JSONObject(new String(test));
       System.out.println(json.get("userPhone"));
   }

}

4. There are also some database encryption and Alipay encryption, which are not listed one by one. If you are interested, you can Baidu

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325792572&siteId=291194637