AES encryption does not work properly under linux

package com.lz.core.fe.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import com.lz.core.fe.exception.BlankException;
/**
 * ASE encryption
 * @ClassName ASEUtil.java
 * @author longload
 *@date Jan 13, 2016 at 1:47:27 PM
 */
public class ASEUtil {
	private static final String DEFAULT_CODE="utf-8";
	private static Logger logger =Logger.getLogger("ASEUtil");
	public static void main(String[] args) throws Exception {
		 String content = "{'name':'Li Jian','userId':'3b8ab8b7-510a-4837-b77e-4061976a295c'}";//String to be encrypted
        String key = "cypt";  //appNbr
        //encryption   
       System.out.println(content.length()+":加密前:" + content);   
       String aa = encryptUrlStr(content, key);  
       System.out.println("aa:"+aa);  
         String bb="WAdxm1Bmd1Yp7yM_ns4jEO36TimCrAWKuir7SitedvWBHTO1mCqHStRxKrBxnKv8i-cGEnb-W-tr8PGUupuEzmrG7TuCfdlinOnlA5DpG3A=";
         System.out.println("bb:"+bb);  
        // decrypt   
       System.out.println("After decryption: " + decryptUrlStr(bb,key));   
		
	}
	/**
	 * Encrypt the string into a string that can be transmitted by url
	 * @param content encrypted content
	 * @param key key
	 * @return
	 *@date Jan 13, 2016 at 1:43:46 PM
	 * @author longload
	 */
	  public static String encryptUrlStr(String content, String key)throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
		  logger.log(Level.INFO,content);
		  byte[] encryptResult=encrypt(content,key);
		  logger.log(Level.INFO,"baseBefore:"+new String(encryptResult,DEFAULT_CODE));
		   encryptResult= Base64.getUrlEncoder().encode(encryptResult);
		   String str =new String(encryptResult,DEFAULT_CODE);
		   logger.log(Level.INFO,"baseAfter:"+str);
		   return str;
	  }
	  /**
	   * Decrypt the string transmitted by url and return String
	   * @param content decrypted content
	   * @param key key
	   * @return
	   *@date Jan 13, 2016 at 1:38:41 PM
	   * @author longload
	 * @throws BadPaddingException
	 * @throws IllegalBlockSizeException
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 * @throws InvalidKeyException
	 * @throws UnsupportedEncodingException
	   */
	  public static String decryptUrlStr(String content, String key) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
		  if (content==null) {
			  throw new BlankException("Decrypted content is empty!");
		  }
		  logger.log(Level.INFO,"debaseBefore:"+content);
		  byte[] contentBytes=Base64.getUrlDecoder().decode(content);
		  logger.log(Level.INFO,"debaseAfter:"+new String(contentBytes,DEFAULT_CODE));
		  byte[] decryptResult= decrypt(contentBytes, key);
		  String str=new String(decryptResult,DEFAULT_CODE);
		  logger.log(Level.INFO,"decrypt:"+str);
		  return str;
	  }
	 /**
     * Encrypted
    *  
     * @param content the content to be encrypted
    * @param key encryption password
    * @return
	 * @throws NoSuchPaddingException
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 * @throws InvalidKeyException
	 * @throws BadPaddingException
	 * @throws IllegalBlockSizeException
     */   
    public static byte[] encrypt(String content, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {   
    				SecretKey secretKey =getKey(key);
                    byte[] enCodeFormat = secretKey.getEncoded();
                    SecretKeySpec secretKeyspec = new SecretKeySpec(enCodeFormat, "AES");   
                    Cipher cipher = Cipher.getInstance("AES");// create a cipher   
                    byte[] byteContent = content.getBytes(DEFAULT_CODE);   
                    cipher.init(Cipher.ENCRYPT_MODE, secretKeyspec);//Initialization   
                    byte[] result = cipher.doFinal(byteContent);   
                    return result; // encryption   
    }  
    /**
     * Get decryption key
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     *@date Jan 15, 2016 at 2:33:47 PM
     * @author longload
     */
    public static SecretKey getKey(String key) throws NoSuchAlgorithmException, UnsupportedEncodingException {
   try {         
            KeyGenerator _generator = KeyGenerator.getInstance( "AES" );
            _generator.init(128, new SecureRandom(strKey.getBytes()));
                return _generator.generateKey();
        }  catch (Exception e) {
             throw new RuntimeException( "An exception occurred while initializing the key" );
        }
         return   _generator.generateKey();  
     }
    /** decrypt
     * @param content content to be decrypted
     * @param key decryption key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     * @throws UnsupportedEncodingException
      */   
     public static byte[] decrypt(byte[] content, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {   
                      SecretKey secretKey =getKey(key);   
                      byte[] enCodeFormat = secretKey.getEncoded();   
                      SecretKeySpec secretKeySpec = new SecretKeySpec(enCodeFormat, "AES");               
                      Cipher cipher = Cipher.getInstance("AES");// create a cipher   
                     cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);//Initialization   
                     byte[] result = cipher.doFinal(content);   
                     return result; // encryption   
     }  
       
       
     /**
      * 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;   
       }   
     
}

Works fine under Windows but will fail under Linux

 Replace the getKey method with the following:

public static SecretKey getKey(String key) throws NoSuchAlgorithmException, UnsupportedEncodingException {
    	 KeyGenerator kgen = KeyGenerator.getInstance("AES");   
         SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
         secureRandom.setSeed(key.getBytes(DEFAULT_CODE));
         kgen.init(128, secureRandom);
         return   kgen.generateKey();  
     }

 

reason:

The SecureRandom implementation is completely dependent on the internal state of the operating system itself, unless the caller calls the setSeed (using the padding method to make it fixed) method after calling the getInstance method; this implementation generates the same key every time on windows, but in solaris Or different on some linux systems. 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327106023&siteId=291194637