CookieUtilEncryptUtil(各种加密算法)HttpUtil
Posted xiaofeng-fu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CookieUtilEncryptUtil(各种加密算法)HttpUtil相关的知识,希望对你有一定的参考价值。
1、CookieUtil
ublic class CookieUtil { // 默认缓存时间,单位/秒, 2H private static final int COOKIE_MAX_AGE = 60 * 60 * 2; // 保存路径,根路径 private static final String COOKIE_PATH = "/"; /** * 保存 * * @param response * @param key * @param value * @param ifRemember */ public static void set(HttpServletResponse response, String key, String value, boolean ifRemember) { int age = ifRemember?COOKIE_MAX_AGE:-1; set(response, key, value, null, COOKIE_PATH, age, true); } /** * 保存 * * @param response * @param key * @param value * @param maxAge */ private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) { Cookie cookie = new Cookie(key, value); if (domain != null) { cookie.setDomain(domain); } cookie.setPath(path); cookie.setMaxAge(maxAge); cookie.setHttpOnly(isHttpOnly); response.addCookie(cookie); } /** * 查询value * * @param request * @param key * @return */ public static String getValue(HttpServletRequest request, String key) { Cookie cookie = get(request, key); if (cookie != null) { return cookie.getValue(); } return null; } /** * 查询Cookie * * @param request * @param key */ private static Cookie get(HttpServletRequest request, String key) { Cookie[] arr_cookie = request.getCookies(); if (arr_cookie != null && arr_cookie.length > 0) { for (Cookie cookie : arr_cookie) { if (cookie.getName().equals(key)) { return cookie; } } } return null; } /** * 删除Cookie * * @param request * @param response * @param key */ public static void remove(HttpServletRequest request, HttpServletResponse response, String key) { Cookie cookie = get(request, key); if (cookie != null) { set(response, key, "", null, COOKIE_PATH, 0, true); } } }
2、EncryptUtil(各种加密算法)
public class EncryptUtil { private static final String MD5 = "MD5"; private static final String SHA1 = "SHA1"; private static final String HmacMD5 = "HmacMD5"; private static final String HmacSHA1 = "HmacSHA1"; private static final String DES = "DES"; private static final String AES = "AES"; /** * 编码格式;默认使用uft-8 */ public String charset = "utf-8"; /** * DES */ public int keysizeDES = 0; /** * AES */ public int keysizeAES = 128; public static volatile EncryptUtil me; private EncryptUtil() { //单例 } //双重锁 public static EncryptUtil getInstance() { if (me == null) { synchronized (EncryptUtil.class) { if (me == null) { me = new EncryptUtil(); } } } return me; } /** * 使用MessageDigest进行单向加密(无密码) * * @param res 被加密的文本 * @param algorithm 加密算法名称 * @return */ private String messageDigest(String res, String algorithm) { try { MessageDigest md = MessageDigest.getInstance(algorithm); byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset); return base64(md.digest(resBytes)); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 使用KeyGenerator进行单向/双向加密(可设密码) * * @param res 被加密的原文 * @param algorithm 加密使用的算法名称 * @param key 加密使用的秘钥 * @return */ private String keyGeneratorMac(String res, String algorithm, String key) { try { SecretKey sk = null; if (key == null) { KeyGenerator kg = KeyGenerator.getInstance(algorithm); sk = kg.generateKey(); } else { byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset); sk = new SecretKeySpec(keyBytes, algorithm); } Mac mac = Mac.getInstance(algorithm); mac.init(sk); byte[] result = mac.doFinal(res.getBytes()); return base64(result); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 使用KeyGenerator双向加密,DES/AES,注意这里转化为字符串的时候是将2进制转为16进制格式的字符串,不是直接转,因为会出错 * * @param res 加密的原文 * @param algorithm 加密使用的算法名称 * @param key 加密的秘钥 * @param keysize * @param isEncode * @return */ private String keyGeneratorES(String res, String algorithm, String key, int keysize, boolean isEncode) { try { KeyGenerator kg = KeyGenerator.getInstance(algorithm); if (keysize == 0) { byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset); kg.init(new SecureRandom(keyBytes)); } else if (key == null) { kg.init(keysize); } else { byte[] keyBytes = charset == null ? key.getBytes() : key.getBytes(charset); kg.init(keysize, new SecureRandom(keyBytes)); } SecretKey sk = kg.generateKey(); SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm); Cipher cipher = Cipher.getInstance(algorithm); if (isEncode) { cipher.init(Cipher.ENCRYPT_MODE, sks); byte[] resBytes = charset == null ? res.getBytes() : res.getBytes(charset); return parseByte2HexStr(cipher.doFinal(resBytes)); } else { cipher.init(Cipher.DECRYPT_MODE, sks); return new String(cipher.doFinal(parseHexStr2Byte(res))); } } catch (Exception e) { e.printStackTrace(); } return null; } private String base64(byte[] res) { return Base64.encode(res); } /** * 将二进制转换成16进制 */ 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(); } /** * 将16进制转换为二进制 */ 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; } /** * md5加密算法进行加密(不可逆) * * @param res 需要加密的原文 * @return */ public String MD5(String res) { return messageDigest(res, MD5); } /** * md5加密算法进行加密(不可逆) * * @param res 需要加密的原文 * @param key 秘钥 * @return */ public String MD5(String res, String key) { return keyGeneratorMac(res, HmacMD5, key); } /** * 使用SHA1加密算法进行加密(不可逆) * * @param res 需要加密的原文 * @return */ public String SHA1(String res) { return messageDigest(res, SHA1); } /** * 使用SHA1加密算法进行加密(不可逆) * * @param res 需要加密的原文 * @param key 秘钥 * @return */ public String SHA1(String res, String key) { return keyGeneratorMac(res, HmacSHA1, key); } /** * 使用DES加密算法进行加密(可逆) * * @param res 需要加密的原文 * @param key 秘钥 * @return */ public String DESencode(String res, String key) { return keyGeneratorES(res, DES, key, keysizeDES, true); } /** * 对使用DES加密算法的密文进行解密(可逆) * * @param res 需要解密的密文 * @param key 秘钥 * @return */ public String DESdecode(String res, String key) { return keyGeneratorES(res, DES, key, keysizeDES, false); } /** * 使用AES加密算法经行加密(可逆) * * @param res 需要加密的密文 * @param key 秘钥 * @return */ public String AESencode(String res, String key) { return keyGeneratorES(res, AES, key, keysizeAES, true); } /** * 对使用AES加密算法的密文进行解密 * * @param res 需要解密的密文 * @param key 秘钥 * @return */ public String AESdecode(String res, String key) { return keyGeneratorES(res, AES, key, keysizeAES, false); } /** * 使用异或进行加密 * * @param res 需要加密的密文 * @param key 秘钥 * @return */ public String XORencode(String res, String key) { byte[] bs = res.getBytes(); for (int i = 0; i < bs.length; i++) { bs[i] = (byte) ((bs[i]) ^ key.hashCode()); } return parseByte2HexStr(bs); } /** * 使用异或进行解密 * * @param res 需要解密的密文 * @param key 秘钥 * @return */ public String XORdecode(String res, String key) { byte[] bs = parseHexStr2Byte(res); for (int i = 0; i < bs.length; i++) { bs[i] = (byte) ((bs[i]) ^ key.hashCode()); } return new String(bs); } /** * 直接使用异或(第一调用加密,第二次调用解密) * * @param res 密文 * @param key 秘钥 * @return */ public int XOR(int res, String key) { return res ^ key.hashCode(); } /** * 使用Base64进行加密 * * @param res 密文 * @return */ public String Base64Encode(String res) { return Base64.encode(res.getBytes()); } /** * 使用Base64进行解密 * * @param res * @return */ public String Base64Decode(String res) { return new String(Base64.decode(res)); } public static void main(String[] args) { String s = EncryptUtil.getInstance().MD5("admin", "feng"); System.out.println(s); } }
3、HttpUtil
public class HttpUtil { /** * 发送get 网络请求 * * @param uri * @return */ public static String get(String uri) { CloseableHttpClient httpClient = null; HttpGet get = new HttpGet(uri); CloseableHttpResponse response = null; try { httpClient = HttpClients.createDefault(); response = httpClient.execute(get); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); return result; } else { return null; } } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * get * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception { HttpClient httpClient = wrapClient(host); HttpGet request = new HttpGet(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } return httpClient.execute(request); } /** * post form * * @param host * @param path * @param method * @param headers * @param querys * @param bodys * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, Map<String, String> bodys) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (bodys != null) { List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>(); for (String key : bodys.keySet()) { nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key))); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8"); formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8"); request.setEntity(formEntity); } return httpClient.execute(request); } /** * Post String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (StringUtils.isNotBlank(body)) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); } /** * Post stream * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPost request = new HttpPost(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); } /** * Put String * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, String body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (StringUtils.isNotBlank(body)) { request.setEntity(new StringEntity(body, "utf-8")); } return httpClient.execute(request); } /** * Put stream * * @param host * @param path * @param method * @param headers * @param querys * @param body * @return * @throws Exception */ public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers, Map<String, String> querys, byte[] body) throws Exception { HttpClient httpClient = wrapClient(host); HttpPut request = new HttpPut(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } if (body != null) { request.setEntity(new ByteArrayEntity(body)); } return httpClient.execute(request); } /** * Delete * * @param host * @param path * @param method * @param headers * @param querys * @return * @throws Exception */ public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers, Map<String, String> querys) throws Exception { HttpClient httpClient = wrapClient(host); HttpDelete request = new HttpDelete(buildUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { request.addHeader(e.getKey(), e.getValue()); } return httpClient.execute(request); } private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException { StringBuilder sbUrl = new StringBuilder(); sbUrl.append(host); if (!StringUtils.isBlank(path)) { sbUrl.append(path); } if (null != querys) { StringBuilder sbQuery = new StringBuilder(); for (Map.Entry<String, String> query : querys.entrySet()) { if (0 < sbQuery.length()) { sbQuery.append("&"); } if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) { sbQuery.append(query.getValue()); } if (!StringUtils.isBlank(query.getKey())) { sbQuery.append(query.getKey()); if (!StringUtils.isBlank(query.getValue())) { sbQuery.append("="); sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8")); } } } if (0 < sbQuery.length()) { sbUrl.append("?").append(sbQuery); } } return sbUrl.toString(); } private static HttpClient wrapClient(String host) { HttpClient httpClient = new DefaultHttpClient(); if (host.startsWith("https://")) { sslClient(httpClient); } return httpClient; } private static void sslClient(HttpClient httpClient) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] xcs, String str) { } public void checkServerTrusted(X509Certificate[] xcs, String str) { } }; ctx.init(null, new TrustManager[]{tm}, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = httpClient.getConnectionManager(); SchemeRegistry registry = ccm.getSchemeRegistry(); registry.register(new Scheme("https", 443, ssf)); } catch (KeyManagementException ex) { throw new RuntimeException(ex); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } }
以上是关于CookieUtilEncryptUtil(各种加密算法)HttpUtil的主要内容,如果未能解决你的问题,请参考以下文章