java web project garbled problem

When running locally, the Chinese is normal, but it is garbled when accessed through the client. To find the encoding format of tomcat, and then convert it into the required normal format (utf-8)

System.out.println(System.getProperty("file.encoding "));
String pStr = decrypt.encode(phlist);
System.out.println("After encryption:" + pStr);

String postStr = decrypt.decode(pStr);
postStr = new String(postStr.getBytes("GBK "), "UTF-8");
System.out.println("After decryption: "+ postStr );




test code


import java.io.UnsupportedEncodingException;
import java.security.Key;

import javax.crypto.Cipher;
import javax .crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

/**
* Created by Administrator on 2016/9/26 0026.
*/
public class AES {

    static final String algorithmStr = "AES/ECB/PKCS5Padding";

    private static final Object TAG = "AES";

    static private KeyGenerator keyGen;

    static private Cipher cipher;

    static boolean isInited = false;

    private static void init() {
        try {
            /* * Generate a KeyGenerator object for the specified algorithm.
             * This class provides the functionality of a (symmetric) key generator.
             *The key generator is constructed using one of the getInstance class methods of this class.
             *KeyGenerator objects are reusable, that is, after a key is generated,
             *the same KeyGenerator object can be reused to generate further keys.
             *There are two ways to generate keys: an algorithm-independent way, and an algorithm-specific way.
             *The only difference between the two is the initialization of the object:
             *Algorithm-independent initialization
             *All key generators have the concept of key length and source of randomness.
             *There is an init method in this KeyGenerator class that takes parameters for these two general concepts.
             *There is also an init method with only a keysize parameter that
             *uses the provider's SecureRandom implementation with the highest priority as the source of randomness
             * (if none of the installed providers provide a SecureRandom implementation, the system-supplied source of randomness is used).
             *The KeyGenerator class also provides an inti method that takes only a random source parameter.
             *Because no additional parameters are specified when the algorithm-independent init method above is called,
             it is * up to the provider to decide what to do with the algorithm-specific parameters (if any) that will be associated with each key.
             *Algorithm-specific initialization
             * In cases where an algorithm-specific parameter set already exists,
             *there are two init methods with an AlgorithmParameterSpec parameter.
             *One of the methods also has a SecureRandom parameter,
             *while the other method uses the installed high-priority provider's SecureRandom implementation as the source of randomness
             * (or as the system-provided source of randomness if none of the installed providers provide SecureRandom accomplish).
             *If the client does not explicitly initialize the KeyGenerator (by calling the init method),
             *each provider must provide (and document) default initialization.
             */
            keyGen = KeyGenerator.getInstance("AES");
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Initialize this key generator to have a certain key length.
        keyGen.init(128); //128-bit AES encryption
        try {
            // Generate a Cipher object that implements the specified conversion.
            cipher = Cipher.getInstance(algorithmStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //Identifies the initialized field
        isInited = true;
    }

    private static byte[] genKey() {
        if (!isInited) {
            init();
        }
        //First generate a secret key (SecretKey),
        //Then, through this secret key, return the key in the basic encoding format, if the key does not support encoding, return null .
        return keyGen.generateKey().getEncoded();
    }

    private static byte[] encrypt(byte[] content, byte[] keyBytes) {
        byte[] encryptedText = null;
        if (!isInited) {
            init();
        }
        /* *
         *Class SecretKeySpec
         *This class can be used to construct a SecretKey from a byte array,
         * without going through a (provider-based) SecretKeyFactory.
         * This class is only useful for raw keys that can be represented as a byte array and do not have any key parameter associated with them
         * Constructor Constructs a key from the given byte array.
         * This constructor does not check whether the given byte array specifies an algorithm's key.
         */
        Key key = new SecretKeySpec(keyBytes, "AES");
        try {
            // Initialize this cipher with the key.
            cipher.init(Cipher.ENCRYPT_MODE, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //Encrypt or decrypt data by single-part operation, or end a multi-part operation. (I don't know what it means)
            encryptedText = cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encryptedText;
    }

    private static byte[] encrypt(String content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);//algorithmStr
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);//   ʼ
            byte[] result = cipher.doFinal(byteContent);
            return result; //
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] decrypt(byte[] content, String password) {
        try {
            byte[] keyStr = getKey(password);
            SecretKeySpec key = new SecretKeySpec(keyStr, "AES");
            Cipher cipher = Cipher.getInstance(algorithmStr);//algorithmStr
            cipher.init(Cipher.DECRYPT_MODE, key);//   ʼ
            byte[] result = cipher.doFinal(content);
            return result; //
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] getKey(String password) {
        byte[] rByte = null;
        if (password!=null) {
            rByte = password.getBytes();
        }else{
            rByte = new byte[24];
        }
        return rByte;
    }

    /**
     * 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;
    }

    //注意: 这里的password(秘钥必须是16位的)
    private static final String keyBytes = "abcdefgabcdefg12";

    /**
     *Encryption
     */
    public static String encode(String content){
        //The encrypted byte array is converted into a hexadecimal string for output
        return parseByte2HexStr(encrypt(content, keyBytes));
    }

    /**
     *decryption
     * /
    public static String decode(String content){
        //Before decryption, convert the input string into a binary byte array according to hexadecimal, and enter
        byte[] as the content to be decrypted b = decrypt(parseHexStr2Byte(content) , keyBytes);
        return new String(b);
    }

    //Test case
    public static void test1() throws UnsupportedEncodingException{
    System.out.println(System.getProperty("file.encoding"));
        String content = new String(" Zhang San".getBytes(),"utf-8");
        String pStr = encode(content );
        System.out.println("加密前:"+content);
        System.out.println("加密后:" + pStr);

        String postStr = decode(pStr);
        System.out.println("解密后:"+ postStr );
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        test1();
    }
}

Guess you like

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