GHGL工具类代码

1.四舍五入保留两位小数

	public static double getdouble(double d){
		return (double)Math.round(d*100)/100;
	}

2.计算增减百分比

	/**
	 * 计算增减百分比
	 * @param x 本期
	 * @param y 同期
	 * @return
	 */
	public static String toPercent(double x , double y){
		String rst = null;
		if( y == 0){
			rst = " ";
		}else{
			if(x-y == 0){
				rst = "0.00%";
			}else{
				double fen = (x - y) / y ;
				DecimalFormat df1 = new DecimalFormat("##.00%");
				rst = df1.format(fen);
			}
		}
		return rst;		
	}

3.冒泡排序

	/**  
	 * 冒泡法排序<br/>  

	 * <li>比较相邻的元素。如果第一个比第二个大,就交换他们两个。</li>  
	 * <li>对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。在这一点,最后的元素应该会是最大的数。</li>  
	 * <li>针对所有的元素重复以上的步骤,除了最后一个。</li>  
	 * <li>持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。</li>  

	 *   
	 * @param numbers  
	 *            需要排序的数组  
	 */  
	public static void bubbleSort(double[] numbers) {   
	    double temp; // 记录临时中间值   
	    int size = numbers.length; // 数组大小   
	    for (int i = 0; i < size - 1; i++) {   
	        for (int j = i + 1; j < size; j++) {   
	            if (numbers[i] < numbers[j]) { // 交换两数的位置   
	                temp = numbers[i];   
	                numbers[i] = numbers[j];   
	                numbers[j] = temp;   
	            }   
	        }   
	    }   
	}

4.传入 1 ,返回 001

	/**
	 * 传入 1 ,返回 001
	 * @param str 字符串
	 * @return
	 */
    public static String pullZero(String str){
        if(str != null && !"".equals(str) && str.length() < 3) {
            int length = str.length();
            for(int i = 0; i < 3 - length; i++) {
                str = "0" + str;
            }
            return str;
        } else {
            return str;
        }
    }

5.计算百分比

	public static String goPercent(double x , double y){
		String rst = null;
		if( y == 0){
			rst = " ";
		}else{
			if(x == 0){
				rst = "0.00%";
			}else{
				double fen = x/y ;
				DecimalFormat df1 = new DecimalFormat("##.00%");
				rst = df1.format(fen);
			}
		}
		return rst;		
	}

6.后台 RSA AES 加密解密工具类代码

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SecureRandom;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;


public class EncryptionDecryption {
	
	static String pathKey = EncryptionDecryption.class.getClassLoader().getResource("RSAKey.txt").getPath();
	
	/** 密钥文件存储位置 */
	private static String RSAKeyStore = pathKey;
	
    /**
     * 日志记录器
     */
    public static Logger logger = Logger.getLogger(EncryptionDecryption.class);
    
	/**
	 * AES加密
	 * @param content  明文
	 * @param keyBytes 秘钥
	 * @param iv      偏移量
	 * @return   
	 */	
    public static String AES_CBC_Encrypt(String content, byte[] keyBytes, byte[] iv){  
          
        try{ 
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");  
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));  
            content = URLEncoder.encode(content,"UTF-8");   //用url编码
            byte[] result=cipher.doFinal(content.getBytes()); //加密
            return new String(Base64.encodeBase64(result),"UTF-8");
        }catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		} 
        return null;
    }
    
    /**
     * AES解密
     * @param content   密文
     * @param keyBytes  秘钥
     * @param iv        偏移量
     * @return          
     */
	public static String AES_CBC_Decrypt(String content, byte[] keyBytes, byte[] iv){  
          
        try{  
        	content = content.replaceAll(" ", "+");
        	byte[] decryptBaseData=Base64.decodeBase64(content.getBytes("utf-8"));
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
            Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding");  
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));  
            byte[] result=cipher.doFinal(decryptBaseData);  
            return URLDecoder.decode(new String(result),"utf-8");  
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
			e.printStackTrace();
		}   
        return null;  
    }
    
    /**
     * 字符串转为 byte[]
     * @param hexString
     * @return
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    
    /**
     * Convert char to byte
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
    
    /**
     * 解密由RSA加密的AES的key 和 iv
     * @param para
     * @return
     * @throws Exception
     */
    public static byte[] getValue(String param){
    	byte[] trueValue = null;
		try {
			if(!param.equals("") && param != null){
				byte[] KeyB = hexStringToBytes(param);
				KeyB = decrypt(getKeyPair().getPrivate(),KeyB);
				StringBuffer sbKey = new StringBuffer();
				sbKey.append(new String(KeyB));
				param = sbKey.reverse().toString();
				trueValue = URLDecoder.decode(param,"UTF-8").getBytes(); 
			}			
		} catch (Exception e) {
			//重要参数值
			logger.error("传入参数:" + "param: " + param);
			//异常说明
			logger.error("解密由RSA加密的AES的key 和 iv 失败,可能前台传入的aKey或者aIv为空");
			e.printStackTrace();
		}
		return trueValue; 
    }
    
    /**
     * 获取密钥文件中的公钥
     * @return
     */
    public String getPublicKey(){
    	Object publicKey = null;
    	String publicKEY = null;
		try {
			publicKey = getKeyPair().getPublic();
			publicKEY = (String) publicKey.toString().subSequence(36, 293);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return publicKEY;		
    }
    
    /**
     * RSA 生成密钥对
     * @return
     * @throws Exception
     */
	public static KeyPair generateKeyPair() throws Exception {
		try {
			KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
			final int KEY_SIZE = 1024;
			keyPairGen.initialize(KEY_SIZE, new SecureRandom());
			KeyPair keyPair = keyPairGen.generateKeyPair();
			FileOutputStream fos = new FileOutputStream(RSAKeyStore);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(keyPair);
			oos.close();
			fos.close();
			return keyPair;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 获取密钥对
	 * @return
	 * @throws Exception
	 */
	public static KeyPair getKeyPair() throws Exception {
		FileInputStream fis = new FileInputStream(RSAKeyStore);
		ObjectInputStream oos = new ObjectInputStream(fis);
		KeyPair kp = (KeyPair) oos.readObject();
		oos.close();
		fis.close();
		return kp;
	}

	/**
	 * 解密
	 * @param pk
	 * @param raw
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("static-access")
	private static byte[] decrypt(PrivateKey pk, byte[] raw) {
		try {
			Cipher cipher = Cipher.getInstance("RSA",
					new org.bouncycastle.jce.provider.BouncyCastleProvider());
			cipher.init(cipher.DECRYPT_MODE, pk);
			int blockSize = cipher.getBlockSize();
			ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
			int j = 0;

			while (raw.length - j * blockSize > 0) {
				bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
				j++;
			}
			return bout.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return raw;
	}
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值