| @@ -0,0 +1,102 @@ | |||
| package com.simple.utils; | |||
| import org.bouncycastle.jce.provider.BouncyCastleProvider; | |||
| import org.bouncycastle.util.encoders.Base64; | |||
| import org.slf4j.Logger; | |||
| import org.slf4j.LoggerFactory; | |||
| import javax.crypto.Cipher; | |||
| import javax.crypto.spec.IvParameterSpec; | |||
| import javax.crypto.spec.SecretKeySpec; | |||
| import java.security.Key; | |||
| import java.security.Security; | |||
| import java.util.Arrays; | |||
| public class AesUtil { | |||
| private static final Logger logger = LoggerFactory.getLogger(AesUtil.class); | |||
| /** | |||
| * 加密 | |||
| * 模式:AES/CBC/PKCS7Padding | |||
| * | |||
| * @param encodeRules 秘钥 | |||
| * @param content 加密串 | |||
| * @return | |||
| */ | |||
| public static String AESEncode(String encodeRules, String content, String ivParameter) throws Exception { | |||
| int base = 16; | |||
| byte[] keybyte = encodeRules.getBytes("UTF-8"); | |||
| if (keybyte.length % base != 0) { | |||
| int groups = keybyte.length / base + (keybyte.length % base != 0 ? 1 : 0); | |||
| byte[] temp = new byte[groups * base]; | |||
| Arrays.fill(temp, (byte) 0); | |||
| System.arraycopy(keybyte, 0, temp, 0, keybyte.length); | |||
| keybyte = temp; | |||
| } | |||
| // 初始化 | |||
| Security.addProvider(new BouncyCastleProvider()); | |||
| // 转化成JAVA的密钥格式 | |||
| Key key = new SecretKeySpec(keybyte, "AES"); | |||
| try | |||
| { | |||
| // 初始化cipher | |||
| Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); | |||
| cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivParameter.getBytes())); | |||
| byte[] encryptedText = cipher.doFinal(content.getBytes()); | |||
| return new String(new Base64().encode(encryptedText)).replaceAll("\r\n", ""); | |||
| } catch ( | |||
| Exception e) | |||
| { | |||
| logger.info("AESEncode error", e); | |||
| } | |||
| return null; | |||
| } | |||
| /** | |||
| * 解密 | |||
| * | |||
| * @param encodeRules 秘钥 | |||
| * @param content 解密串 | |||
| * @return | |||
| */ | |||
| public static String AESDecode(String encodeRules, String content, String ivParameter) throws Exception { | |||
| try { | |||
| // 判断Key是否正确 | |||
| if (encodeRules == null) { | |||
| logger.info("Key为空null"); | |||
| return null; | |||
| } | |||
| // 判断Key是否为16位 | |||
| if (encodeRules.length() != 16) { | |||
| logger.info("Key长度不是16位"); | |||
| return null; | |||
| } | |||
| byte[] raw = encodeRules.getBytes("UTF-8"); | |||
| Security.addProvider(new BouncyCastleProvider()); | |||
| SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); | |||
| Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); | |||
| IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes()); | |||
| cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); | |||
| try { | |||
| byte[] encrypted1 = new Base64().decode(content);//先用base64解密 | |||
| byte[] original = cipher.doFinal(encrypted1); | |||
| String originalString = new String(original); | |||
| return originalString; | |||
| } catch (Exception e) { | |||
| logger.info(e.toString()); | |||
| return null; | |||
| } | |||
| } catch (Exception ex) { | |||
| logger.info(ex.toString()); | |||
| return null; | |||
| } | |||
| } | |||
| } | |||
| @@ -0,0 +1,36 @@ | |||
| package com.simple.utils; | |||
| import javax.crypto.Mac; | |||
| import javax.crypto.spec.SecretKeySpec; | |||
| public class HMACSHA256 { | |||
| public static String byteArrayToHexString(byte[] b) { | |||
| StringBuilder hs = new StringBuilder(); | |||
| String stmp; | |||
| for (int n = 0; b != null && n < b.length; n++) { | |||
| stmp = Integer.toHexString(b[n] & 0XFF); | |||
| if (stmp.length() == 1) | |||
| hs.append('0'); | |||
| hs.append(stmp); | |||
| } | |||
| return hs.toString().toLowerCase(); | |||
| } | |||
| public static String sha256_HMAC(String message, String secret) { | |||
| String hash = ""; | |||
| try { | |||
| Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); | |||
| SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256"); | |||
| sha256_HMAC.init(secret_key); | |||
| byte[] bytes = sha256_HMAC.doFinal(message.getBytes()); | |||
| hash = byteArrayToHexString(bytes); | |||
| System.out.println(hash); | |||
| } catch (Exception e) { | |||
| System.out.println("Error HmacSHA256 ===========" + e.getMessage()); | |||
| } | |||
| return hash; | |||
| } | |||
| } | |||
| @@ -0,0 +1,167 @@ | |||
| package com.simple.utils; | |||
| import org.apache.http.*; | |||
| import org.apache.http.client.HttpClient; | |||
| import org.apache.http.client.entity.UrlEncodedFormEntity; | |||
| import org.apache.http.client.methods.CloseableHttpResponse; | |||
| import org.apache.http.client.methods.HttpGet; | |||
| import org.apache.http.client.methods.HttpPost; | |||
| import org.apache.http.entity.StringEntity; | |||
| import org.apache.http.impl.client.CloseableHttpClient; | |||
| import org.apache.http.impl.client.DefaultHttpClient; | |||
| import org.apache.http.impl.client.HttpClients; | |||
| import org.apache.http.message.BasicNameValuePair; | |||
| import org.apache.http.protocol.HTTP; | |||
| import org.apache.http.util.EntityUtils; | |||
| import java.io.BufferedReader; | |||
| import java.io.IOException; | |||
| import java.io.InputStreamReader; | |||
| import java.net.URI; | |||
| import java.util.ArrayList; | |||
| import java.util.Iterator; | |||
| import java.util.List; | |||
| import java.util.Map; | |||
| import java.util.logging.Logger; | |||
| /** | |||
| * @author | |||
| * @date | |||
| * HttpClient工具类 | |||
| */ | |||
| public class HttpUtil { | |||
| private static Logger logger = Logger.getLogger(String.valueOf(HttpUtil.class)); | |||
| /** | |||
| * get请求 | |||
| * @return | |||
| */ | |||
| public static String doGet(String url) { | |||
| try { | |||
| HttpClient client = new DefaultHttpClient(); | |||
| //发送get请求 | |||
| HttpGet request = new HttpGet(url); | |||
| HttpResponse response = client.execute(request); | |||
| /**请求发送成功,并得到响应**/ | |||
| if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { | |||
| /**读取服务器返回过来的json字符串数据**/ | |||
| String strResult = EntityUtils.toString(response.getEntity()); | |||
| return strResult; | |||
| } | |||
| } | |||
| catch (IOException e) { | |||
| e.printStackTrace(); | |||
| } | |||
| return null; | |||
| } | |||
| /** | |||
| * post请求(用于key-value格式的参数) | |||
| * @param url | |||
| * @param params | |||
| * @return | |||
| */ | |||
| public static String doPost(String url, Map params){ | |||
| BufferedReader in = null; | |||
| try { | |||
| // 定义HttpClient | |||
| HttpClient client = new DefaultHttpClient(); | |||
| // 实例化HTTP方法 | |||
| HttpPost request = new HttpPost(); | |||
| request.setURI(new URI(url)); | |||
| //设置参数 | |||
| List<NameValuePair> nvps = new ArrayList<NameValuePair>(); | |||
| for (Iterator iter = params.keySet().iterator(); iter.hasNext();) { | |||
| String name = (String) iter.next(); | |||
| String value = String.valueOf(params.get(name)); | |||
| nvps.add(new BasicNameValuePair(name, value)); | |||
| //System.out.println(name +"-"+value); | |||
| } | |||
| request.setEntity(new UrlEncodedFormEntity(nvps,HTTP.UTF_8)); | |||
| HttpResponse response = client.execute(request); | |||
| int code = response.getStatusLine().getStatusCode(); | |||
| if(code == 200){ //请求成功 | |||
| in = new BufferedReader(new InputStreamReader(response.getEntity() | |||
| .getContent(),"utf-8")); | |||
| StringBuffer sb = new StringBuffer(""); | |||
| String line = ""; | |||
| String NL = System.getProperty("line.separator"); | |||
| while ((line = in.readLine()) != null) { | |||
| sb.append(line + NL); | |||
| } | |||
| in.close(); | |||
| return sb.toString(); | |||
| } | |||
| else{ // | |||
| System.out.println("状态码:" + code); | |||
| return null; | |||
| } | |||
| } | |||
| catch(Exception e){ | |||
| e.printStackTrace(); | |||
| return null; | |||
| } | |||
| } | |||
| /** | |||
| * post请求(用于请求json格式的参数) | |||
| * @param url | |||
| * @param params | |||
| * @return | |||
| */ | |||
| public static String doPost(String url, String params) throws Exception { | |||
| CloseableHttpClient httpclient = HttpClients.createDefault(); | |||
| HttpPost httpPost = new HttpPost(url);// 创建httpPost | |||
| httpPost.setHeader("Accept", "application/json"); | |||
| httpPost.setHeader("Content-Type", "application/json"); | |||
| String charSet = "UTF-8"; | |||
| StringEntity entity = new StringEntity(params, charSet); | |||
| httpPost.setEntity(entity); | |||
| CloseableHttpResponse response = null; | |||
| try { | |||
| response = httpclient.execute(httpPost); | |||
| StatusLine status = response.getStatusLine(); | |||
| int state = status.getStatusCode(); | |||
| if (state == HttpStatus.SC_OK) { | |||
| HttpEntity responseEntity = response.getEntity(); | |||
| String jsonString = EntityUtils.toString(responseEntity); | |||
| return jsonString; | |||
| } | |||
| else{ | |||
| logger.info("请求返回:"+state+"("+url+")"); | |||
| } | |||
| } | |||
| finally { | |||
| if (response != null) { | |||
| try { | |||
| response.close(); | |||
| } catch (IOException e) { | |||
| e.printStackTrace(); | |||
| } | |||
| } | |||
| try { | |||
| httpclient.close(); | |||
| } catch (IOException e) { | |||
| e.printStackTrace(); | |||
| } | |||
| } | |||
| return null; | |||
| } | |||
| } | |||
| @@ -0,0 +1,63 @@ | |||
| package com.simple.utils; | |||
| import org.apache.commons.codec.binary.Base64; | |||
| import javax.crypto.Cipher; | |||
| import java.io.ByteArrayOutputStream; | |||
| import java.security.Key; | |||
| import java.security.KeyFactory; | |||
| import java.security.spec.X509EncodedKeySpec; | |||
| public class RsaUtil { | |||
| public static final String KEY_ALGORITHM = "RSA"; | |||
| public static final String PUBLIC_KEY = //"-----BEGIN PUBLIC KEY-----" + | |||
| "MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAvh8j/zagfxQdnSh5OIic" + | |||
| "MzN+MuRuWQJPjgu4Gza4+gX3j5Ln2xNDBOTjpwyuLBjh/JcBd1cGO3lAaKCwcaix" + | |||
| "smhTq56wVXXUMgDiAChu4ud8FSvRc8G8tdZAirKVAIi3NW+/pYgpWBs/0wnF8hz4" + | |||
| "8no4pyJHl9Jc1LH3VNIMz8vqzKUPc4ack4pFUXlcNj6C+sBlaurmI4/vwLqNxBGs" + | |||
| "7/zyM7dv6oy3DSU/Y1qBArM1YPjfL2dNun8rmtPgJvlPwXqA7uoHPwQ2Ym3aUn59" + | |||
| "pkS7QI6IE8uuqNkfSte8BXLd2nIqPLFxLYLDmdll7eoyRblHcHqAYSj8stK6StC7" + | |||
| "DNryNKEjTEwbgf9trUI0uvF1pfgTy2gpclnY69FtD/m0+FvLyorMq+nmBqYMjka5" + | |||
| "K0txDQJPOa7gsi//uXd/cJW2SAXY9MSO1AfMi8Xq/YKRQzN9FW5iapskXFHca7uX" + | |||
| "g5NhH7flr6DW+QInFlpoN6WIEAuDF1aj4O49Ikm3WxwhTqnvEkdSCfivpYQkp9Sh" + | |||
| "4kQ/SQdxuT7VX+Nz6k+uMx2z4cySk33bHi0KoHbA9QFGg/54Qd0+eU4qZnd4mrgh" + | |||
| "hH7/QQhL7Z9eF1U5UPrsHq2Vq3rEnN+tYQ26AuKeU8vzTxBrC/SxC6C/SMFt3f/Y" + | |||
| "nuFh1UnNJZleZwyQt+ZdGO0CAwEAAQ=="; | |||
| //"-----END PUBLIC KEY-----"; | |||
| private static final int MAX_ENCRYPT_BLOCK = 117; | |||
| public static String RSAEncode(byte[] data, String publickey) | |||
| throws Exception { | |||
| byte[] keyBytes = Base64.decodeBase64(publickey); | |||
| X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); | |||
| KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); | |||
| Key publicK = keyFactory.generatePublic(x509KeySpec); | |||
| // 对数据加密 | |||
| Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); | |||
| cipher.init(Cipher.ENCRYPT_MODE, publicK); | |||
| int inputLen = data.length; | |||
| ByteArrayOutputStream out = new ByteArrayOutputStream(); | |||
| int offSet = 0; | |||
| byte[] cache; | |||
| int i = 0; | |||
| // 对数据分段加密 | |||
| while (inputLen - offSet > 0) { | |||
| if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { | |||
| cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); | |||
| } else { | |||
| cache = cipher.doFinal(data, offSet, inputLen - offSet); | |||
| } | |||
| out.write(cache, 0, cache.length); | |||
| i++; | |||
| offSet = i * MAX_ENCRYPT_BLOCK; | |||
| } | |||
| byte[] encryptedData = out.toByteArray(); | |||
| out.close(); | |||
| return Base64.encodeBase64String(encryptedData); | |||
| } | |||
| } | |||