list = wifiManager.getScanResults();
270 | if (list != null) {
271 | for (int i = 0; i < list.size(); i++) {
272 | scanResult = list.get(i);
273 | if (scanResult.BSSID.equals(bssid)) {
274 | break;
275 | }
276 | }
277 | }
278 | return scanResult;
279 | }
280 |
281 | /**
282 | * 获取wifi连接信息
283 | *
284 | * @param context the context
285 | * @return the wifi connection info
286 | */
287 | public static WifiInfo getWifiConnectionInfo(Context context) {
288 | WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
289 | return wifiManager.getConnectionInfo();
290 | }
291 | }
292 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/SPUtils.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 | import android.content.SharedPreferences.Editor;
6 |
7 | /**
8 | * The type Sp utils.
9 | */
10 | public class SPUtils {
11 |
12 | /**
13 | * 存储SharedPreferences值
14 | *
15 | * @param context the context
16 | * @param filename the filename
17 | * @param key the key
18 | * @param object the object
19 | */
20 | public static void setSP(Context context, String filename, String key, Object object) {
21 | String type = object.getClass().getSimpleName();
22 | String packageName = context.getPackageName();
23 | SharedPreferences sp = context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
24 | Editor edit = sp.edit();
25 | if ("String".equals(type)) {
26 | edit.putString(key, (String) object);
27 | } else if ("Integer".equals(type)) {
28 | edit.putInt(key, (Integer) object);
29 | } else if ("Boolean".equals(type)) {
30 | edit.putBoolean(key, (Boolean) object);
31 | } else if ("Float".equals(type)) {
32 | edit.putFloat(key, (Float) object);
33 | } else if ("Long".equals(type)) {
34 | edit.putLong(key, (Long) object);
35 | }
36 | edit.apply();
37 | }
38 |
39 | /**
40 | * 获取SharedPreferences值
41 | *
42 | * @param context the context
43 | * @param key the key
44 | * @param defaultObject the default object
45 | * @return the sp
46 | */
47 | public static Object getSp(Context context, String key, Object defaultObject) {
48 | String type = defaultObject.getClass().getSimpleName();
49 | String packageName = context.getPackageName();
50 | SharedPreferences sp = context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
51 | if ("String".equals(type)) {
52 | return sp.getString(key, (String) defaultObject);
53 | } else if ("Integer".equals(type)) {
54 | return sp.getInt(key, (Integer) defaultObject);
55 | } else if ("Boolean".equals(type)) {
56 | return sp.getBoolean(key, (Boolean) defaultObject);
57 | } else if ("Float".equals(type)) {
58 | return sp.getFloat(key, (Float) defaultObject);
59 | } else if ("Long".equals(type)) {
60 | return sp.getLong(key, (Long) defaultObject);
61 | }
62 | return null;
63 | }
64 |
65 | /**
66 | * 清除所有的SP值
67 | *
68 | * @param context the context
69 | */
70 | public static void cleanAllSP(Context context) {
71 | String packageName = context.getPackageName();
72 | SharedPreferences sp = context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
73 | Editor editor = sp.edit();
74 | editor.clear();
75 | editor.apply();
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/VerificationUtils.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a;
2 |
3 | import android.text.TextUtils;
4 |
5 | import java.text.SimpleDateFormat;
6 | import java.util.regex.Pattern;
7 |
8 | /**
9 | * https://github.com/sharinghuang/ASRabbit/blob/7350ea1c212946633316d36760c7088728dc2730/baselib/src/main/java/com/ht/baselib/utils/FormatVerificationUtils.java
10 | */
11 | public class VerificationUtils {
12 | /**
13 | * 判断真实姓名是否格式正确
14 | *
15 | * 要求:真实姓名可以是汉字,也可以是字母,但是不能两者都有,也不能包含任何符号和数字
16 | * 注意:1.如果是英文名,可以允许英文名字中出现空格
17 | * 2.英文名的空格可以是多个,但是不能连续出现多个
18 | * 3.汉字不能出现空格
19 | *
20 | *
21 | * @param value 真实姓名字符串
22 | * @return true为正确,false为错误
23 | */
24 | public static boolean matcherRealName(String value) {
25 | String regex = "^([\\u4e00-\\u9fa5]+|([a-zA-Z]+\\s?)+)$";
26 | return testRegex(regex, value);
27 | }
28 |
29 | /**
30 | * 判断手机号码是否格式正确
31 | *
32 | * @param value 手机号码字符串
33 | * @return true为正确,false为错误
34 | */
35 | public static boolean matcherPhoneNum(String value) {
36 | // 匹配11数字,并且13-19开头
37 | String regex = "^((13[0-9])|(14[57])|(15[^4])|(17[013678])|(18[0-9]))\\d{8}$";
38 | return testRegex(regex, value);
39 | }
40 |
41 | /**
42 | * 判断密码格式正确(必须输入6-12位非纯数字、英文的密码)
43 | *
44 | * @param value 密码字符串
45 | * @return true为正确,false为错误
46 | */
47 | public static boolean matcherPassword(String value) {
48 | // String regex = "^[a-zA-Z0-9]{6,12}$";// (6-12位字母或数字)
49 | String regex = "(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}";//(6-12位字母或数字,必须同时包含字母和数字)
50 | return testRegex(regex, value);
51 | }
52 |
53 | /**
54 | * 判断注册账号格式正确
55 | *
56 | * @param value 账号字符串
57 | * @return true为正确,false为错误
58 | */
59 | public static boolean matcherAccount(String value) {
60 | // (4-20位字符)
61 | String regex = "[\\u4e00-\\u9fa5a-zA-Z0-9\\-]{4,20}";
62 | return testRegex(regex, value);
63 | }
64 |
65 | /**
66 | * 判断邮箱格式正确
67 | *
68 | * @param value 邮箱字符串
69 | * @return true为正确,false为错误
70 | */
71 | public static boolean matcherEmail(String value) {
72 | // String regex = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)" +
73 | // "+[a-zA-Z]{2,}$";
74 | String regex = "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+" +
75 | "(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+" +
76 | "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$";
77 | return testRegex(regex, value);
78 | }
79 |
80 | /**
81 | * 判断IP地址格式正确
82 | *
83 | * @param value IP字符串
84 | * @return true为正确,false为错误
85 | */
86 | public static boolean matcherIP(String value) {
87 | String regex = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\" +
88 | "d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\" +
89 | "d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
90 | return testRegex(regex, value.toLowerCase());
91 | }
92 |
93 | /**
94 | * 判断身份证格式正确性
95 | *
96 | * @param value 身份证字符串
97 | * @return true为正确,false为错误
98 | */
99 |
100 | public static boolean matcherIdentityCard(String value) {
101 | // String regex = "^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|" +
102 | // "(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|" +
103 | // "\\d{3}[Xx])$)$";
104 | // return testRegex(regex, value);
105 | IDCardTester idCardTester = new IDCardTester();
106 | return idCardTester.test(value);
107 | }
108 |
109 | /**
110 | * 判断网址格式正确性 支持http,https,ftp
111 | *
112 | * @param value 网址字符串
113 | * @return true为正确,false为错误
114 | */
115 | public static boolean matcherUrl(String value) {
116 | String regex = "^(([hH][tT]{2}[pP][sS]?)|([fF][tT][pP]))\\:\\/\\/[wW]{3}\\.[\\w-]+\\.\\w{2,4}(\\/.*)?$";
117 | return testRegex(regex, value.toLowerCase());
118 | }
119 |
120 |
121 | /**
122 | * 中国民用车辆号牌
123 | *
124 | * @param value 车牌号码
125 | * @return true为正确,false为错误
126 | */
127 | public static boolean matcherVehicleNumber(String value) {
128 | String regex = "^[京津晋冀蒙辽吉黑沪苏浙皖闽赣鲁豫鄂湘粤桂琼川贵云藏陕甘青宁新渝]?[A-Z][A-HJ-NP-Z0-9学挂港澳练]{5}$";
129 | return testRegex(regex, value.toLowerCase());
130 | }
131 | // 公用方法
132 | //============================================================
133 |
134 | /**
135 | * 身份证校验
136 | *
137 | * 根据〖中华人民共和国国家标准 GB 11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。
138 | * 地址码表示编码对象常住户口所在县(市、旗、区)的行政区划代码。
139 | * 出生日期码表示编码对象出生的年、月、日,其中年份用四位数字表示,年、月、日之间不用分隔符。
140 | * 顺序码表示同一地址码所标识的区域范围内,对同年、月、日出生的人员编定的顺序号。顺序码的奇数分给男性,偶数分给女性。
141 | * 校验码是根据前面十七位数字码,按照ISO 7064:1983.MOD 11-2校验码计算出来的检验码。
142 | * 出生日期计算方法。
143 | * 15位的身份证编码首先把出生年扩展为4位,简单的就是增加一个19或18,这样就包含了所有1800-1999年出生的人;
144 | * 2000年后出生的肯定都是18位的了没有这个烦恼,至于1800年前出生的,那啥那时应该还没身份证号这个东东,⊙﹏⊙b汗...
145 | * 下面是正则表达式:
146 | * 出生日期1800-2099 /(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])/
147 | * 身份证正则表达式 /^[1-9]\d{5}((1[89]|20)\d{2})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dx]$/i
148 | * 15位校验规则 6位地址编码+6位出生日期+3位顺序号
149 | * 18位校验规则 6位地址编码+8位出生日期+3位顺序号+1位校验位
150 | * 校验位规则 公式:∑(ai×Wi)(mod 11)……………………………………(1)
151 | * 公式(1)中:
152 | * i----表示号码字符从由至左包括校验码在内的位置序号;
153 | * ai----表示第i位置上的号码字符值;
154 | * Wi----示第i位置上的加权因子,其数值依据公式Wi=2^(n-1)(mod 11)计算得出。
155 | * i 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
156 | * Wi 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2 1
157 | *
158 | *
159 | * @author Yoojia.Chen (yoojia.chen@gmail.com)
160 | * @version version 2015-05-21
161 | * @since 2.0
162 | */
163 | private static class IDCardTester {
164 | public boolean test(String content) {
165 | if (TextUtils.isEmpty(content)) {
166 | return false;
167 | }
168 | final int length = content.length();
169 | if (15 == length) {
170 | try {
171 | return isOldCNIDCard(content);
172 | } catch (NumberFormatException e) {
173 | e.printStackTrace();
174 | return false;
175 | }
176 | } else if (18 == length) {
177 | return isNewCNIDCard(content);
178 | } else {
179 | return false;
180 | }
181 | }
182 |
183 | final int[] WEIGHT = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
184 |
185 | final char[] VALID = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
186 |
187 | public boolean isNewCNIDCard(String numbers) {
188 | //转换字符串中的字母为大写字母
189 | numbers = numbers.toUpperCase();
190 | int sum = 0;
191 | for (int i = 0; i < WEIGHT.length; i++) {
192 | final int cell = Character.getNumericValue(numbers.charAt(i));
193 | sum += WEIGHT[i] * cell;
194 | }
195 | int index = sum % 11;
196 | return VALID[index] == numbers.charAt(17);
197 | }
198 |
199 | public boolean isOldCNIDCard(String numbers) {
200 | //ABCDEFYYMMDDXXX
201 | String yymmdd = numbers.substring(6, 11);
202 | boolean aPass = numbers.equals(String.valueOf(Long.parseLong(numbers)));
203 | boolean yPass = true;
204 | try {
205 | new SimpleDateFormat("yyMMdd").parse(yymmdd);
206 | } catch (Exception e) {
207 | e.printStackTrace();
208 | yPass = false;
209 | }
210 | return aPass && yPass;
211 | }
212 | }
213 |
214 | /**
215 | * 是否数值型
216 | *
implements commit apache common utils
217 | *
218 | * @param input 校验内容
219 | * @return true为正确,false为错误
220 | */
221 | public static boolean isNumeric(String input) {
222 | if (TextUtils.isEmpty(input)) {
223 | return false;
224 | }
225 | char[] chars = input.toCharArray();
226 | int sz = chars.length;
227 | boolean hasExp = false;
228 | boolean hasDecPoint = false;
229 | boolean allowSigns = false;
230 | boolean foundDigit = false;
231 | // deal loader any possible sign up front
232 | int start = (chars[0] == '-' || chars[0] == '+') ? 1 : 0;
233 | if (sz > start + 1) {
234 | if (chars[start] == '0' && chars[start + 1] == 'x') {
235 | int i = start + 2;
236 | if (i == sz) {
237 | return false; // str == "0x"
238 | }
239 | // checking hex (it can't be anything else)
240 | for (; i < chars.length; i++) {
241 | if ((chars[i] < '0' || chars[i] > '9')
242 | && (chars[i] < 'a' || chars[i] > 'f')
243 | && (chars[i] < 'A' || chars[i] > 'F')) {
244 | return false;
245 | }
246 | }
247 | return true;
248 | }
249 | }
250 | sz--; // don't want to loop to the last char, check it afterwords
251 | // for build qualifiers
252 | int i = start;
253 | // loop to the next to last char or to the last char if we need another digit to
254 | // make a valid numeric (e.g. chars[0..5] = "1234E")
255 | while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) {
256 | if (chars[i] >= '0' && chars[i] <= '9') {
257 | foundDigit = true;
258 | allowSigns = false;
259 |
260 | } else if (chars[i] == '.') {
261 | if (hasDecPoint || hasExp) {
262 | // two decimal points or dec in exponent
263 | return false;
264 | }
265 | hasDecPoint = true;
266 | } else if (chars[i] == 'e' || chars[i] == 'E') {
267 | // we've already taken care of hex.
268 | if (hasExp) {
269 | // two E's
270 | return false;
271 | }
272 | if (!foundDigit) {
273 | return false;
274 | }
275 | hasExp = true;
276 | allowSigns = true;
277 | } else if (chars[i] == '+' || chars[i] == '-') {
278 | if (!allowSigns) {
279 | return false;
280 | }
281 | allowSigns = false;
282 | foundDigit = false; // we need a digit after the E
283 | } else {
284 | return false;
285 | }
286 | i++;
287 | }
288 | if (i < chars.length) {
289 | if (chars[i] >= '0' && chars[i] <= '9') {
290 | // no build qualifier, OK
291 | return true;
292 | }
293 | if (chars[i] == 'e' || chars[i] == 'E') {
294 | // can't have an E at the last byte
295 | return false;
296 | }
297 | if (!allowSigns
298 | && (chars[i] == 'd'
299 | || chars[i] == 'D'
300 | || chars[i] == 'f'
301 | || chars[i] == 'F')) {
302 | return foundDigit;
303 | }
304 | if (chars[i] == 'l'
305 | || chars[i] == 'L') {
306 | // not allowing L loader an exponent
307 | return foundDigit && !hasExp;
308 | }
309 | // last character is illegal
310 | return false;
311 | }
312 | // allowSigns is true iff the val ends in 'E'
313 | // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
314 | return !allowSigns && foundDigit;
315 | }
316 |
317 | /**
318 | * 校验内容是否匹配指定正则表达式
319 | *
320 | * @param regex 正则表达式
321 | * @param inputValue 内容
322 | * @return 是否匹配 true为匹配,false为不匹配
323 | */
324 | public static boolean testRegex(String regex, String inputValue) {
325 | return Pattern.compile(regex).matcher(inputValue).matches();
326 | }
327 | }
328 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/ViewUtils.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a;
2 |
3 | import android.app.Activity;
4 | import android.content.Context;
5 | import android.content.ContextWrapper;
6 | import android.content.res.Resources;
7 | import android.content.res.TypedArray;
8 | import android.graphics.Bitmap;
9 | import android.graphics.Canvas;
10 | import android.graphics.Matrix;
11 | import android.graphics.Paint;
12 | import android.graphics.drawable.BitmapDrawable;
13 | import android.view.LayoutInflater;
14 | import android.view.MotionEvent;
15 | import android.view.View;
16 | import android.view.View.MeasureSpec;
17 | import android.view.ViewGroup;
18 | import android.view.ViewParent;
19 | import android.widget.PopupWindow;
20 | import android.widget.TextView;
21 | import android.widget.Toast;
22 |
23 |
24 | /**
25 | * The type View utils.
26 | */
27 | public class ViewUtils {
28 |
29 | /**
30 | * Remove self from parent.
31 | *
32 | * @param view the view
33 | */
34 | public static void removeSelfFromParent(View view) {
35 | if (view != null) {
36 | ViewParent parent = view.getParent();
37 | if (parent != null && parent instanceof ViewGroup) {
38 | ViewGroup group = (ViewGroup) parent;
39 | group.removeView(view);
40 | }
41 | }
42 | }
43 |
44 |
45 | /**
46 | * Request layout parent.
47 | *
48 | * @param view the view
49 | * @param isAll the is all
50 | */
51 | public static void requestLayoutParent(View view, boolean isAll) {
52 | ViewParent parent = view.getParent();
53 | while (parent != null && parent instanceof View) {
54 | if (!parent.isLayoutRequested()) {
55 | parent.requestLayout();
56 | if (!isAll) {
57 | break;
58 | }
59 | }
60 | parent = parent.getParent();
61 | }
62 | }
63 |
64 |
65 | /**
66 | * Is touch in view boolean.
67 | *
68 | * @param ev the ev
69 | * @param v the v
70 | * @return the boolean
71 | */
72 | public static boolean isTouchInView(MotionEvent ev, View v) {
73 | int[] vLoc = new int[2];
74 | v.getLocationOnScreen(vLoc);
75 | float motionX = ev.getRawX();
76 | float motionY = ev.getRawY();
77 | return motionX >= vLoc[0] && motionX <= (vLoc[0] + v.getWidth()) && motionY >= vLoc[1] && motionY <= (vLoc[1] + v.getHeight());
78 | }
79 |
80 | /**
81 | * Big image bitmap.
82 | *
83 | * @param bmp the bmp
84 | * @param big the big
85 | * @return the bitmap
86 | */
87 | public static Bitmap bigImage(Bitmap bmp, float big) {
88 | int bmpWidth = bmp.getWidth();
89 | int bmpHeight = bmp.getHeight();
90 | Matrix matrix = new Matrix();
91 | matrix.postScale(big, big);
92 | return Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeight, matrix, true);
93 | }
94 |
95 |
96 | /**
97 | * 给TextView设置下划线
98 | *
99 | * @param textView the text view
100 | */
101 | public static void setTVUnderLine(TextView textView) {
102 | textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
103 | textView.getPaint().setAntiAlias(true);
104 | }
105 |
106 |
107 | /**
108 | * The Popup window.
109 | */
110 | static PopupWindow popupWindow;
111 |
112 | /**
113 | * Show popup window view.
114 | *
115 | * @param context the context
116 | * @param resId the res id
117 | * @param root the root
118 | * @param paramsType the params type
119 | * @return the view
120 | */
121 | public static View showPopupWindow(Context context, int resId, View root, int paramsType) {
122 | View popupView;
123 | popupView = LayoutInflater.from(context).inflate(resId, null);
124 |
125 | switch (paramsType) {
126 | case 1:
127 | popupWindow = new PopupWindow(popupView,
128 | ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
129 | break;
130 | case 2:
131 | popupWindow = new PopupWindow(popupView,
132 | ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
133 | break;
134 | case 3:
135 | popupWindow = new PopupWindow(popupView,
136 | ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
137 | break;
138 | case 4:
139 | popupWindow = new PopupWindow(popupView,
140 | ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
141 | break;
142 | default:
143 | popupWindow = new PopupWindow(popupView,
144 | ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
145 | break;
146 | }
147 | popupWindow.setFocusable(true);
148 | popupWindow.setOutsideTouchable(true);
149 | popupWindow.setTouchable(true);
150 | popupWindow.setBackgroundDrawable(new BitmapDrawable());
151 | popupWindow.showAsDropDown(root);
152 | return popupView;
153 | }
154 |
155 |
156 | /**
157 | * Dismiss popup.
158 | */
159 | public static void dismissPopup() {
160 | if (popupWindow != null && popupWindow.isShowing()) {
161 | popupWindow.dismiss();
162 | popupWindow = null;
163 | }
164 | }
165 |
166 | /**
167 | * 截图
168 | *
169 | * @param v the v
170 | * @return the bitmap
171 | */
172 | public static Bitmap captureView(View v) {
173 | v.setDrawingCacheEnabled(true);
174 | v.buildDrawingCache();
175 | return v.getDrawingCache();
176 | }
177 |
178 |
179 | /**
180 | * 截图
181 | *
182 | * @param v the v
183 | * @return the bitmap
184 | */
185 | public static Bitmap createViewBitmap(View v) {
186 | Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
187 | Canvas canvas = new Canvas(bitmap);
188 | v.draw(canvas);
189 | return bitmap;
190 | }
191 |
192 |
193 | /**
194 | * 截图
195 | *
196 | * @param view the view
197 | * @return the bitmap
198 | */
199 | public static Bitmap convertViewToBitmap(View view) {
200 | view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
201 | view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
202 | view.buildDrawingCache();
203 | return view.getDrawingCache();
204 | }
205 |
206 |
207 | /**
208 | * 获取Activity的截图
209 | *
210 | * @param activity the activity
211 | * @return the activity bitmap
212 | */
213 | public static Bitmap getActivityBitmap(Activity activity) {
214 | View view = activity.getWindow().getDecorView().findViewById(android.R.id.content);
215 | view.setDrawingCacheEnabled(true);
216 | return view.getDrawingCache();
217 | }
218 |
219 |
220 | /**
221 | * 获取状态栏高度
222 | *
223 | * @param context the context
224 | * @return the status bar height
225 | */
226 | public static int getStatusBarHeight(Context context) {
227 | int result = 0;
228 | int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
229 | if (resourceId > 0) {
230 | result = context.getResources().getDimensionPixelSize(resourceId);
231 | }
232 | return result;
233 | }
234 |
235 |
236 | /**
237 | * 获取工具栏高度
238 | *
239 | * @param context the context
240 | * @return the toolbar height
241 | */
242 | public static int getToolbarHeight(Context context) {
243 | final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(new int[]{R.attr.actionBarSize});
244 | int toolbarHeight = (int) styledAttributes.getDimension(0, 0);
245 | styledAttributes.recycle();
246 | return toolbarHeight;
247 | }
248 |
249 | /**
250 | * 获取导航栏高度
251 | *
252 | * @param activity the activity
253 | * @return the navigation bar height
254 | */
255 | public static int getNavigationBarHeight(Activity activity) {
256 | Resources resources = activity.getResources();
257 | int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
258 | if (resourceId > 0) {
259 | return resources.getDimensionPixelSize(resourceId);
260 | }
261 | return 0;
262 | }
263 |
264 | /**
265 | * 测量view
266 | *
267 | * @param view the view
268 | */
269 | public static void measureView(View view) {
270 | ViewGroup.LayoutParams p = view.getLayoutParams();
271 | if (p == null) {
272 | p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
273 | }
274 |
275 | int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width);
276 | int lpHeight = p.height;
277 | int childHeightSpec;
278 | if (lpHeight > 0) {
279 | childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
280 | } else {
281 | childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
282 | }
283 | view.measure(childWidthSpec, childHeightSpec);
284 | }
285 |
286 | /**
287 | * 获取view的宽度
288 | *
289 | * @param view the view
290 | * @return the view width
291 | */
292 | public static int getViewWidth(View view) {
293 | measureView(view);
294 | return view.getMeasuredWidth();
295 | }
296 |
297 | /**
298 | * 获取view的高度
299 | *
300 | * @param view the view
301 | * @return the view height
302 | */
303 | public static int getViewHeight(View view) {
304 | measureView(view);
305 | return view.getMeasuredHeight();
306 | }
307 |
308 | /**
309 | * 获取view的上下文
310 | *
311 | * @param view the view
312 | * @return the activity
313 | */
314 | public static Activity getActivity(View view) {
315 | Context context = view.getContext();
316 | while (context instanceof ContextWrapper) {
317 | if (context instanceof Activity) {
318 | return (Activity) context;
319 | }
320 | context = ((ContextWrapper) context).getBaseContext();
321 | }
322 | throw new IllegalStateException("View " + view + " is not attached to an Activity");
323 | }
324 | }
325 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/Md5.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a.cipher;
2 |
3 | import com.gyf.toolutils4a.StringUtil;
4 |
5 | import java.io.File;
6 | import java.io.FileInputStream;
7 | import java.io.FileNotFoundException;
8 | import java.io.InputStream;
9 | import java.security.MessageDigest;
10 | import java.security.NoSuchAlgorithmException;
11 |
12 | /**
13 | * MD5 加密工具类
14 | * Created by gyf on 2016/11/14.
15 | */
16 | public class Md5 {
17 | private Md5(){}
18 | /**
19 | * Md 5 string.
20 | * md5加密通过String
21 | *
22 | * @param str the str
23 | * @return the string
24 | */
25 | public static String MD5(String str) {
26 | try {
27 | // 获得MD5摘要算法的 MessageDigest 对象
28 | MessageDigest mdInst = MessageDigest.getInstance("Md5");
29 | // 使用指定的字节更新摘要
30 | mdInst.update(str.getBytes());
31 | // 获得密文
32 | byte[] md = mdInst.digest();
33 | // 字节数组转换为 十六进制 数并返回
34 | return StringUtil.byte2Hex(md);
35 | } catch (NoSuchAlgorithmException e) {
36 | return "";
37 | }
38 | }
39 |
40 | /**
41 | * Md 5 string.
42 | * md5加密通过字节数组
43 | *
44 | * @param bytes the bytes
45 | * @return the string
46 | */
47 | public static String MD5(byte[] bytes) {
48 | try {
49 | MessageDigest mdInst = MessageDigest.getInstance("Md5");
50 | mdInst.update(bytes);
51 | byte[] md = mdInst.digest();
52 | return StringUtil.byte2Hex(md);
53 | } catch (NoSuchAlgorithmException e) {
54 | return "";
55 | }
56 | }
57 |
58 | /**
59 | * Md 5 string.
60 | * md5加密通过输入流
61 | *
62 | * @param is the is
63 | * @return the string
64 | */
65 | public static String MD5(InputStream is) {
66 | byte[] dataBytes = new byte[1024];
67 | int read;
68 | try {
69 | MessageDigest mdInst = MessageDigest.getInstance("Md5");
70 | while ((read = is.read(dataBytes)) != -1) {
71 | mdInst.update(dataBytes, 0, read);
72 | }
73 | byte[] md = mdInst.digest();
74 | return StringUtil.byte2Hex(md);
75 | } catch (Exception e) {
76 | return "";
77 | }
78 | }
79 |
80 | /**
81 | * Md 5 string.
82 | * md5加密通过文件
83 | *
84 | * @param file the file
85 | * @return the string
86 | */
87 | public static String MD5(File file) {
88 | try {
89 | FileInputStream fis = new FileInputStream(file);
90 | return MD5(fis);
91 | } catch (FileNotFoundException e) {
92 | return "";
93 | }
94 |
95 | }
96 |
97 | /**
98 | * Md 5 by path string.
99 | * md5加密通过文件路径
100 | *
101 | * @param path the path
102 | * @return the string
103 | */
104 | public static String MD5ByPath(String path) {
105 | try {
106 | FileInputStream fis = new FileInputStream(path);
107 | return MD5(fis);
108 | } catch (FileNotFoundException e) {
109 | return "";
110 | }
111 | }
112 |
113 |
114 | /**
115 | * Md 5 check boolean.
116 | * md5检验通过字符串
117 | *
118 | * @param str the str
119 | * @param toBeCheckSum the to be check sum
120 | * @return the boolean
121 | */
122 | public static boolean MD5Check(String str, String toBeCheckSum) {
123 | return MD5(str).equals(toBeCheckSum);
124 | }
125 |
126 | /**
127 | * Md 5 check boolean.
128 | * md5检验通过字节数组
129 | *
130 | * @param bytes the bytes
131 | * @param toBeCheckSum the to be check sum
132 | * @return the boolean
133 | */
134 | public static boolean MD5Check(byte[] bytes, String toBeCheckSum) {
135 | return MD5(bytes).equals(toBeCheckSum);
136 | }
137 |
138 | /**
139 | * Md 5 check boolean.
140 | * md5检验通过输入流
141 | *
142 | * @param is the is
143 | * @param toBeCheckSum the to be check sum
144 | * @return the boolean
145 | */
146 | public static boolean MD5Check(InputStream is, String toBeCheckSum) {
147 | return MD5(is).equals(toBeCheckSum);
148 | }
149 |
150 | /**
151 | * Md 5 check boolean.
152 | * md5检验通过文件
153 | *
154 | * @param file the file
155 | * @param toBeCheckSum the to be check sum
156 | * @return the boolean
157 | */
158 | public static boolean MD5Check(File file, String toBeCheckSum) {
159 | return MD5(file).equals(toBeCheckSum);
160 | }
161 |
162 | /**
163 | * Md 5 check boolean.
164 | * md5检验通过文件路径
165 | *
166 | * @param path the path
167 | * @param toBeCheckSum the to be check sum
168 | * @return the boolean
169 | */
170 | public static boolean MD5CheckByPath(String path, String toBeCheckSum) {
171 | return MD5ByPath(path).equals(toBeCheckSum);
172 | }
173 |
174 | }
175 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/Sha1.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a.cipher;
2 |
3 | import com.gyf.toolutils4a.StringUtil;
4 |
5 | import java.io.File;
6 | import java.io.FileInputStream;
7 | import java.io.FileNotFoundException;
8 | import java.io.InputStream;
9 | import java.security.MessageDigest;
10 | import java.security.NoSuchAlgorithmException;
11 |
12 | /**
13 | * SHA1 加密工具类
14 | * Created by gyf on 2016/11/14.
15 | */
16 | public class Sha1 {
17 |
18 | private Sha1(){}
19 | /**
20 | * Sha 1 string.
21 | * sha1加密通过字符串
22 | *
23 | * @param str the str
24 | * @return the string
25 | */
26 | public static String SHA1(String str) {
27 | try {
28 | MessageDigest digest = MessageDigest.getInstance("SHA-1");
29 | digest.update(str.getBytes());
30 | byte md[] = digest.digest();
31 | return StringUtil.byte2Hex(md);
32 |
33 | } catch (NoSuchAlgorithmException e) {
34 | return "";
35 | }
36 | }
37 |
38 | /**
39 | * Sha 1 string.
40 | * sha1加密通过字节数组
41 | *
42 | * @param bytes the bytes
43 | * @return the string
44 | */
45 | public static String SHA1(byte[] bytes) {
46 | try {
47 | MessageDigest digest = MessageDigest.getInstance("SHA-1");
48 | digest.update(bytes);
49 | byte md[] = digest.digest();
50 | return StringUtil.byte2Hex(md);
51 | } catch (NoSuchAlgorithmException e) {
52 | return "";
53 | }
54 | }
55 |
56 | /**
57 | * Sha 1 string.
58 | * sha1加密通过输入流
59 | *
60 | * @param is the is
61 | * @return the string
62 | */
63 | public static String SHA1(InputStream is) {
64 | byte[] dataBytes = new byte[1024];
65 | int read;
66 | try {
67 | MessageDigest mdInst = MessageDigest.getInstance("SHA-1");
68 | while ((read = is.read(dataBytes)) != -1) {
69 | mdInst.update(dataBytes, 0, read);
70 | }
71 | byte[] md = mdInst.digest();
72 | return StringUtil.byte2Hex(md);
73 | } catch (Exception e) {
74 | return "";
75 | }
76 | }
77 |
78 | /**
79 | * Sha 1 string.
80 | * sha1加密通过文件
81 | *
82 | * @param file the file
83 | * @return the string
84 | */
85 | public static String SHA1(File file) {
86 | try {
87 | FileInputStream fis = new FileInputStream(file);
88 | return SHA1(fis);
89 | } catch (FileNotFoundException e) {
90 | return "";
91 | }
92 |
93 | }
94 |
95 | /**
96 | * Sha 1 by path string.
97 | * sha1加密通过路径
98 | *
99 | * @param path the path
100 | * @return the string
101 | */
102 | public static String SHA1ByPath(String path) {
103 | try {
104 | FileInputStream fis = new FileInputStream(path);
105 | return SHA1(fis);
106 | } catch (FileNotFoundException e) {
107 | return "";
108 | }
109 | }
110 |
111 | /**
112 | * Sha 1 check boolean.
113 | * sha1检验通过字符串
114 | *
115 | * @param str the str
116 | * @param toBeCheckSum the to be check sum
117 | * @return the boolean
118 | */
119 | public static boolean SHA1Check(String str, String toBeCheckSum) {
120 | return SHA1(str).equals(toBeCheckSum);
121 | }
122 |
123 | /**
124 | * Sha 1 check boolean.
125 | * sha1检验通过字节数组
126 | *
127 | * @param bytes the bytes
128 | * @param toBeCheckSum the to be check sum
129 | * @return the boolean
130 | */
131 | public static boolean SHA1Check(byte[] bytes, String toBeCheckSum) {
132 | return SHA1(bytes).equals(toBeCheckSum);
133 | }
134 |
135 | /**
136 | * Sha 1 check boolean.
137 | * sha1检验通过输入流
138 | *
139 | * @param is the is
140 | * @param toBeCheckSum the to be check sum
141 | * @return the boolean
142 | */
143 | public static boolean SHA1Check(InputStream is, String toBeCheckSum) {
144 | return SHA1(is).equals(toBeCheckSum);
145 | }
146 |
147 | /**
148 | * Sha 1 check boolean.
149 | * sha1检验通过文件
150 | *
151 | * @param file the file
152 | * @param toBeCheckSum the to be check sum
153 | * @return the boolean
154 | */
155 | public static boolean SHA1Check(File file, String toBeCheckSum) {
156 | return SHA1(file).equals(toBeCheckSum);
157 | }
158 |
159 | /**
160 | * Sha 1 check boolean.
161 | * sha1检验通过文件路径
162 | *
163 | * @param path the path
164 | * @param toBeCheckSum the to be check sum
165 | * @return the boolean
166 | */
167 | public static boolean SHA1CheckByPath(String path, String toBeCheckSum) {
168 | return SHA1ByPath(path).equals(toBeCheckSum);
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/Base64.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a.cipher.base64;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.io.OutputStream;
6 |
7 | /**
8 | * Base64 加密解密工具类
9 | * Created by gyf on 2016/11/8.
10 | */
11 | public class Base64 {
12 |
13 | /**
14 | * Instantiates a new Base 64.
15 | */
16 | private Base64() {
17 | }
18 |
19 | static {
20 | encoder = new Base64Encoder();
21 | decoder = new Base64Decoder();
22 | }
23 |
24 | /**
25 | * The constant encoder.
26 | */
27 | private static Base64Encoder encoder;
28 | /**
29 | * The constant decoder.
30 | */
31 | private static Base64Decoder decoder;
32 |
33 | /**
34 | * base64加密
35 | *
36 | * @param str the str
37 | * @return the string
38 | */
39 | public static String encode(String str) {
40 | return encoder.encode(str.getBytes());
41 | }
42 |
43 | /**
44 | * base64加密
45 | *
46 | * @param bytes the bytes
47 | * @return the string
48 | */
49 | public static String encode(byte[] bytes) {
50 | return encoder.encode(bytes);
51 | }
52 |
53 | /**
54 | * base64加密.
55 | *
56 | * @param bytes the bytes
57 | * @param out the out
58 | */
59 | public static void encode(byte[] bytes, OutputStream out) {
60 | try {
61 | encoder.encode(bytes, out);
62 | } catch (IOException e) {
63 | e.printStackTrace();
64 | }
65 | }
66 |
67 | /**
68 | * base64加密.
69 | *
70 | * @param str the str
71 | * @param out the out
72 | */
73 | public static void encode(String str, OutputStream out) {
74 | try {
75 | encoder.encode(str.getBytes(), out);
76 | } catch (IOException e) {
77 | e.printStackTrace();
78 | }
79 | }
80 |
81 | /**
82 | * 对输入流的加密
83 | *
84 | * @param in the in
85 | * @param out the out
86 | * @throws IOException the io exception
87 | */
88 | public static void encode(InputStream in, OutputStream out) {
89 | try {
90 | encoder.encode(in, out);
91 | } catch (IOException e) {
92 | e.printStackTrace();
93 | }
94 | }
95 |
96 | /**
97 | * base64解密
98 | *
99 | * @param str the str
100 | * @return the byte [ ]
101 | */
102 | public static byte[] decode(String str) {
103 | try {
104 | return decoder.decodeBuffer(str);
105 | } catch (IOException e) {
106 | e.printStackTrace();
107 | }
108 | return null;
109 | }
110 |
111 | /**
112 | * base64对输入流解密.
113 | *
114 | * @param in the in
115 | * @param out the out
116 | */
117 | public static void decode(InputStream in, OutputStream out) {
118 | try {
119 | decoder.decodeBuffer(in, out);
120 | } catch (IOException e) {
121 | e.printStackTrace();
122 | }
123 | }
124 |
125 | /**
126 | * base64对输入流解密.
127 | *
128 | * @param in the in
129 | * @return the byte [ ]
130 | */
131 | public static byte[] decode(InputStream in) {
132 | try {
133 | return decoder.decodeBuffer(in);
134 | } catch (IOException e) {
135 | e.printStackTrace();
136 | }
137 | return null;
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/Base64Decoder.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a.cipher.base64;
2 |
3 | import java.io.IOException;
4 | import java.io.OutputStream;
5 | import java.io.PushbackInputStream;
6 |
7 | /**
8 | * Created by gyf on 2016/11/14.
9 | */
10 |
11 | public class Base64Decoder extends CharacterDecoder{
12 | private static final char[] pem_array = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
13 | private static final byte[] pem_convert_array = new byte[256];
14 | byte[] decode_buffer = new byte[4];
15 |
16 | public Base64Decoder() {
17 | }
18 |
19 | protected int bytesPerAtom() {
20 | return 4;
21 | }
22 |
23 | protected int bytesPerLine() {
24 | return 72;
25 | }
26 |
27 | protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws IOException {
28 | byte var5 = -1;
29 | byte var6 = -1;
30 | byte var7 = -1;
31 | byte var8 = -1;
32 | if(var3 < 2) {
33 | throw new IOException("Base64Decoder: Not enough bytes for an atom.");
34 | } else {
35 | int var4;
36 | do {
37 | var4 = var1.read();
38 | if(var4 == -1) {
39 | throw new IOException();
40 | }
41 | } while(var4 == 10 || var4 == 13);
42 |
43 | this.decode_buffer[0] = (byte)var4;
44 | var4 = this.readFully(var1, this.decode_buffer, 1, var3 - 1);
45 | if(var4 == -1) {
46 | throw new IOException();
47 | } else {
48 | if(var3 > 3 && this.decode_buffer[3] == 61) {
49 | var3 = 3;
50 | }
51 |
52 | if(var3 > 2 && this.decode_buffer[2] == 61) {
53 | var3 = 2;
54 | }
55 |
56 | switch(var3) {
57 | case 4:
58 | var8 = pem_convert_array[this.decode_buffer[3] & 255];
59 | case 3:
60 | var7 = pem_convert_array[this.decode_buffer[2] & 255];
61 | case 2:
62 | var6 = pem_convert_array[this.decode_buffer[1] & 255];
63 | var5 = pem_convert_array[this.decode_buffer[0] & 255];
64 | default:
65 | switch(var3) {
66 | case 2:
67 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3));
68 | break;
69 | case 3:
70 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3));
71 | var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15));
72 | break;
73 | case 4:
74 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3));
75 | var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15));
76 | var2.write((byte)(var7 << 6 & 192 | var8 & 63));
77 | }
78 |
79 | }
80 | }
81 | }
82 | }
83 |
84 | static {
85 | int var0;
86 | for(var0 = 0; var0 < 255; ++var0) {
87 | pem_convert_array[var0] = -1;
88 | }
89 |
90 | for(var0 = 0; var0 < pem_array.length; ++var0) {
91 | pem_convert_array[pem_array[var0]] = (byte)var0;
92 | }
93 |
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/Base64Encoder.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a.cipher.base64;
2 |
3 | import java.io.IOException;
4 | import java.io.OutputStream;
5 |
6 | /**
7 | * Created by gyf on 2016/11/14.
8 | */
9 |
10 | public class Base64Encoder extends CharacterEncoder{
11 | private static final char[] pem_array = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
12 |
13 | public Base64Encoder() {
14 | }
15 |
16 | protected int bytesPerAtom() {
17 | return 3;
18 | }
19 |
20 | protected int bytesPerLine() {
21 | return 57;
22 | }
23 |
24 | protected void encodeAtom(OutputStream var1, byte[] var2, int var3, int var4) throws IOException {
25 | byte var5;
26 | if(var4 == 1) {
27 | var5 = var2[var3];
28 | byte var6 = 0;
29 | boolean var7 = false;
30 | var1.write(pem_array[var5 >>> 2 & 63]);
31 | var1.write(pem_array[(var5 << 4 & 48) + (var6 >>> 4 & 15)]);
32 | var1.write(61);
33 | var1.write(61);
34 | } else {
35 | byte var8;
36 | if(var4 == 2) {
37 | var5 = var2[var3];
38 | var8 = var2[var3 + 1];
39 | byte var9 = 0;
40 | var1.write(pem_array[var5 >>> 2 & 63]);
41 | var1.write(pem_array[(var5 << 4 & 48) + (var8 >>> 4 & 15)]);
42 | var1.write(pem_array[(var8 << 2 & 60) + (var9 >>> 6 & 3)]);
43 | var1.write(61);
44 | } else {
45 | var5 = var2[var3];
46 | var8 = var2[var3 + 1];
47 | byte var10 = var2[var3 + 2];
48 | var1.write(pem_array[var5 >>> 2 & 63]);
49 | var1.write(pem_array[(var5 << 4 & 48) + (var8 >>> 4 & 15)]);
50 | var1.write(pem_array[(var8 << 2 & 60) + (var10 >>> 6 & 3)]);
51 | var1.write(pem_array[var10 & 63]);
52 | }
53 | }
54 |
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/CharacterDecoder.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a.cipher.base64;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.io.ByteArrayOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.io.OutputStream;
8 | import java.io.PushbackInputStream;
9 | import java.nio.ByteBuffer;
10 |
11 | /**
12 | * Created by gyf on 2016/11/14.
13 | */
14 |
15 | public abstract class CharacterDecoder {
16 | public CharacterDecoder() {
17 | }
18 |
19 | protected abstract int bytesPerAtom();
20 |
21 | protected abstract int bytesPerLine();
22 |
23 | protected void decodeBufferPrefix(PushbackInputStream var1, OutputStream var2) throws IOException {
24 | }
25 |
26 | protected void decodeBufferSuffix(PushbackInputStream var1, OutputStream var2) throws IOException {
27 | }
28 |
29 | protected int decodeLinePrefix(PushbackInputStream var1, OutputStream var2) throws IOException {
30 | return this.bytesPerLine();
31 | }
32 |
33 | protected void decodeLineSuffix(PushbackInputStream var1, OutputStream var2) throws IOException {
34 | }
35 |
36 | protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws IOException {
37 | throw new IOException();
38 | }
39 |
40 | protected int readFully(InputStream var1, byte[] var2, int var3, int var4) throws IOException {
41 | for(int var5 = 0; var5 < var4; ++var5) {
42 | int var6 = var1.read();
43 | if(var6 == -1) {
44 | return var5 == 0?-1:var5;
45 | }
46 |
47 | var2[var5 + var3] = (byte)var6;
48 | }
49 |
50 | return var4;
51 | }
52 |
53 | public void decodeBuffer(InputStream var1, OutputStream var2) throws IOException {
54 | int var4 = 0;
55 | PushbackInputStream var5 = new PushbackInputStream(var1);
56 | this.decodeBufferPrefix(var5, var2);
57 |
58 | while(true) {
59 | try {
60 | int var6 = this.decodeLinePrefix(var5, var2);
61 |
62 | int var3;
63 | for(var3 = 0; var3 + this.bytesPerAtom() < var6; var3 += this.bytesPerAtom()) {
64 | this.decodeAtom(var5, var2, this.bytesPerAtom());
65 | var4 += this.bytesPerAtom();
66 | }
67 |
68 | if(var3 + this.bytesPerAtom() == var6) {
69 | this.decodeAtom(var5, var2, this.bytesPerAtom());
70 | var4 += this.bytesPerAtom();
71 | } else {
72 | this.decodeAtom(var5, var2, var6 - var3);
73 | var4 += var6 - var3;
74 | }
75 |
76 | this.decodeLineSuffix(var5, var2);
77 | } catch (IOException var8) {
78 | this.decodeBufferSuffix(var5, var2);
79 | return;
80 | }
81 | }
82 | }
83 |
84 | public byte[] decodeBuffer(String var1) throws IOException {
85 | byte[] var2 = new byte[var1.length()];
86 | var1.getBytes(0, var1.length(), var2, 0);
87 | ByteArrayInputStream var3 = new ByteArrayInputStream(var2);
88 | ByteArrayOutputStream var4 = new ByteArrayOutputStream();
89 | this.decodeBuffer(var3, var4);
90 | return var4.toByteArray();
91 | }
92 |
93 | public byte[] decodeBuffer(InputStream var1) throws IOException {
94 | ByteArrayOutputStream var2 = new ByteArrayOutputStream();
95 | this.decodeBuffer(var1, var2);
96 | return var2.toByteArray();
97 | }
98 |
99 | public ByteBuffer decodeBufferToByteBuffer(String var1) throws IOException {
100 | return ByteBuffer.wrap(this.decodeBuffer(var1));
101 | }
102 |
103 | public ByteBuffer decodeBufferToByteBuffer(InputStream var1) throws IOException {
104 | return ByteBuffer.wrap(this.decodeBuffer(var1));
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/cipher/base64/CharacterEncoder.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a.cipher.base64;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.io.ByteArrayOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.io.OutputStream;
8 | import java.io.PrintStream;
9 | import java.nio.ByteBuffer;
10 |
11 | /**
12 | * Created by gyf on 2016/11/14.
13 | */
14 |
15 | public abstract class CharacterEncoder {
16 | protected PrintStream pStream;
17 |
18 | public CharacterEncoder() {
19 | }
20 |
21 | protected abstract int bytesPerAtom();
22 |
23 | protected abstract int bytesPerLine();
24 |
25 | protected void encodeBufferPrefix(OutputStream var1) throws IOException {
26 | this.pStream = new PrintStream(var1);
27 | }
28 |
29 | protected void encodeBufferSuffix(OutputStream var1) throws IOException {
30 | }
31 |
32 | protected void encodeLinePrefix(OutputStream var1, int var2) throws IOException {
33 | }
34 |
35 | protected void encodeLineSuffix(OutputStream var1) throws IOException {
36 | this.pStream.println();
37 | }
38 |
39 | protected abstract void encodeAtom(OutputStream var1, byte[] var2, int var3, int var4) throws IOException;
40 |
41 | protected int readFully(InputStream var1, byte[] var2) throws IOException {
42 | for(int var3 = 0; var3 < var2.length; ++var3) {
43 | int var4 = var1.read();
44 | if(var4 == -1) {
45 | return var3;
46 | }
47 |
48 | var2[var3] = (byte)var4;
49 | }
50 |
51 | return var2.length;
52 | }
53 |
54 | public void encode(InputStream var1, OutputStream var2) throws IOException {
55 | byte[] var5 = new byte[this.bytesPerLine()];
56 | this.encodeBufferPrefix(var2);
57 |
58 | while(true) {
59 | int var4 = this.readFully(var1, var5);
60 | if(var4 == 0) {
61 | break;
62 | }
63 |
64 | this.encodeLinePrefix(var2, var4);
65 |
66 | for(int var3 = 0; var3 < var4; var3 += this.bytesPerAtom()) {
67 | if(var3 + this.bytesPerAtom() <= var4) {
68 | this.encodeAtom(var2, var5, var3, this.bytesPerAtom());
69 | } else {
70 | this.encodeAtom(var2, var5, var3, var4 - var3);
71 | }
72 | }
73 |
74 | if(var4 < this.bytesPerLine()) {
75 | break;
76 | }
77 |
78 | this.encodeLineSuffix(var2);
79 | }
80 |
81 | this.encodeBufferSuffix(var2);
82 | }
83 |
84 | public void encode(byte[] var1, OutputStream var2) throws IOException {
85 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1);
86 | this.encode((InputStream)var3, var2);
87 | }
88 |
89 | public String encode(byte[] var1) {
90 | ByteArrayOutputStream var2 = new ByteArrayOutputStream();
91 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1);
92 | String var4 = null;
93 |
94 | try {
95 | this.encode((InputStream)var3, var2);
96 | var4 = var2.toString("8859_1");
97 | return var4;
98 | } catch (Exception var6) {
99 | throw new Error("CharacterEncoder.encode internal error");
100 | }
101 | }
102 |
103 | private byte[] getBytes(ByteBuffer var1) {
104 | byte[] var2 = null;
105 | if(var1.hasArray()) {
106 | byte[] var3 = var1.array();
107 | if(var3.length == var1.capacity() && var3.length == var1.remaining()) {
108 | var2 = var3;
109 | var1.position(var1.limit());
110 | }
111 | }
112 |
113 | if(var2 == null) {
114 | var2 = new byte[var1.remaining()];
115 | var1.get(var2);
116 | }
117 |
118 | return var2;
119 | }
120 |
121 | public void encode(ByteBuffer var1, OutputStream var2) throws IOException {
122 | byte[] var3 = this.getBytes(var1);
123 | this.encode(var3, var2);
124 | }
125 |
126 | public String encode(ByteBuffer var1) {
127 | byte[] var2 = this.getBytes(var1);
128 | return this.encode(var2);
129 | }
130 |
131 | public void encodeBuffer(InputStream var1, OutputStream var2) throws IOException {
132 | byte[] var5 = new byte[this.bytesPerLine()];
133 | this.encodeBufferPrefix(var2);
134 |
135 | int var4;
136 | do {
137 | var4 = this.readFully(var1, var5);
138 | if(var4 == 0) {
139 | break;
140 | }
141 |
142 | this.encodeLinePrefix(var2, var4);
143 |
144 | for(int var3 = 0; var3 < var4; var3 += this.bytesPerAtom()) {
145 | if(var3 + this.bytesPerAtom() <= var4) {
146 | this.encodeAtom(var2, var5, var3, this.bytesPerAtom());
147 | } else {
148 | this.encodeAtom(var2, var5, var3, var4 - var3);
149 | }
150 | }
151 |
152 | this.encodeLineSuffix(var2);
153 | } while(var4 >= this.bytesPerLine());
154 |
155 | this.encodeBufferSuffix(var2);
156 | }
157 |
158 | public void encodeBuffer(byte[] var1, OutputStream var2) throws IOException {
159 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1);
160 | this.encodeBuffer((InputStream)var3, var2);
161 | }
162 |
163 | public String encodeBuffer(byte[] var1) {
164 | ByteArrayOutputStream var2 = new ByteArrayOutputStream();
165 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1);
166 |
167 | try {
168 | this.encodeBuffer((InputStream)var3, var2);
169 | } catch (Exception var5) {
170 | throw new Error("CharacterEncoder.encodeBuffer internal error");
171 | }
172 |
173 | return var2.toString();
174 | }
175 |
176 | public void encodeBuffer(ByteBuffer var1, OutputStream var2) throws IOException {
177 | byte[] var3 = this.getBytes(var1);
178 | this.encodeBuffer(var3, var2);
179 | }
180 |
181 | public String encodeBuffer(ByteBuffer var1) {
182 | byte[] var2 = this.getBytes(var1);
183 | return this.encodeBuffer(var2);
184 | }
185 | }
186 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/java/com/gyf/toolutils4a/service/DownloadService.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a.service;
2 |
3 | import android.app.DownloadManager;
4 | import android.app.Service;
5 | import android.content.BroadcastReceiver;
6 | import android.content.Context;
7 | import android.content.Intent;
8 | import android.content.IntentFilter;
9 | import android.database.Cursor;
10 | import android.net.Uri;
11 | import android.os.IBinder;
12 |
13 | import com.gyf.toolutils4a.AppUtils;
14 | import com.gyf.toolutils4a.L;
15 |
16 | public class DownloadService extends Service {
17 |
18 | private long mTaskId;
19 | private DownloadManager mDownloadManager;
20 | private String filePath;
21 |
22 | public DownloadService() {
23 | }
24 |
25 | @Override
26 | public void onCreate() {
27 | super.onCreate();
28 | }
29 |
30 | @Override
31 | public int onStartCommand(Intent intent, int flags, int startId) {
32 | L.w("onStartCommand:" + intent.getStringExtra("fileurl"));
33 | String fileurl = intent.getStringExtra("fileurl");
34 | downloadFile(fileurl);
35 | return super.onStartCommand(intent, flags, startId);
36 | }
37 |
38 | @Override
39 | public IBinder onBind(Intent intent) {
40 | return null;
41 | }
42 |
43 | private void downloadFile(String fileurl) {
44 | filePath = "/sdcard/Download/" + fileurl.substring(fileurl.lastIndexOf("/") + 1);
45 | DownloadManager.Request request = new DownloadManager.Request(Uri.parse(fileurl));
46 | request.setDestinationInExternalPublicDir("/Download/", fileurl.substring(fileurl.lastIndexOf("/") + 1));
47 | mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
48 | mTaskId = mDownloadManager.enqueue(request);
49 | registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
50 | }
51 |
52 | private BroadcastReceiver mReceiver = new BroadcastReceiver() {
53 | @Override
54 | public void onReceive(Context context, Intent intent) {
55 | checkDownloadStatus();
56 | }
57 | };
58 |
59 | private void checkDownloadStatus() {
60 | DownloadManager.Query query = new DownloadManager.Query();
61 | query.setFilterById(mTaskId);
62 | Cursor c = mDownloadManager.query(query);
63 | if (c.moveToFirst()) {
64 | int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
65 | switch (status) {
66 | /* case DownloadManager.STATUS_PAUSED:
67 | break;
68 | case DownloadManager.STATUS_FAILED:
69 | break;
70 | case DownloadManager.STATUS_PENDING:
71 | break;
72 | case DownloadManager.STATUS_RUNNING:
73 | break;*/
74 | case DownloadManager.STATUS_SUCCESSFUL:
75 | AppUtils.installApk(this, filePath);
76 | break;
77 | }
78 | }
79 |
80 |
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/toolutils4a/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | ToolUtils4a
3 | 无法跳转到微信,请检查您是否安装了微信!
4 | 无法跳转到支付宝,请检查您是否安装了支付宝!
5 |
6 |
--------------------------------------------------------------------------------
/toolutils4a/src/test/java/com/gyf/toolutils4a/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.gyf.toolutils4a;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | int i = 0;
16 | while (i < 10000){
17 | i++;
18 | System.out.println(StringUtil.randomFor6());
19 | }
20 |
21 | //assertEquals(4, 2 + 2);
22 | }
23 | }
--------------------------------------------------------------------------------
/toolutils4j/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/toolutils4j/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'java'
2 |
3 | dependencies {
4 | compile fileTree(include: ['*.jar'], dir: 'libs')
5 | }
6 | tasks.withType(JavaCompile) {
7 | options.encoding = "UTF-8"
8 | }
9 | sourceCompatibility = "1.7"
10 | targetCompatibility = "1.7"
11 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/cipher/Md5.java:
--------------------------------------------------------------------------------
1 | package com.gyf.cipher;
2 |
3 | import com.gyf.tool.StringUtil;
4 |
5 | import java.io.File;
6 | import java.io.FileInputStream;
7 | import java.io.FileNotFoundException;
8 | import java.io.InputStream;
9 | import java.security.MessageDigest;
10 | import java.security.NoSuchAlgorithmException;
11 |
12 | /**
13 | * MD5 加密工具类
14 | * Created by gyf on 2016/11/14.
15 | */
16 | public class Md5 {
17 | private Md5(){}
18 | /**
19 | * Md 5 string.
20 | * md5加密通过String
21 | *
22 | * @param str the str
23 | * @return the string
24 | */
25 | public static String MD5(String str) {
26 | try {
27 | // 获得MD5摘要算法的 MessageDigest 对象
28 | MessageDigest mdInst = MessageDigest.getInstance("Md5");
29 | // 使用指定的字节更新摘要
30 | mdInst.update(str.getBytes());
31 | // 获得密文
32 | byte[] md = mdInst.digest();
33 | // 字节数组转换为 十六进制 数并返回
34 | return StringUtil.byte2Hex(md);
35 | } catch (NoSuchAlgorithmException e) {
36 | return "";
37 | }
38 | }
39 |
40 | /**
41 | * Md 5 string.
42 | * md5加密通过字节数组
43 | *
44 | * @param bytes the bytes
45 | * @return the string
46 | */
47 | public static String MD5(byte[] bytes) {
48 | try {
49 | MessageDigest mdInst = MessageDigest.getInstance("Md5");
50 | mdInst.update(bytes);
51 | byte[] md = mdInst.digest();
52 | return StringUtil.byte2Hex(md);
53 | } catch (NoSuchAlgorithmException e) {
54 | return "";
55 | }
56 | }
57 |
58 | /**
59 | * Md 5 string.
60 | * md5加密通过输入流
61 | *
62 | * @param is the is
63 | * @return the string
64 | */
65 | public static String MD5(InputStream is) {
66 | byte[] dataBytes = new byte[1024];
67 | int read;
68 | try {
69 | MessageDigest mdInst = MessageDigest.getInstance("Md5");
70 | while ((read = is.read(dataBytes)) != -1) {
71 | mdInst.update(dataBytes, 0, read);
72 | }
73 | byte[] md = mdInst.digest();
74 | return StringUtil.byte2Hex(md);
75 | } catch (Exception e) {
76 | return "";
77 | }
78 | }
79 |
80 | /**
81 | * Md 5 string.
82 | * md5加密通过文件
83 | *
84 | * @param file the file
85 | * @return the string
86 | */
87 | public static String MD5(File file) {
88 | try {
89 | FileInputStream fis = new FileInputStream(file);
90 | return MD5(fis);
91 | } catch (FileNotFoundException e) {
92 | return "";
93 | }
94 |
95 | }
96 |
97 | /**
98 | * Md 5 by path string.
99 | * md5加密通过文件路径
100 | *
101 | * @param path the path
102 | * @return the string
103 | */
104 | public static String MD5ByPath(String path) {
105 | try {
106 | FileInputStream fis = new FileInputStream(path);
107 | return MD5(fis);
108 | } catch (FileNotFoundException e) {
109 | return "";
110 | }
111 | }
112 |
113 |
114 | /**
115 | * Md 5 check boolean.
116 | * md5检验通过字符串
117 | *
118 | * @param str the str
119 | * @param toBeCheckSum the to be check sum
120 | * @return the boolean
121 | */
122 | public static boolean MD5Check(String str, String toBeCheckSum) {
123 | return MD5(str).equals(toBeCheckSum);
124 | }
125 |
126 | /**
127 | * Md 5 check boolean.
128 | * md5检验通过字节数组
129 | *
130 | * @param bytes the bytes
131 | * @param toBeCheckSum the to be check sum
132 | * @return the boolean
133 | */
134 | public static boolean MD5Check(byte[] bytes, String toBeCheckSum) {
135 | return MD5(bytes).equals(toBeCheckSum);
136 | }
137 |
138 | /**
139 | * Md 5 check boolean.
140 | * md5检验通过输入流
141 | *
142 | * @param is the is
143 | * @param toBeCheckSum the to be check sum
144 | * @return the boolean
145 | */
146 | public static boolean MD5Check(InputStream is, String toBeCheckSum) {
147 | return MD5(is).equals(toBeCheckSum);
148 | }
149 |
150 | /**
151 | * Md 5 check boolean.
152 | * md5检验通过文件
153 | *
154 | * @param file the file
155 | * @param toBeCheckSum the to be check sum
156 | * @return the boolean
157 | */
158 | public static boolean MD5Check(File file, String toBeCheckSum) {
159 | return MD5(file).equals(toBeCheckSum);
160 | }
161 |
162 | /**
163 | * Md 5 check boolean.
164 | * md5检验通过文件路径
165 | *
166 | * @param path the path
167 | * @param toBeCheckSum the to be check sum
168 | * @return the boolean
169 | */
170 | public static boolean MD5CheckByPath(String path, String toBeCheckSum) {
171 | return MD5ByPath(path).equals(toBeCheckSum);
172 | }
173 |
174 | }
175 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/cipher/RSA.java:
--------------------------------------------------------------------------------
1 | package com.gyf.cipher;
2 |
3 |
4 | import com.gyf.cipher.base64.Base64;
5 |
6 | import javax.crypto.BadPaddingException;
7 | import javax.crypto.Cipher;
8 | import javax.crypto.IllegalBlockSizeException;
9 | import javax.crypto.NoSuchPaddingException;
10 |
11 | import java.io.*;
12 | import java.security.*;
13 | import java.security.interfaces.RSAPrivateKey;
14 | import java.security.interfaces.RSAPublicKey;
15 | import java.security.spec.InvalidKeySpecException;
16 | import java.security.spec.PKCS8EncodedKeySpec;
17 | import java.security.spec.X509EncodedKeySpec;
18 | import java.util.HashMap;
19 | import java.util.Map;
20 |
21 |
22 | /**
23 | * RSA 加密解密工具类
24 | * Created by gyf on 2016/11/14.
25 | */
26 | public class RSA {
27 |
28 | private RSA(){}
29 | /**
30 | * 加密算法RSA
31 | */
32 | public static final String KEY_ALGORITHM = "RSA";
33 |
34 | /**
35 | * 字节数据转字符串专用集合
36 | */
37 | public static final String MD5_SIGN = "MD5WithRSA";
38 | public static final String SHA1_SIGN = "SHA1WithRSA";
39 |
40 | /**
41 | * 存储名称
42 | */
43 | public static final String PUBLIC_KEY_PATH = "/publicKey.RSA";
44 | public static final String PRIVATE_KEY_PATH = "/privateKey.RSA";
45 |
46 | /**
47 | * 公钥的key
48 | */
49 | private static final String PUBLIC_KEY = "RSAPublicKey";
50 |
51 | /**
52 | * 私钥的key
53 | */
54 | private static final String PRIVATE_KEY = "RSAPrivateKey";
55 |
56 | /**
57 | * 生成秘钥对
58 | *
59 | * @return the map
60 | * @throws Exception the exception
61 | */
62 | public static Map genKeyPair() throws Exception {
63 | KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
64 | keyPairGen.initialize(1024, new SecureRandom());
65 | KeyPair keyPair = keyPairGen.generateKeyPair();
66 | RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
67 | RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
68 | Map keyMap = new HashMap<>();
69 | keyMap.put(PUBLIC_KEY, publicKey);
70 | keyMap.put(PRIVATE_KEY, privateKey);
71 | return keyMap;
72 | }
73 |
74 | /**
75 | * 生成秘钥对
76 | *
77 | * @param filePath 指定存储路径
78 | * @throws NoSuchAlgorithmException the no such algorithm exception
79 | */
80 | public static void genKeyPair(String filePath) throws Exception {
81 | // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
82 | KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
83 | // 初始化密钥对生成器,密钥大小为96-1024位
84 | keyPairGen.initialize(1024, new SecureRandom());
85 | // 生成一个密钥对,保存在keyPair中
86 | KeyPair keyPair = keyPairGen.generateKeyPair();
87 | // 得到私钥
88 | RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
89 | // 得到公钥
90 | RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
91 | try {
92 | // 得到公钥字符串
93 | String publicKeyString = Base64.encode(publicKey.getEncoded());
94 | // 得到私钥字符串
95 | String privateKeyString = Base64.encode(privateKey.getEncoded());
96 |
97 | // 将密钥对写入到文件
98 | FileWriter pubfw = new FileWriter(filePath + PUBLIC_KEY_PATH);
99 | FileWriter prifw = new FileWriter(filePath + PRIVATE_KEY_PATH);
100 | BufferedWriter pubbw = new BufferedWriter(pubfw);
101 | BufferedWriter pribw = new BufferedWriter(prifw);
102 | pubbw.write(publicKeyString);
103 | pribw.write(privateKeyString);
104 | pubbw.flush();
105 | pubbw.close();
106 | pubfw.close();
107 | pribw.flush();
108 | pribw.close();
109 | prifw.close();
110 | } catch (Exception e) {
111 | e.printStackTrace();
112 | }
113 | }
114 |
115 | /**
116 | * 从文件中输入流中加载公钥
117 | *
118 | * @param path 地址
119 | * @return 公钥字符串 string
120 | * @throws Exception 加载公钥时产生的异常
121 | */
122 | public static String loadPublicKeyByFile(String path) throws Exception {
123 | try {
124 | BufferedReader br = new BufferedReader(new FileReader(path + PUBLIC_KEY_PATH));
125 | String readLine = null;
126 | StringBuilder sb = new StringBuilder();
127 | while ((readLine = br.readLine()) != null) {
128 | sb.append(readLine);
129 | }
130 | br.close();
131 | return sb.toString();
132 | } catch (IOException e) {
133 | throw new Exception("公钥数据流读取错误");
134 | } catch (NullPointerException e) {
135 | throw new Exception("公钥输入流为空");
136 | }
137 | }
138 |
139 | /**
140 | * 从字符串中加载公钥
141 | *
142 | * @param publicKeyStr 公钥数据字符串
143 | * @return the rsa public key
144 | * @throws Exception 加载公钥时产生的异常
145 | */
146 | public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
147 | throws Exception {
148 | try {
149 | byte[] buffer = Base64.decode(publicKeyStr);
150 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
151 | X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
152 | return (RSAPublicKey) keyFactory.generatePublic(keySpec);
153 | } catch (NoSuchAlgorithmException e) {
154 | throw new Exception("无此算法");
155 | } catch (InvalidKeySpecException e) {
156 | throw new Exception("公钥非法");
157 | } catch (NullPointerException e) {
158 | throw new Exception("公钥数据为空");
159 | }
160 | }
161 |
162 | /**
163 | * 从文件中加载私钥
164 | *
165 | * @param path 地址
166 | * @return 私钥字符串 string
167 | * @throws Exception the exception
168 | */
169 | public static String loadPrivateKeyByFile(String path) throws Exception {
170 | try {
171 | BufferedReader br = new BufferedReader(new FileReader(path + PRIVATE_KEY_PATH));
172 | String readLine;
173 | StringBuilder sb = new StringBuilder();
174 | while ((readLine = br.readLine()) != null) {
175 | sb.append(readLine);
176 | }
177 | br.close();
178 | return sb.toString();
179 | } catch (IOException e) {
180 | throw new Exception("私钥数据读取错误");
181 | } catch (NullPointerException e) {
182 | throw new Exception("私钥输入流为空");
183 | }
184 | }
185 |
186 | /**
187 | * 从字符串中加载私钥
188 | *
189 | * @param privateKeyStr 私钥数据字符串
190 | * @return the rsa private key
191 | * @throws Exception 加载公钥时产生的异常
192 | */
193 | public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) throws Exception {
194 | try {
195 | byte[] buffer = Base64.decode(privateKeyStr);
196 | PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
197 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
198 | return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
199 | } catch (NoSuchAlgorithmException e) {
200 | throw new Exception("无此算法");
201 | } catch (InvalidKeySpecException e) {
202 | throw new Exception("私钥非法");
203 | } catch (NullPointerException e) {
204 | throw new Exception("私钥数据为空");
205 | }
206 | }
207 |
208 | /**
209 | * 公钥加密过程
210 | *
211 | * @param publicKey 公钥
212 | * @param plainTextData 明文数据
213 | * @return 密文字节数组 byte [ ]
214 | * @throws Exception 加密过程中的异常信息
215 | */
216 | public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
217 | if (publicKey == null) {
218 | throw new Exception("加密公钥为空, 请设置");
219 | }
220 | Cipher cipher = null;
221 | try {
222 | // 使用默认RSA
223 | cipher = Cipher.getInstance(KEY_ALGORITHM);
224 | // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
225 | cipher.init(Cipher.ENCRYPT_MODE, publicKey);
226 | byte[] output = cipher.doFinal(plainTextData);
227 | return output;
228 | } catch (NoSuchAlgorithmException e) {
229 | throw new Exception("无此加密算法");
230 | } catch (NoSuchPaddingException e) {
231 | e.printStackTrace();
232 | return null;
233 | } catch (InvalidKeyException e) {
234 | throw new Exception("加密公钥非法,请检查");
235 | } catch (IllegalBlockSizeException e) {
236 | throw new Exception("明文长度非法");
237 | } catch (BadPaddingException e) {
238 | throw new Exception("明文数据已损坏");
239 | }
240 | }
241 |
242 | /**
243 | * 私钥加密过程
244 | *
245 | * @param privateKey 私钥
246 | * @param plainTextData 明文数据
247 | * @return 密文字节数组 byte [ ]
248 | * @throws Exception 加密过程中的异常信息
249 | */
250 | public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
251 | throws Exception {
252 | if (privateKey == null) {
253 | throw new Exception("加密私钥为空, 请设置");
254 | }
255 | Cipher cipher = null;
256 | try {
257 | // 使用默认RSA
258 | cipher = Cipher.getInstance(KEY_ALGORITHM);
259 | cipher.init(Cipher.ENCRYPT_MODE, privateKey);
260 | byte[] output = cipher.doFinal(plainTextData);
261 | return output;
262 | } catch (NoSuchAlgorithmException e) {
263 | throw new Exception("无此加密算法");
264 | } catch (NoSuchPaddingException e) {
265 | e.printStackTrace();
266 | return null;
267 | } catch (InvalidKeyException e) {
268 | throw new Exception("加密私钥非法,请检查");
269 | } catch (IllegalBlockSizeException e) {
270 | throw new Exception("明文长度非法");
271 | } catch (BadPaddingException e) {
272 | throw new Exception("明文数据已损坏");
273 | }
274 | }
275 |
276 | /**
277 | * 私钥解密过程
278 | *
279 | * @param privateKey 私钥
280 | * @param cipherData 密文数据
281 | * @return 明文 byte [ ]
282 | * @throws Exception 解密过程中的异常信息
283 | */
284 | public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
285 | throws Exception {
286 | if (privateKey == null) {
287 | throw new Exception("解密私钥为空, 请设置");
288 | }
289 | Cipher cipher = null;
290 | try {
291 | // 使用默认RSA
292 | cipher = Cipher.getInstance(KEY_ALGORITHM);
293 | // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
294 | cipher.init(Cipher.DECRYPT_MODE, privateKey);
295 | byte[] output = cipher.doFinal(cipherData);
296 | return output;
297 | } catch (NoSuchAlgorithmException e) {
298 | throw new Exception("无此解密算法");
299 | } catch (NoSuchPaddingException e) {
300 | e.printStackTrace();
301 | return null;
302 | } catch (InvalidKeyException e) {
303 | throw new Exception("解密私钥非法,请检查");
304 | } catch (IllegalBlockSizeException e) {
305 | throw new Exception("密文长度非法");
306 | } catch (BadPaddingException e) {
307 | throw new Exception("密文数据已损坏");
308 | }
309 | }
310 |
311 | /**
312 | * 公钥解密过程
313 | *
314 | * @param publicKey 公钥
315 | * @param cipherData 密文数据
316 | * @return 明文 byte [ ]
317 | * @throws Exception 解密过程中的异常信息
318 | */
319 | public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
320 | throws Exception {
321 | if (publicKey == null) {
322 | throw new Exception("解密公钥为空, 请设置");
323 | }
324 | Cipher cipher = null;
325 | try {
326 | // 使用默认RSA
327 | cipher = Cipher.getInstance(KEY_ALGORITHM);
328 | // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
329 | cipher.init(Cipher.DECRYPT_MODE, publicKey);
330 | byte[] output = cipher.doFinal(cipherData);
331 | return output;
332 | } catch (NoSuchAlgorithmException e) {
333 | throw new Exception("无此解密算法");
334 | } catch (NoSuchPaddingException e) {
335 | e.printStackTrace();
336 | return null;
337 | } catch (InvalidKeyException e) {
338 | throw new Exception("解密公钥非法,请检查");
339 | } catch (IllegalBlockSizeException e) {
340 | throw new Exception("密文长度非法");
341 | } catch (BadPaddingException e) {
342 | throw new Exception("密文数据已损坏");
343 | }
344 | }
345 |
346 | /**
347 | * 私钥签名
348 | *
349 | * @param rsaPrivateKey 私钥
350 | * @param cipherData 待签名加密后的数据
351 | * @return 签名后的byte[]
352 | * @throws Exception 签名过程中的异常信息
353 | */
354 | public static byte[] sign(RSAPrivateKey rsaPrivateKey, byte[] cipherData) throws Exception {
355 | try {
356 | Signature signature = Signature.getInstance(MD5_SIGN);
357 | signature.initSign(rsaPrivateKey);
358 | signature.update(cipherData);
359 | byte[] output = signature.sign();
360 | return output;
361 | } catch (NoSuchAlgorithmException e) {
362 | throw new Exception("无此解密算法");
363 | } catch (InvalidKeyException e) {
364 | throw new Exception("解密非法,请检查");
365 | } catch (SignatureException e) {
366 | throw new Exception("签名异常");
367 | }
368 | }
369 |
370 | /**
371 | * 私钥签名
372 | *
373 | * @param privateKey 私钥字符串
374 | * @param cipherData 加密后的数据
375 | * @return 签名后的byte[]
376 | * @throws Exception 签名过程中的异常信息
377 | */
378 | public static byte[] sign(String privateKey, byte[] cipherData) throws Exception {
379 | return sign(loadPrivateKeyByStr(privateKey), cipherData);
380 | }
381 |
382 | /**
383 | * 公钥验签
384 | *
385 | * @param rsaPublicKey 公钥
386 | * @param cipherData 加密后的数据
387 | * @param sign 签名后的数据(base64加密)
388 | * @return the boolean
389 | * @throws Exception the exception
390 | */
391 | public static boolean verify(RSAPublicKey rsaPublicKey, byte[] cipherData, String sign) throws Exception {
392 | try {
393 | Signature signature = Signature.getInstance(MD5_SIGN);
394 | signature.initVerify(rsaPublicKey);
395 | signature.update(cipherData);
396 | return signature.verify(Base64.decode(sign));
397 | } catch (NoSuchAlgorithmException e) {
398 | throw new Exception("无此解密算法");
399 | } catch (InvalidKeyException e) {
400 | throw new Exception("解密非法,请检查");
401 | } catch (SignatureException e) {
402 | throw new Exception("签名异常");
403 | }
404 | }
405 |
406 | /**
407 | * 公钥验签
408 | *
409 | * @param publicKey 公钥字符串
410 | * @param cipherData 加密后的数据
411 | * @param sign 签名后的数据(base64加密)
412 | * @return the boolean
413 | * @throws Exception the exception
414 | */
415 | public static boolean verify(String publicKey, byte[] cipherData, String sign) throws Exception {
416 | return verify(loadPublicKeyByStr(publicKey), cipherData, sign);
417 | }
418 |
419 | /**
420 | * 获取私钥
421 | *
422 | * @param keyMap 密钥对
423 | * @return string
424 | */
425 | public static String getPrivateKey(Map keyMap) {
426 | Key key = (Key) keyMap.get(PRIVATE_KEY);
427 | return Base64.encode(key.getEncoded());
428 | }
429 |
430 | /**
431 | * 获取公钥
432 | *
433 | * @param keyMap 密钥对
434 | * @return string
435 | */
436 | public static String getPublicKey(Map keyMap) {
437 | Key key = (Key) keyMap.get(PUBLIC_KEY);
438 | return Base64.encode(key.getEncoded());
439 | }
440 | }
441 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/cipher/Sha1.java:
--------------------------------------------------------------------------------
1 | package com.gyf.cipher;
2 |
3 | import com.gyf.tool.StringUtil;
4 |
5 | import java.io.File;
6 | import java.io.FileInputStream;
7 | import java.io.FileNotFoundException;
8 | import java.io.InputStream;
9 | import java.security.MessageDigest;
10 | import java.security.NoSuchAlgorithmException;
11 |
12 | /**
13 | * SHA1 加密工具类
14 | * Created by gyf on 2016/11/14.
15 | */
16 | public class Sha1 {
17 |
18 | private Sha1(){}
19 | /**
20 | * Sha 1 string.
21 | * sha1加密通过字符串
22 | *
23 | * @param str the str
24 | * @return the string
25 | */
26 | public static String SHA1(String str) {
27 | try {
28 | MessageDigest digest = MessageDigest.getInstance("SHA-1");
29 | digest.update(str.getBytes());
30 | byte md[] = digest.digest();
31 | return StringUtil.byte2Hex(md);
32 |
33 | } catch (NoSuchAlgorithmException e) {
34 | return "";
35 | }
36 | }
37 |
38 | /**
39 | * Sha 1 string.
40 | * sha1加密通过字节数组
41 | *
42 | * @param bytes the bytes
43 | * @return the string
44 | */
45 | public static String SHA1(byte[] bytes) {
46 | try {
47 | MessageDigest digest = MessageDigest.getInstance("SHA-1");
48 | digest.update(bytes);
49 | byte md[] = digest.digest();
50 | return StringUtil.byte2Hex(md);
51 | } catch (NoSuchAlgorithmException e) {
52 | return "";
53 | }
54 | }
55 |
56 | /**
57 | * Sha 1 string.
58 | * sha1加密通过输入流
59 | *
60 | * @param is the is
61 | * @return the string
62 | */
63 | public static String SHA1(InputStream is) {
64 | byte[] dataBytes = new byte[1024];
65 | int read;
66 | try {
67 | MessageDigest mdInst = MessageDigest.getInstance("SHA-1");
68 | while ((read = is.read(dataBytes)) != -1) {
69 | mdInst.update(dataBytes, 0, read);
70 | }
71 | byte[] md = mdInst.digest();
72 | return StringUtil.byte2Hex(md);
73 | } catch (Exception e) {
74 | return "";
75 | }
76 | }
77 |
78 | /**
79 | * Sha 1 string.
80 | * sha1加密通过文件
81 | *
82 | * @param file the file
83 | * @return the string
84 | */
85 | public static String SHA1(File file) {
86 | try {
87 | FileInputStream fis = new FileInputStream(file);
88 | return SHA1(fis);
89 | } catch (FileNotFoundException e) {
90 | return "";
91 | }
92 |
93 | }
94 |
95 | /**
96 | * Sha 1 by path string.
97 | * sha1加密通过路径
98 | *
99 | * @param path the path
100 | * @return the string
101 | */
102 | public static String SHA1ByPath(String path) {
103 | try {
104 | FileInputStream fis = new FileInputStream(path);
105 | return SHA1(fis);
106 | } catch (FileNotFoundException e) {
107 | return "";
108 | }
109 | }
110 |
111 | /**
112 | * Sha 1 check boolean.
113 | * sha1检验通过字符串
114 | *
115 | * @param str the str
116 | * @param toBeCheckSum the to be check sum
117 | * @return the boolean
118 | */
119 | public static boolean SHA1Check(String str, String toBeCheckSum) {
120 | return SHA1(str).equals(toBeCheckSum);
121 | }
122 |
123 | /**
124 | * Sha 1 check boolean.
125 | * sha1检验通过字节数组
126 | *
127 | * @param bytes the bytes
128 | * @param toBeCheckSum the to be check sum
129 | * @return the boolean
130 | */
131 | public static boolean SHA1Check(byte[] bytes, String toBeCheckSum) {
132 | return SHA1(bytes).equals(toBeCheckSum);
133 | }
134 |
135 | /**
136 | * Sha 1 check boolean.
137 | * sha1检验通过输入流
138 | *
139 | * @param is the is
140 | * @param toBeCheckSum the to be check sum
141 | * @return the boolean
142 | */
143 | public static boolean SHA1Check(InputStream is, String toBeCheckSum) {
144 | return SHA1(is).equals(toBeCheckSum);
145 | }
146 |
147 | /**
148 | * Sha 1 check boolean.
149 | * sha1检验通过文件
150 | *
151 | * @param file the file
152 | * @param toBeCheckSum the to be check sum
153 | * @return the boolean
154 | */
155 | public static boolean SHA1Check(File file, String toBeCheckSum) {
156 | return SHA1(file).equals(toBeCheckSum);
157 | }
158 |
159 | /**
160 | * Sha 1 check boolean.
161 | * sha1检验通过文件路径
162 | *
163 | * @param path the path
164 | * @param toBeCheckSum the to be check sum
165 | * @return the boolean
166 | */
167 | public static boolean SHA1CheckByPath(String path, String toBeCheckSum) {
168 | return SHA1ByPath(path).equals(toBeCheckSum);
169 | }
170 | }
171 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/cipher/base64/Base64.java:
--------------------------------------------------------------------------------
1 | package com.gyf.cipher.base64;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.io.OutputStream;
6 |
7 | /**
8 | * Base64 加密解密工具类
9 | * Created by gyf on 2016/11/8.
10 | */
11 | public class Base64 {
12 |
13 | /**
14 | * Instantiates a new Base 64.
15 | */
16 | private Base64() {
17 | }
18 |
19 | static {
20 | encoder = new Base64Encoder();
21 | decoder = new Base64Decoder();
22 | }
23 |
24 | /**
25 | * The constant encoder.
26 | */
27 | private static Base64Encoder encoder;
28 | /**
29 | * The constant decoder.
30 | */
31 | private static Base64Decoder decoder;
32 |
33 | /**
34 | * base64加密
35 | *
36 | * @param str the str
37 | * @return the string
38 | */
39 | public static String encode(String str) {
40 | return encoder.encode(str.getBytes());
41 | }
42 |
43 | /**
44 | * base64加密
45 | *
46 | * @param bytes the bytes
47 | * @return the string
48 | */
49 | public static String encode(byte[] bytes) {
50 | return encoder.encode(bytes);
51 | }
52 |
53 | /**
54 | * base64加密.
55 | *
56 | * @param bytes the bytes
57 | * @param out the out
58 | */
59 | public static void encode(byte[] bytes, OutputStream out) {
60 | try {
61 | encoder.encode(bytes, out);
62 | } catch (IOException e) {
63 | e.printStackTrace();
64 | }
65 | }
66 |
67 | /**
68 | * base64加密.
69 | *
70 | * @param str the str
71 | * @param out the out
72 | */
73 | public static void encode(String str, OutputStream out) {
74 | try {
75 | encoder.encode(str.getBytes(), out);
76 | } catch (IOException e) {
77 | e.printStackTrace();
78 | }
79 | }
80 |
81 | /**
82 | * 对输入流的加密
83 | *
84 | * @param in the in
85 | * @param out the out
86 | * @throws IOException the io exception
87 | */
88 | public static void encode(InputStream in, OutputStream out) {
89 | try {
90 | encoder.encode(in, out);
91 | } catch (IOException e) {
92 | e.printStackTrace();
93 | }
94 | }
95 |
96 | /**
97 | * base64解密
98 | *
99 | * @param str the str
100 | * @return the byte [ ]
101 | */
102 | public static byte[] decode(String str) {
103 | try {
104 | return decoder.decodeBuffer(str);
105 | } catch (IOException e) {
106 | e.printStackTrace();
107 | }
108 | return null;
109 | }
110 |
111 | /**
112 | * base64对输入流解密.
113 | *
114 | * @param in the in
115 | * @param out the out
116 | */
117 | public static void decode(InputStream in, OutputStream out) {
118 | try {
119 | decoder.decodeBuffer(in, out);
120 | } catch (IOException e) {
121 | e.printStackTrace();
122 | }
123 | }
124 |
125 | /**
126 | * base64对输入流解密.
127 | *
128 | * @param in the in
129 | * @return the byte [ ]
130 | */
131 | public static byte[] decode(InputStream in) {
132 | try {
133 | return decoder.decodeBuffer(in);
134 | } catch (IOException e) {
135 | e.printStackTrace();
136 | }
137 | return null;
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/cipher/base64/Base64Decoder.java:
--------------------------------------------------------------------------------
1 | package com.gyf.cipher.base64;
2 |
3 | import java.io.IOException;
4 | import java.io.OutputStream;
5 | import java.io.PushbackInputStream;
6 |
7 | /**
8 | * Created by gyf on 2016/11/14.
9 | */
10 |
11 | public class Base64Decoder extends CharacterDecoder{
12 | private static final char[] pem_array = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
13 | private static final byte[] pem_convert_array = new byte[256];
14 | byte[] decode_buffer = new byte[4];
15 |
16 | public Base64Decoder() {
17 | }
18 |
19 | protected int bytesPerAtom() {
20 | return 4;
21 | }
22 |
23 | protected int bytesPerLine() {
24 | return 72;
25 | }
26 |
27 | protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws IOException {
28 | byte var5 = -1;
29 | byte var6 = -1;
30 | byte var7 = -1;
31 | byte var8 = -1;
32 | if(var3 < 2) {
33 | throw new IOException("Base64Decoder: Not enough bytes for an atom.");
34 | } else {
35 | int var4;
36 | do {
37 | var4 = var1.read();
38 | if(var4 == -1) {
39 | throw new IOException();
40 | }
41 | } while(var4 == 10 || var4 == 13);
42 |
43 | this.decode_buffer[0] = (byte)var4;
44 | var4 = this.readFully(var1, this.decode_buffer, 1, var3 - 1);
45 | if(var4 == -1) {
46 | throw new IOException();
47 | } else {
48 | if(var3 > 3 && this.decode_buffer[3] == 61) {
49 | var3 = 3;
50 | }
51 |
52 | if(var3 > 2 && this.decode_buffer[2] == 61) {
53 | var3 = 2;
54 | }
55 |
56 | switch(var3) {
57 | case 4:
58 | var8 = pem_convert_array[this.decode_buffer[3] & 255];
59 | case 3:
60 | var7 = pem_convert_array[this.decode_buffer[2] & 255];
61 | case 2:
62 | var6 = pem_convert_array[this.decode_buffer[1] & 255];
63 | var5 = pem_convert_array[this.decode_buffer[0] & 255];
64 | default:
65 | switch(var3) {
66 | case 2:
67 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3));
68 | break;
69 | case 3:
70 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3));
71 | var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15));
72 | break;
73 | case 4:
74 | var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3));
75 | var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15));
76 | var2.write((byte)(var7 << 6 & 192 | var8 & 63));
77 | }
78 |
79 | }
80 | }
81 | }
82 | }
83 |
84 | static {
85 | int var0;
86 | for(var0 = 0; var0 < 255; ++var0) {
87 | pem_convert_array[var0] = -1;
88 | }
89 |
90 | for(var0 = 0; var0 < pem_array.length; ++var0) {
91 | pem_convert_array[pem_array[var0]] = (byte)var0;
92 | }
93 |
94 | }
95 | }
96 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/cipher/base64/Base64Encoder.java:
--------------------------------------------------------------------------------
1 | package com.gyf.cipher.base64;
2 |
3 | import java.io.IOException;
4 | import java.io.OutputStream;
5 |
6 | /**
7 | * Created by gyf on 2016/11/14.
8 | */
9 |
10 | public class Base64Encoder extends CharacterEncoder{
11 | private static final char[] pem_array = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
12 |
13 | public Base64Encoder() {
14 | }
15 |
16 | protected int bytesPerAtom() {
17 | return 3;
18 | }
19 |
20 | protected int bytesPerLine() {
21 | return 57;
22 | }
23 |
24 | protected void encodeAtom(OutputStream var1, byte[] var2, int var3, int var4) throws IOException {
25 | byte var5;
26 | if(var4 == 1) {
27 | var5 = var2[var3];
28 | byte var6 = 0;
29 | boolean var7 = false;
30 | var1.write(pem_array[var5 >>> 2 & 63]);
31 | var1.write(pem_array[(var5 << 4 & 48) + (var6 >>> 4 & 15)]);
32 | var1.write(61);
33 | var1.write(61);
34 | } else {
35 | byte var8;
36 | if(var4 == 2) {
37 | var5 = var2[var3];
38 | var8 = var2[var3 + 1];
39 | byte var9 = 0;
40 | var1.write(pem_array[var5 >>> 2 & 63]);
41 | var1.write(pem_array[(var5 << 4 & 48) + (var8 >>> 4 & 15)]);
42 | var1.write(pem_array[(var8 << 2 & 60) + (var9 >>> 6 & 3)]);
43 | var1.write(61);
44 | } else {
45 | var5 = var2[var3];
46 | var8 = var2[var3 + 1];
47 | byte var10 = var2[var3 + 2];
48 | var1.write(pem_array[var5 >>> 2 & 63]);
49 | var1.write(pem_array[(var5 << 4 & 48) + (var8 >>> 4 & 15)]);
50 | var1.write(pem_array[(var8 << 2 & 60) + (var10 >>> 6 & 3)]);
51 | var1.write(pem_array[var10 & 63]);
52 | }
53 | }
54 |
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/cipher/base64/CharacterDecoder.java:
--------------------------------------------------------------------------------
1 | package com.gyf.cipher.base64;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.io.ByteArrayOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.io.OutputStream;
8 | import java.io.PushbackInputStream;
9 | import java.nio.ByteBuffer;
10 |
11 | /**
12 | * Created by gyf on 2016/11/14.
13 | */
14 |
15 | public abstract class CharacterDecoder {
16 | public CharacterDecoder() {
17 | }
18 |
19 | protected abstract int bytesPerAtom();
20 |
21 | protected abstract int bytesPerLine();
22 |
23 | protected void decodeBufferPrefix(PushbackInputStream var1, OutputStream var2) throws IOException {
24 | }
25 |
26 | protected void decodeBufferSuffix(PushbackInputStream var1, OutputStream var2) throws IOException {
27 | }
28 |
29 | protected int decodeLinePrefix(PushbackInputStream var1, OutputStream var2) throws IOException {
30 | return this.bytesPerLine();
31 | }
32 |
33 | protected void decodeLineSuffix(PushbackInputStream var1, OutputStream var2) throws IOException {
34 | }
35 |
36 | protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws IOException {
37 | throw new IOException();
38 | }
39 |
40 | protected int readFully(InputStream var1, byte[] var2, int var3, int var4) throws IOException {
41 | for(int var5 = 0; var5 < var4; ++var5) {
42 | int var6 = var1.read();
43 | if(var6 == -1) {
44 | return var5 == 0?-1:var5;
45 | }
46 |
47 | var2[var5 + var3] = (byte)var6;
48 | }
49 |
50 | return var4;
51 | }
52 |
53 | public void decodeBuffer(InputStream var1, OutputStream var2) throws IOException {
54 | int var4 = 0;
55 | PushbackInputStream var5 = new PushbackInputStream(var1);
56 | this.decodeBufferPrefix(var5, var2);
57 |
58 | while(true) {
59 | try {
60 | int var6 = this.decodeLinePrefix(var5, var2);
61 |
62 | int var3;
63 | for(var3 = 0; var3 + this.bytesPerAtom() < var6; var3 += this.bytesPerAtom()) {
64 | this.decodeAtom(var5, var2, this.bytesPerAtom());
65 | var4 += this.bytesPerAtom();
66 | }
67 |
68 | if(var3 + this.bytesPerAtom() == var6) {
69 | this.decodeAtom(var5, var2, this.bytesPerAtom());
70 | var4 += this.bytesPerAtom();
71 | } else {
72 | this.decodeAtom(var5, var2, var6 - var3);
73 | var4 += var6 - var3;
74 | }
75 |
76 | this.decodeLineSuffix(var5, var2);
77 | } catch (IOException var8) {
78 | this.decodeBufferSuffix(var5, var2);
79 | return;
80 | }
81 | }
82 | }
83 |
84 | public byte[] decodeBuffer(String var1) throws IOException {
85 | byte[] var2 = new byte[var1.length()];
86 | var1.getBytes(0, var1.length(), var2, 0);
87 | ByteArrayInputStream var3 = new ByteArrayInputStream(var2);
88 | ByteArrayOutputStream var4 = new ByteArrayOutputStream();
89 | this.decodeBuffer(var3, var4);
90 | return var4.toByteArray();
91 | }
92 |
93 | public byte[] decodeBuffer(InputStream var1) throws IOException {
94 | ByteArrayOutputStream var2 = new ByteArrayOutputStream();
95 | this.decodeBuffer(var1, var2);
96 | return var2.toByteArray();
97 | }
98 |
99 | public ByteBuffer decodeBufferToByteBuffer(String var1) throws IOException {
100 | return ByteBuffer.wrap(this.decodeBuffer(var1));
101 | }
102 |
103 | public ByteBuffer decodeBufferToByteBuffer(InputStream var1) throws IOException {
104 | return ByteBuffer.wrap(this.decodeBuffer(var1));
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/cipher/base64/CharacterEncoder.java:
--------------------------------------------------------------------------------
1 | package com.gyf.cipher.base64;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.io.ByteArrayOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.io.OutputStream;
8 | import java.io.PrintStream;
9 | import java.nio.ByteBuffer;
10 |
11 | /**
12 | * Created by gyf on 2016/11/14.
13 | */
14 |
15 | public abstract class CharacterEncoder {
16 | protected PrintStream pStream;
17 |
18 | public CharacterEncoder() {
19 | }
20 |
21 | protected abstract int bytesPerAtom();
22 |
23 | protected abstract int bytesPerLine();
24 |
25 | protected void encodeBufferPrefix(OutputStream var1) throws IOException {
26 | this.pStream = new PrintStream(var1);
27 | }
28 |
29 | protected void encodeBufferSuffix(OutputStream var1) throws IOException {
30 | }
31 |
32 | protected void encodeLinePrefix(OutputStream var1, int var2) throws IOException {
33 | }
34 |
35 | protected void encodeLineSuffix(OutputStream var1) throws IOException {
36 | this.pStream.println();
37 | }
38 |
39 | protected abstract void encodeAtom(OutputStream var1, byte[] var2, int var3, int var4) throws IOException;
40 |
41 | protected int readFully(InputStream var1, byte[] var2) throws IOException {
42 | for(int var3 = 0; var3 < var2.length; ++var3) {
43 | int var4 = var1.read();
44 | if(var4 == -1) {
45 | return var3;
46 | }
47 |
48 | var2[var3] = (byte)var4;
49 | }
50 |
51 | return var2.length;
52 | }
53 |
54 | public void encode(InputStream var1, OutputStream var2) throws IOException {
55 | byte[] var5 = new byte[this.bytesPerLine()];
56 | this.encodeBufferPrefix(var2);
57 |
58 | while(true) {
59 | int var4 = this.readFully(var1, var5);
60 | if(var4 == 0) {
61 | break;
62 | }
63 |
64 | this.encodeLinePrefix(var2, var4);
65 |
66 | for(int var3 = 0; var3 < var4; var3 += this.bytesPerAtom()) {
67 | if(var3 + this.bytesPerAtom() <= var4) {
68 | this.encodeAtom(var2, var5, var3, this.bytesPerAtom());
69 | } else {
70 | this.encodeAtom(var2, var5, var3, var4 - var3);
71 | }
72 | }
73 |
74 | if(var4 < this.bytesPerLine()) {
75 | break;
76 | }
77 |
78 | this.encodeLineSuffix(var2);
79 | }
80 |
81 | this.encodeBufferSuffix(var2);
82 | }
83 |
84 | public void encode(byte[] var1, OutputStream var2) throws IOException {
85 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1);
86 | this.encode((InputStream)var3, var2);
87 | }
88 |
89 | public String encode(byte[] var1) {
90 | ByteArrayOutputStream var2 = new ByteArrayOutputStream();
91 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1);
92 | String var4 = null;
93 |
94 | try {
95 | this.encode((InputStream)var3, var2);
96 | var4 = var2.toString("8859_1");
97 | return var4;
98 | } catch (Exception var6) {
99 | throw new Error("CharacterEncoder.encode internal error");
100 | }
101 | }
102 |
103 | private byte[] getBytes(ByteBuffer var1) {
104 | byte[] var2 = null;
105 | if(var1.hasArray()) {
106 | byte[] var3 = var1.array();
107 | if(var3.length == var1.capacity() && var3.length == var1.remaining()) {
108 | var2 = var3;
109 | var1.position(var1.limit());
110 | }
111 | }
112 |
113 | if(var2 == null) {
114 | var2 = new byte[var1.remaining()];
115 | var1.get(var2);
116 | }
117 |
118 | return var2;
119 | }
120 |
121 | public void encode(ByteBuffer var1, OutputStream var2) throws IOException {
122 | byte[] var3 = this.getBytes(var1);
123 | this.encode(var3, var2);
124 | }
125 |
126 | public String encode(ByteBuffer var1) {
127 | byte[] var2 = this.getBytes(var1);
128 | return this.encode(var2);
129 | }
130 |
131 | public void encodeBuffer(InputStream var1, OutputStream var2) throws IOException {
132 | byte[] var5 = new byte[this.bytesPerLine()];
133 | this.encodeBufferPrefix(var2);
134 |
135 | int var4;
136 | do {
137 | var4 = this.readFully(var1, var5);
138 | if(var4 == 0) {
139 | break;
140 | }
141 |
142 | this.encodeLinePrefix(var2, var4);
143 |
144 | for(int var3 = 0; var3 < var4; var3 += this.bytesPerAtom()) {
145 | if(var3 + this.bytesPerAtom() <= var4) {
146 | this.encodeAtom(var2, var5, var3, this.bytesPerAtom());
147 | } else {
148 | this.encodeAtom(var2, var5, var3, var4 - var3);
149 | }
150 | }
151 |
152 | this.encodeLineSuffix(var2);
153 | } while(var4 >= this.bytesPerLine());
154 |
155 | this.encodeBufferSuffix(var2);
156 | }
157 |
158 | public void encodeBuffer(byte[] var1, OutputStream var2) throws IOException {
159 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1);
160 | this.encodeBuffer((InputStream)var3, var2);
161 | }
162 |
163 | public String encodeBuffer(byte[] var1) {
164 | ByteArrayOutputStream var2 = new ByteArrayOutputStream();
165 | ByteArrayInputStream var3 = new ByteArrayInputStream(var1);
166 |
167 | try {
168 | this.encodeBuffer((InputStream)var3, var2);
169 | } catch (Exception var5) {
170 | throw new Error("CharacterEncoder.encodeBuffer internal error");
171 | }
172 |
173 | return var2.toString();
174 | }
175 |
176 | public void encodeBuffer(ByteBuffer var1, OutputStream var2) throws IOException {
177 | byte[] var3 = this.getBytes(var1);
178 | this.encodeBuffer(var3, var2);
179 | }
180 |
181 | public String encodeBuffer(ByteBuffer var1) {
182 | byte[] var2 = this.getBytes(var1);
183 | return this.encodeBuffer(var2);
184 | }
185 | }
186 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/tool/CoordinateTransformUtil.java:
--------------------------------------------------------------------------------
1 | package com.gyf.tool;
2 |
3 |
4 | /**
5 | * CoordinateTransformUtil.java GPS坐标转换工具
6 | */
7 | public class CoordinateTransformUtil {
8 | /**
9 | * The X pi.
10 | */
11 | static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
12 | /**
13 | * The Pi.
14 | */
15 | static double pi = 3.1415926535897932384626;
16 | /**
17 | * The A.
18 | */
19 | static double a = 6378245.0;
20 | /**
21 | * The Ee.
22 | */
23 | static double ee = 0.00669342162296594323;
24 |
25 | /**
26 | * 百度坐标系(BD-09)转WGS坐标(百度坐标纬度,百度坐标经度),WGS84坐标数组
27 | *
28 | * @param lng the lng
29 | * @param lat the lat
30 | * @return the double [ ]
31 | */
32 | public static double[] bd09towgs84(double lng, double lat) {
33 | double[] gcj = bd09togcj02(lng, lat);
34 | double[] wgs84 = gcj02towgs84(gcj[0], gcj[1]);
35 | return wgs84;
36 | }
37 |
38 | /**
39 | * WGS坐标转百度坐标系(BD-09)(WGS84坐标系的经度,WGS84坐标系的纬度),百度坐标数组
40 | *
41 | * @param lng the lng
42 | * @param lat the lat
43 | * @return the double [ ]
44 | */
45 | public static double[] wgs84tobd09(double lng, double lat) {
46 | double[] gcj = wgs84togcj02(lng, lat);
47 | double[] bd09 = gcj02tobd09(gcj[0], gcj[1]);
48 | return bd09;
49 | }
50 |
51 | /**
52 | * 火星坐标系(GCJ-02)转百度坐标系(BD-09)(火星坐标经度,火星坐标纬度),百度坐标数组
53 | *
54 | * @param lng the lng
55 | * @param lat the lat
56 | * @return the double [ ]
57 | */
58 | public static double[] gcj02tobd09(double lng, double lat) {
59 | double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi);
60 | double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi);
61 | double bd_lng = z * Math.cos(theta) + 0.0065;
62 | double bd_lat = z * Math.sin(theta) + 0.006;
63 | return new double[]{bd_lng, bd_lat};
64 | }
65 |
66 | /**
67 | * 百度坐标系(BD-09)转火星坐标系(GCJ-02)(百度坐标纬度,百度坐标经度),火星坐标数组
68 | *
69 | * @param bd_lon the bd lon
70 | * @param bd_lat the bd lat
71 | * @return the double [ ]
72 | */
73 | public static double[] bd09togcj02(double bd_lon, double bd_lat) {
74 | double x = bd_lon - 0.0065;
75 | double y = bd_lat - 0.006;
76 | double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
77 | double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
78 | double gg_lng = z * Math.cos(theta);
79 | double gg_lat = z * Math.sin(theta);
80 | return new double[]{gg_lng, gg_lat};
81 | }
82 |
83 | /**
84 | * WGS84转GCJ02(火星坐标系)(WGS84坐标系的经度,WGS84坐标系的纬度),火星坐标数组
85 | *
86 | * @param lng the lng
87 | * @param lat the lat
88 | * @return the double [ ]
89 | */
90 | public static double[] wgs84togcj02(double lng, double lat) {
91 | if (out_of_china(lng, lat)) {
92 | return new double[]{lng, lat};
93 | }
94 | double dlat = transformlat(lng - 105.0, lat - 35.0);
95 | double dlng = transformlng(lng - 105.0, lat - 35.0);
96 | double radlat = lat / 180.0 * pi;
97 | double magic = Math.sin(radlat);
98 | magic = 1 - ee * magic * magic;
99 | double sqrtmagic = Math.sqrt(magic);
100 | dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
101 | dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
102 | double mglat = lat + dlat;
103 | double mglng = lng + dlng;
104 | return new double[]{mglng, mglat};
105 | }
106 |
107 | /**
108 | * GCJ02(火星坐标系)转GPS84(火星坐标系的经度,火星坐标系纬度),WGS84坐标数组
109 | *
110 | * @param lng the lng
111 | * @param lat the lat
112 | * @return the double [ ]
113 | */
114 | public static double[] gcj02towgs84(double lng, double lat) {
115 | if (out_of_china(lng, lat)) {
116 | return new double[]{lng, lat};
117 | }
118 | double dlat = transformlat(lng - 105.0, lat - 35.0);
119 | double dlng = transformlng(lng - 105.0, lat - 35.0);
120 | double radlat = lat / 180.0 * pi;
121 | double magic = Math.sin(radlat);
122 | magic = 1 - ee * magic * magic;
123 | double sqrtmagic = Math.sqrt(magic);
124 | dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
125 | dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
126 | double mglat = lat + dlat;
127 | double mglng = lng + dlng;
128 | return new double[]{lng * 2 - mglng, lat * 2 - mglat};
129 | }
130 |
131 | /**
132 | * 纬度转换
133 | *
134 | * @param lng the lng
135 | * @param lat the lat
136 | * @return the double
137 | */
138 | public static double transformlat(double lng, double lat) {
139 | double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
140 | ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
141 | ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
142 | ret += (160.0 * Math.sin(lat / 12.0 * pi) + 320 * Math.sin(lat * pi / 30.0)) * 2.0 / 3.0;
143 | return ret;
144 | }
145 |
146 | /**
147 | * 经度转换
148 | *
149 | * @param lng the lng
150 | * @param lat the lat
151 | * @return the double
152 | */
153 | public static double transformlng(double lng, double lat) {
154 | double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
155 | ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
156 | ret += (20.0 * Math.sin(lng * pi) + 40.0 * Math.sin(lng / 3.0 * pi)) * 2.0 / 3.0;
157 | ret += (150.0 * Math.sin(lng / 12.0 * pi) + 300.0 * Math.sin(lng / 30.0 * pi)) * 2.0 / 3.0;
158 | return ret;
159 | }
160 |
161 | /**
162 | * 判断是否在国内,不在国内不做偏移
163 | *
164 | * @param lng the lng
165 | * @param lat the lat
166 | * @return the boolean
167 | */
168 | public static boolean out_of_china(double lng, double lat) {
169 | if (lng < 72.004 || lng > 137.8347) {
170 | return true;
171 | } else if (lat < 0.8293 || lat > 55.8271) {
172 | return true;
173 | }
174 | return false;
175 | }
176 | }
177 |
--------------------------------------------------------------------------------
/toolutils4j/src/main/java/com/gyf/tool/DateUtil.java:
--------------------------------------------------------------------------------
1 | package com.gyf.tool;
2 |
3 | import java.text.ParseException;
4 | import java.text.SimpleDateFormat;
5 | import java.util.*;
6 |
7 | /**
8 | * The type Date utils.
9 | */
10 | public class DateUtil {
11 | /**
12 | * The constant DATE_FORMAT_DATETIME.
13 | */
14 | private static final SimpleDateFormat DATE_FORMAT_DATETIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
15 | /**
16 | * The constant DATE_FORMAT_DATE.
17 | */
18 | private static final SimpleDateFormat DATE_FORMAT_DATE = new SimpleDateFormat("yyyy-MM-dd");
19 | /**
20 | * The constant DATE_FORMAT_TIME.
21 | */
22 | private static final SimpleDateFormat DATE_FORMAT_TIME = new SimpleDateFormat("HH:mm:ss");
23 |
24 | /**
25 | * Format data time string.
26 | * 格式化日期时间
27 | *
28 | * @param date the date
29 | * @return the string
30 | */
31 | public static String formatDataTime(long date) {
32 | return DATE_FORMAT_DATETIME.format(new Date(date));
33 | }
34 |
35 | /**
36 | * Format date string.
37 | * 格式化日期
38 | *
39 | * @param date the date
40 | * @return the string
41 | */
42 | public static String formatDate(long date) {
43 | return DATE_FORMAT_DATE.format(new Date(date));
44 | }
45 |
46 | /**
47 | * Format time string.
48 | * 格式化时间
49 | *
50 | * @param date the date
51 | * @return the string
52 | */
53 | public static String formatTime(long date) {
54 | return DATE_FORMAT_TIME.format(new Date(date));
55 | }
56 |
57 | /**
58 | * Format date custom string.
59 | * 自定义格式的格式化日期时间
60 | *
61 | * @param beginDate the begin date
62 | * @param format the format
63 | * @return the string
64 | */
65 | public static String formatDateCustom(String beginDate, String format) {
66 | return new SimpleDateFormat(format).format(new Date(Long.parseLong(beginDate)));
67 | }
68 |
69 | /**
70 | * Format date custom string.
71 | * 自定义格式的格式化日期时间
72 | *
73 | * @param beginDate the begin date
74 | * @param format the format
75 | * @return the string
76 | */
77 | public static String formatDateCustom(Date beginDate, String format) {
78 | return new SimpleDateFormat(format).format(beginDate);
79 | }
80 |
81 | /**
82 | * Gets time.
83 | * 获取系统日期
84 | *
85 | * @return the time
86 | */
87 | public static String getTime() {
88 | Calendar cal = Calendar.getInstance();
89 | cal.setTimeInMillis(System.currentTimeMillis());
90 | return cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND);
91 | }
92 |
93 | /**
94 | * Gets date.
95 | * 获取系统时间
96 | *
97 | * @return the date
98 | */
99 | public static String getDate() {
100 | return new SimpleDateFormat("yyyyMMdd").format(System.currentTimeMillis());
101 | }
102 |
103 | /**
104 | * Get date time string.
105 | * 获取系统日期时间
106 | *
107 | * @return the string
108 | */
109 | public static String getDateTime() {
110 | return DATE_FORMAT_DATETIME.format(System.currentTimeMillis());
111 | }
112 |
113 | /**
114 | * Get date time string.
115 | * 获取系统日期时间
116 | *
117 | * @param format the format
118 | * @return the string
119 | */
120 | public static String getDateTime(String format) {
121 | return new SimpleDateFormat(format).format(System.currentTimeMillis());
122 | }
123 |
124 |
125 | /**
126 | * Subtract date long.
127 | * 计算两个时间差
128 | *
129 | * @param dateStart the date start
130 | * @param dateEnd the date end
131 | * @return the long
132 | */
133 | public static long subtractDate(Date dateStart, Date dateEnd) {
134 | return dateEnd.getTime() - dateStart.getTime();
135 | }
136 |
137 | /**
138 | * Gets date after.
139 | * 得到几天后的时间
140 | *
141 | * @param d the d
142 | * @param day the day
143 | * @return the date after
144 | */
145 | public static Date getDateAfter(Date d, int day) {
146 | Calendar now = Calendar.getInstance();
147 | now.setTime(d);
148 | now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
149 | return now.getTime();
150 | }
151 |
152 | /**
153 | * Gets date time after.
154 | * 得到当前时间指定毫秒后的时间
155 | *
156 | * @param mill the mill
157 | * @return the String
158 | */
159 | public static String getDateTimeAfter(long mill) {
160 | return DATE_FORMAT_DATETIME.format(System.currentTimeMillis() + mill);
161 | }
162 |
163 | /**
164 | * Get week of year int.
165 | * 获取当前时间为本年的第几周
166 | *
167 | * @return the int
168 | */
169 | public static int getWeekOfYear() {
170 | Calendar calendar = Calendar.getInstance();
171 | calendar.setTime(new Date());
172 | return calendar.get(Calendar.WEEK_OF_YEAR);
173 | }
174 |
175 | /**
176 | * Gets week of month.
177 | * 获取当前时间为本月的第几周
178 | *
179 | * @return the week of month
180 | */
181 | public static int getWeekOfMonth() {
182 | Calendar calendar = Calendar.getInstance();
183 | int week = calendar.get(Calendar.WEEK_OF_MONTH);
184 | return week - 1;
185 | }
186 |
187 | /**
188 | * Gets day of week.
189 | * 获取当前时间为本周的第几天
190 | *
191 | * @return the day of week
192 | */
193 | public static int getDayOfWeek() {
194 | Calendar calendar = Calendar.getInstance();
195 | int day = calendar.get(Calendar.DAY_OF_WEEK);
196 | if (day == 1) {
197 | day = 7;
198 | } else {
199 | day = day - 1;
200 | }
201 | return day;
202 | }
203 |
204 | /**
205 | * Gets start time of week.
206 | * 获取一周开始时间
207 | *
208 | * @return the start time of week
209 | * @throws ParseException the parse exception
210 | */
211 | public static Date getStartTimeOfWeek() throws ParseException {
212 | Calendar c = Calendar.getInstance();
213 | int day = c.get(Calendar.DAY_OF_WEEK);
214 | long time = System.currentTimeMillis();
215 | if (day > 1) {
216 | time = time - (day - 2) * 24 * 60 * 60 * 1000L;
217 | } else {
218 | time = time - 6 * 24 * 60 * 60 * 1000L;
219 | }
220 | Date date = new Date(time);
221 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
222 | date = sdf.parse(sdf.format(date));
223 | return date;
224 | }
225 |
226 | /**
227 | * Gets end time of week.
228 | * 获取一周结束时间
229 | *
230 | * @return the end time of week
231 | */
232 | public static Date getEndTimeOfWeek() {
233 | Calendar c = Calendar.getInstance();
234 | int day = c.get(Calendar.DAY_OF_WEEK);
235 | long time = System.currentTimeMillis();
236 | if (day > 1) {
237 | time = time + (8 - day) * 24 * 60 * 60 * 1000L;
238 | }
239 | Date date = new Date(time);
240 | SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
241 | SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
242 | try {
243 | date = sdf2.parse(sdf1.format(date) + " 23:59:59");
244 | } catch (ParseException e) {
245 | e.printStackTrace();
246 | }
247 | return date;
248 | }
249 |
250 |
251 | /**
252 | * Gets week of date.
253 | * 根据日期获取星期
254 | *
255 | * @param date the date
256 | * @return the week of date
257 | */
258 | public static int getWeekOfDate(Date date) {
259 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
260 | Date currentDate = null;
261 | Date targetDate = null;
262 | try {
263 | currentDate = sdf.parse(sdf.format(new Date()));
264 | targetDate = sdf.parse(sdf.format(date));
265 | } catch (ParseException e) {
266 | e.printStackTrace();
267 | }
268 | if (currentDate.getTime() == targetDate.getTime()) {
269 | return getDayOfWeek();
270 | } else if (currentDate.getTime() < targetDate.getTime()) {
271 | return (int) ((targetDate.getTime() - currentDate.getTime()) / (24 * 60 * 60 * 1000)
272 | + getDayOfWeek()) % 7;
273 | } else if (currentDate.getTime() > targetDate.getTime()) {
274 | return (int) (getDayOfWeek() + 7
275 | - (currentDate.getTime() - targetDate.getTime()) / (24 * 60 * 60 * 1000) % 7) % 7;
276 | }
277 | return 0;
278 | }
279 |
280 | /**
281 | * Gets date list of week.
282 | * 根据日期获取一周的日期(从周一到周日)
283 | *
284 | * @param date the date
285 | * @return the date list of week
286 | * @throws ParseException the parse exception
287 | */
288 | public static List getDateListOfWeek(Date date) {
289 | List list = new ArrayList();
290 | int weekOfDate = getWeekOfDate(date);
291 | Date firstDay = new Date(date.getTime() - (weekOfDate - 1) * 24 * 60 * 60 * 1000L);
292 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
293 | try {
294 | firstDay = sdf.parse(sdf.format(firstDay));
295 | } catch (ParseException e) {
296 | e.printStackTrace();
297 | }
298 | list.add(firstDay);
299 | for (int i = 1; i < 7; i++) {
300 | if (i == 1) {
301 | list.add(new Date(firstDay.getTime() + i * 24 * 60 * 60 * 1000L));
302 | } else {
303 | list.add(new Date(firstDay.getTime() + (i + 1) * 24 * 60 * 60 * 1000L));
304 | }
305 | }
306 | return list;
307 | }
308 |
309 | /**
310 | * Gets age.
311 | * 根据日期返回年龄
312 | *
313 | * @param birthDate the birth date
314 | * @return the age
315 | */
316 | public static int getAge(Date birthDate) {
317 |
318 | if (birthDate == null)
319 | throw new RuntimeException("出生日期不能为null");
320 |
321 | int age = 0;
322 |
323 | Date now = new Date();
324 |
325 | SimpleDateFormat format_y = new SimpleDateFormat("yyyy");
326 | SimpleDateFormat format_M = new SimpleDateFormat("MM");
327 |
328 | String birth_year = format_y.format(birthDate);
329 | String this_year = format_y.format(now);
330 |
331 | String birth_month = format_M.format(birthDate);
332 | String this_month = format_M.format(now);
333 | // 初步,估算
334 | age = Integer.parseInt(this_year) - Integer.parseInt(birth_year);
335 | // 如果未到出生月份,则age - 1
336 | if (this_month.compareTo(birth_month) < 0) {
337 | age -= 1;
338 | }
339 | if (age < 0) {
340 | age = 0;
341 | }
342 | return age;
343 | }
344 |
345 | /**
346 | * Gets next date.
347 | * 获得第二条日期
348 | *
349 | * @return the next date
350 | * @throws Exception the exception
351 | */
352 | public static Date getNextDate() throws Exception {
353 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
354 | Date date = new Date();
355 | date.setDate(date.getDate() + 1);
356 |
357 | String str = format.format(date);
358 | return format.parse(str);
359 | }
360 |
361 | /**
362 | * Date to str string.
363 | * 日期转字符串
364 | *
365 | * @param date the date
366 | * @return the string
367 | */
368 | public static String date2Str(Date date) {
369 |
370 | SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
371 | String str = format.format(date);
372 | return str;
373 | }
374 |
375 | /**
376 | * Str to date date.
377 | * 字符串转日期
378 | *
379 | * @param str the str
380 | * @return the date
381 | */
382 | public static Date str2Date(String str) {
383 | return str2Date(str, "yyyy-MM-dd HH:mm:ss");
384 | }
385 |
386 | /**
387 | * String 2 date date.
388 | * 字符串转换成Date
389 | *
390 | * @param s the s
391 | * @param style the style
392 | * @return the date
393 | */
394 | public static Date str2Date(String s, String style) {
395 | SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
396 | simpleDateFormat.applyPattern(style);
397 | Date date = null;
398 | if (s == null || s.length() < 6) {
399 | return null;
400 | }
401 | try {
402 | date = simpleDateFormat.parse(s);
403 | } catch (ParseException e) {
404 | e.printStackTrace();
405 | }
406 | return date;
407 | }
408 |
409 | /**
410 | * Is ampm string.
411 | * 判断是上午还是下午
412 | *
413 | * @param date the date
414 | * @return the string
415 | */
416 | public static String isAMPM(Date date) {
417 | GregorianCalendar ca = new GregorianCalendar();
418 | ca.setTime(date);
419 | return GregorianCalendar.AM_PM == 0 ? "am" : "pm";
420 | }
421 |
422 |
423 | /**
424 | * Time am pm night int.
425 | * 判断指定日期是上午,下午,晚上0-上午;1-下午;2-晚上;3-过期
426 | *
427 | * @param date the date
428 | * @return the int
429 | */
430 | public static String isAmPmNight(Date date) {
431 | String start = "00:00:00";
432 | String night = "23:59:59";
433 | String am = "12:00:00";
434 | String pm = "18:00:00";
435 |
436 | SimpleDateFormat s = new SimpleDateFormat("HH:mm:ss");
437 | Date d_start = null;
438 | Date d_night = null;
439 | Date d_am = null;
440 | Date d_pm = null;
441 | try {
442 | d_start = s.parse(start);
443 | d_night = s.parse(night);
444 | d_am = s.parse(am);
445 | d_pm = s.parse(pm);
446 | } catch (ParseException e) {
447 | e.printStackTrace();
448 | }
449 |
450 | Date paramsTime = str2Date(formatTime(date.getTime()), "HH:mm:ss");
451 |
452 | if (paramsTime.after(d_start) && paramsTime.before(d_am)) {
453 | return "am";
454 | }
455 | if (paramsTime.after(d_am) && paramsTime.before(d_pm)) {
456 | return "pm";
457 | }
458 | if (paramsTime.after(d_pm) && paramsTime.before(d_night)) {
459 | return "night";
460 | }
461 | return "";
462 | }
463 |
464 | /**
465 | * Is leap year boolean.
466 | * 判断是否为闰年
467 | * @param date the date
468 | * @return the boolean
469 | */
470 | public static boolean isLeapYear(Date date) {
471 |
472 | /**
473 | * 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年
474 | * 3.能被4整除同时能被100整除则不是闰年
475 | */
476 | GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
477 | gc.setTime(date);
478 | int year = gc.get(Calendar.YEAR);
479 | if ((year % 400) == 0)
480 | return true;
481 | else if ((year % 4) == 0) {
482 | if ((year % 100) == 0)
483 | return false;
484 | else
485 | return true;
486 | } else
487 | return false;
488 | }
489 |
490 | }
491 |
--------------------------------------------------------------------------------