15 | * BASE64编码解码工具包 16 | *
17 | *18 | * 依赖javabase64-1.3.1.jar 19 | *
20 | * 21 | * @author IceWee 22 | * @date 2012-5-19 23 | * @version 1.0 24 | */ 25 | public class Base64Utils { 26 | 27 | /** 28 | * 文件读取缓冲区大小 29 | */ 30 | private static final int CACHE_SIZE = 1024; 31 | 32 | /** 33 | *34 | * BASE64字符串解码为二进制数据 35 | *
36 | * 37 | * @param base64 38 | * @return 39 | * @throws Exception 40 | */ 41 | public static byte[] decode(String base64) throws Exception { 42 | return Base64.decode(base64.getBytes()); 43 | } 44 | 45 | /** 46 | *47 | * 二进制数据编码为BASE64字符串 48 | *
49 | * 50 | * @param bytes 51 | * @return 52 | * @throws Exception 53 | */ 54 | public static String encode(byte[] bytes) throws Exception { 55 | return new String(Base64.encode(bytes)); 56 | } 57 | 58 | /** 59 | *60 | * 将文件编码为BASE64字符串 61 | *
62 | *63 | * 大文件慎用,可能会导致内存溢出 64 | *
65 | * 66 | * @param filePath 文件绝对路径 67 | * @return 68 | * @throws Exception 69 | */ 70 | public static String encodeFile(String filePath) throws Exception { 71 | byte[] bytes = fileToByte(filePath); 72 | return encode(bytes); 73 | } 74 | 75 | /** 76 | *77 | * BASE64字符串转回文件 78 | *
79 | * 80 | * @param filePath 文件绝对路径 81 | * @param base64 编码字符串 82 | * @throws Exception 83 | */ 84 | public static void decodeToFile(String filePath, String base64) throws Exception { 85 | byte[] bytes = decode(base64); 86 | byteArrayToFile(bytes, filePath); 87 | } 88 | 89 | /** 90 | *91 | * 文件转换为二进制数组 92 | *
93 | * 94 | * @param filePath 文件路径 95 | * @return 96 | * @throws Exception 97 | */ 98 | public static byte[] fileToByte(String filePath) throws Exception { 99 | byte[] data = new byte[0]; 100 | File file = new File(filePath); 101 | if (file.exists()) { 102 | FileInputStream in = new FileInputStream(file); 103 | ByteArrayOutputStream out = new ByteArrayOutputStream(2048); 104 | byte[] cache = new byte[CACHE_SIZE]; 105 | int nRead = 0; 106 | while ((nRead = in.read(cache)) != -1) { 107 | out.write(cache, 0, nRead); 108 | out.flush(); 109 | } 110 | out.close(); 111 | in.close(); 112 | data = out.toByteArray(); 113 | } 114 | return data; 115 | } 116 | 117 | /** 118 | *119 | * 二进制数据写文件 120 | *
121 | * 122 | * @param bytes 二进制数据 123 | * @param filePath 文件生成目录 124 | */ 125 | public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { 126 | InputStream in = new ByteArrayInputStream(bytes); 127 | File destFile = new File(filePath); 128 | if (!destFile.getParentFile().exists()) { 129 | destFile.getParentFile().mkdirs(); 130 | } 131 | destFile.createNewFile(); 132 | OutputStream out = new FileOutputStream(destFile); 133 | byte[] cache = new byte[CACHE_SIZE]; 134 | int nRead = 0; 135 | while ((nRead = in.read(cache)) != -1) { 136 | out.write(cache, 0, nRead); 137 | out.flush(); 138 | } 139 | out.close(); 140 | in.close(); 141 | } 142 | 143 | 144 | } -------------------------------------------------------------------------------- /src/main/java/com/scienjus/utils/DateFormatUtil.java: -------------------------------------------------------------------------------- 1 | package com.scienjus.utils; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | import java.util.GregorianCalendar; 8 | 9 | /** 10 | * 11 | *12 | * 时间转换工具类 13 | *
14 | * 15 | * 16 | */ 17 | public class DateFormatUtil { 18 | 19 | /** 格式:yyyy-MM-dd */ 20 | public static SimpleDateFormat yyyy_MM_dd = new SimpleDateFormat( 21 | "yyyy-MM-dd"); 22 | /** 格式:yyyyMMdd */ 23 | public static SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd"); 24 | /** 格式:yyyy/MM/dd */ 25 | public static SimpleDateFormat _yyyy_MM_dd = new SimpleDateFormat( 26 | "yyyy/MM/dd"); 27 | 28 | /** 格式:yyyy-MM-dd HH:mm:ss */ 29 | public static SimpleDateFormat yMd_Hms = new SimpleDateFormat( 30 | "yyyy-MM-dd HH:mm:ss"); 31 | /** 格式:yyyy/MM/dd HH:mm:ss */ 32 | public static SimpleDateFormat _yMd_Hms = new SimpleDateFormat( 33 | "yyyy/MM/dd HH:mm:ss"); 34 | /** 格式:yyyyMMddHHmmss */ 35 | public static SimpleDateFormat yMdHms = new SimpleDateFormat( 36 | "yyyyMMddHHmmss"); 37 | 38 | /** 格式:yyyyMM */ 39 | public static SimpleDateFormat yyyyMM = new SimpleDateFormat("yyyyMM"); 40 | /** 格式:HH:mm:ss */ 41 | public static SimpleDateFormat HHmmss = new SimpleDateFormat("HH:mm:ss"); 42 | 43 | /** 44 | *45 | * 获取当前系统时间 46 | *
47 | * 通过java.util.Date类获取 48 | * 49 | * @return 返回java.util.Date类型对象 50 | * @see #getCurrentDate() 51 | */ 52 | public static Date getDate() { 53 | return new Date(); 54 | } 55 | 56 | /** 57 | *58 | * 获取当前系统时间 59 | *
60 | * 通过java.util.Calendar类获取 61 | * 62 | * @return 返回java.util.Date类型对象 63 | * @see Calendar 64 | */ 65 | public static Date getCalendarDate() { 66 | Calendar calendar = Calendar.getInstance(); 67 | return calendar.getTime(); 68 | } 69 | 70 | /** 71 | *72 | * 获取当前系统日期,返回字符串格式 73 | *
74 | * 格式:yyyy-MM-dd 75 | * 76 | * @return 返回日期字符串格式:yyyy-MM-dd 77 | * @see #getDateStr(Date) 78 | */ 79 | public static String getDateStr() { 80 | return getDateStr(new Date()); 81 | } 82 | 83 | /** 84 | *85 | * 获取格式化字符串日期,返回字符串格式 86 | *
87 | * 格式:yyyy-MM-dd 88 | * 89 | * @param date 90 | * 指定日期对象 91 | * @return 返回日期字符串格式:yyyy-MM-dd 92 | */ 93 | public static String getDateStr(Date date) { 94 | return yyyy_MM_dd.format(date); 95 | } 96 | 97 | /** 98 | *99 | * [默认] 获取当前系统日期时间,返回字符串格式 100 | *
101 | * 格式:yyyy-MM-dd HH:mm:ss112 | * 获取当前系统日期时间,返回字符串格式 113 | *
114 | * 格式:yyyy-MM-dd HH:mm:ss 115 | * 116 | * @return 返回字符串对象:yyyy-MM-dd HH:mm:ss 117 | * @see #getDateTimeStr(Date) 118 | */ 119 | public static String getDateTimeStr() { 120 | return getDateTimeStr(new Date()); 121 | } 122 | 123 | /** 124 | *125 | * 获取格式化字符串日期时间,返回字符串格式 126 | *
127 | * 格式:yyyy-MM-dd HH:mm:ss 128 | * 129 | * @param date 130 | * 指定日期对象 131 | * @return 返回日期时间字符串格式:yyyy-MM-dd HH:mm:ss 132 | */ 133 | public static String getDateTimeStr(Date date) { 134 | return yMd_Hms.format(date); 135 | } 136 | 137 | /** 138 | *139 | * 获取当前年 140 | *
141 | * 142 | * @return 返回int类型的整数 143 | */ 144 | public static int getCurrentYear() { 145 | Calendar c = Calendar.getInstance(); 146 | return c.get(Calendar.YEAR); 147 | } 148 | 149 | /** 150 | * 151 | *152 | * 获取当前月 153 | *
154 | * 155 | * @return 返回int类型的整数,一位或两位数,范围是:1-12 156 | */ 157 | public static int getCurrentMonth() { 158 | Calendar c = Calendar.getInstance(); 159 | return c.get(Calendar.MONTH) + 1; 160 | } 161 | 162 | // 获得本月第一天0点时间 163 | public static Date getTimesMonthmorning() { 164 | Calendar cal = Calendar.getInstance(); 165 | cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), 166 | cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); 167 | cal.set(Calendar.DAY_OF_MONTH, 168 | cal.getActualMinimum(Calendar.DAY_OF_MONTH)); 169 | return cal.getTime(); 170 | } 171 | 172 | public static Date getLastMonthStartMorning() { 173 | Calendar cal = Calendar.getInstance(); 174 | cal.setTime(getTimesMonthmorning()); 175 | cal.add(Calendar.MONTH, -1); 176 | return cal.getTime(); 177 | } 178 | 179 | /** 180 | *181 | * 获取当前日 182 | *
183 | * 184 | * @return 返回int类型的整数,一位或两位数,范围是:1-31 185 | */ 186 | public static int getCurrentDay() { 187 | Calendar c = Calendar.getInstance(); 188 | return c.get(Calendar.DAY_OF_MONTH); 189 | } 190 | 191 | /** 192 | *193 | * 获得指定的年,int格式 194 | *
195 | * 196 | * @param date 197 | * 指定日期对象 198 | * @return 返回int类型的整数 199 | */ 200 | public static int getCustomYear(Date date) { 201 | Calendar c = Calendar.getInstance(); 202 | c.setTime(date); 203 | return c.get(Calendar.YEAR); 204 | } 205 | 206 | /** 207 | *208 | * 获得指定的月,int格式 209 | *
210 | * 211 | * @param date 212 | * 指定日期对象 213 | * @return 返回int类型的整数,一位或两位数,范围是:1-12 214 | */ 215 | public static int getCustomMonth(Date date) { 216 | Calendar c = Calendar.getInstance(); 217 | c.setTime(date); 218 | return c.get(Calendar.MONTH) + 1; 219 | } 220 | 221 | /** 222 | *223 | * 获得指定的日,int格式 224 | *
225 | * 226 | * @param date 227 | * 指定日期对象 228 | * @return 返回int类型的整数,一位或两位数,范围是:1-31 229 | */ 230 | public static int getCustomDay(Date date) { 231 | Calendar c = Calendar.getInstance(); 232 | c.setTime(date); 233 | return c.get(Calendar.DAY_OF_MONTH); 234 | } 235 | 236 | /** 237 | *238 | * 获取当前系统时间的小时数 239 | *
240 | * 通过java.util.Calendar获取 241 | * 242 | * @return 返回小时数 243 | */ 244 | public static int getCurrentHour() { 245 | Calendar calendar = new GregorianCalendar(); 246 | return calendar.get(Calendar.HOUR_OF_DAY); 247 | } 248 | 249 | /** 250 | *251 | * 获取当前系统时间的分钟数 252 | *
253 | * 通过java.util.Calendar获取 254 | * 255 | * @return 返回分钟数 256 | */ 257 | public static int getCurrentMinute() { 258 | Calendar calendar = new GregorianCalendar(); 259 | return calendar.get(Calendar.MINUTE); 260 | } 261 | 262 | /** 263 | *264 | * 获取当前系统时间的秒数 265 | *
266 | * 通过java.util.Calendar获取 267 | * 268 | * @return 返回秒数 269 | */ 270 | public static int getCurrentSecond() { 271 | Calendar calendar = new GregorianCalendar(); 272 | return calendar.get(Calendar.SECOND); 273 | } 274 | 275 | /** 276 | *277 | * 获得指定的小时(日中的),int格式 278 | *
279 | *291 | * 获得指定的分钟,int格式 292 | *
293 | *305 | * 获得指定的秒,int格式 306 | *
307 | *321 | * 获取本月第一天日期(格式如YYYYMMDD),如果当前日为当月1日,则返回上月第一日 322 | *
323 | * 324 | * @return 325 | */ 326 | public static String getMonthFirstDay() { 327 | Calendar calendar = new GregorianCalendar(); 328 | int day = calendar.get(Calendar.DAY_OF_MONTH); 329 | int month = 0; 330 | if (day == 1)// 当月第一日 331 | { 332 | calendar.add(Calendar.MONTH, -1); 333 | } 334 | month = calendar.get(Calendar.MONTH); 335 | if (month < 10) { 336 | return "" + calendar.get(Calendar.YEAR) + "0" + (month + 1) + "01"; 337 | } else { 338 | return "" + calendar.get(Calendar.YEAR) + month + "01"; 339 | } 340 | } 341 | 342 | /** 343 | *344 | * 获取当前时间前几天或后几天的日期 345 | *
346 | * 347 | * @return 348 | */ 349 | public static Date getAddDays(int days) { 350 | Calendar calendar = new GregorianCalendar(); 351 | calendar.add(Calendar.DAY_OF_YEAR, days); 352 | return calendar.getTime(); 353 | } 354 | 355 | /** 356 | *357 | * 获取某个月后的日期格式(yyyyMMdd) 358 | *
359 | * 360 | * @return 361 | */ 362 | public static String getAfterMonth(int monthNum) { 363 | Calendar calendar = new GregorianCalendar(); 364 | calendar.add(Calendar.MONTH, monthNum); 365 | return yyyyMMdd.format(calendar.getTime()); 366 | } 367 | 368 | /** 369 | *370 | * 返回日期(格式yyyyMMdd) 371 | *
372 | * 373 | * @param timeMillis 374 | * @return 375 | */ 376 | public static String getFormatDate(long timeMillis) { 377 | return yMdHms.format(new Date(timeMillis)); 378 | } 379 | 380 | /** 381 | * 获取当前系统时间距离传入时间的毫秒数 382 | * 383 | * @param strTime 384 | * 格式[ DD:00:00] 385 | * @return 386 | * @throws ParseException 387 | */ 388 | public static long getSleepTime(String strTime) throws ParseException { 389 | long p = 1; 390 | long l_date = System.currentTimeMillis(); 391 | Date date_now = new Date(l_date); 392 | String strDate = yyyy_MM_dd.format(date_now) + strTime; 393 | if (date_now.before(yMd_Hms.parse(strDate))) 394 | p = (yMd_Hms.parse(strDate)).getTime() - l_date; 395 | else { 396 | Calendar calendar = new GregorianCalendar(); 397 | calendar.setTime(date_now); 398 | calendar.add(Calendar.DAY_OF_YEAR, 1); 399 | Date date = calendar.getTime(); 400 | strDate = yyyy_MM_dd.format(date) + strTime; 401 | p = (yMd_Hms.parse(strDate)).getTime() - l_date; 402 | } 403 | return p; 404 | } 405 | 406 | public static String getPredate() { 407 | Date nowDate = new Date(); 408 | String nowdates = yyyy_MM_dd.format(nowDate); 409 | String[] dates = nowdates.split("-"); 410 | int year = Integer.parseInt(dates[0]); 411 | int month = Integer.parseInt(dates[1]); 412 | int day = Integer.parseInt(dates[2]) - 1; 413 | if (day == 0) { 414 | switch (month - 1) { 415 | case 1: 416 | day = 31; 417 | break; 418 | case 3: 419 | day = 31; 420 | break; 421 | case 5: 422 | day = 31; 423 | break; 424 | case 7: 425 | day = 31; 426 | break; 427 | case 8: 428 | day = 31; 429 | break; 430 | case 10: 431 | day = 31; 432 | break; 433 | case 0: 434 | month = 13; 435 | year = year - 1; 436 | day = 31; 437 | break; 438 | case 4: 439 | day = 30; 440 | break; 441 | case 6: 442 | day = 30; 443 | break; 444 | case 9: 445 | day = 30; 446 | break; 447 | case 11: 448 | day = 30; 449 | break; 450 | case 2: 451 | if (year % 4 == 0) { 452 | day = 29; 453 | } else { 454 | day = 28; 455 | } 456 | break; 457 | default: 458 | break; 459 | } 460 | month = month - 1; 461 | } 462 | String predate = Integer.toString(year) + "-" 463 | + (month < 10 ? "0" + month : month) + "-" 464 | + (day < 10 ? "0" + day : day); 465 | return predate; 466 | } 467 | 468 | /** 469 | *470 | * 获取中文日期格式 471 | *
472 | * 格式:xxxx年xx月xx日 473 | * 474 | * @param date 475 | * @return 476 | */ 477 | /* 478 | * public static String getChinaDateFormat(Date date) { // 479 | * 获取yyyy-mm-dd格式日期格式 String dateStr = getDateTime_I(date); StringBuffer sb 480 | * = new StringBuffer(); if (dateStr != null && dateStr.length() > 0) { 481 | * String[] newStr = dateStr.split("-"); // 获取月 int month = 482 | * Integer.valueOf(newStr[1]); // 获取日 int day = Integer.valueOf(newStr[2]); 483 | * sb.append(newStr[0]).append("年"); 484 | * sb.append(month).append("月").append(day).append("日"); } return 485 | * sb.toString(); } 486 | */ 487 | 488 | /** 489 | *490 | * 获取中文日期时间格式 491 | *
492 | * 格式:xxxx年xx月xx日514 | * 获取中文日期时间格式 515 | *
516 | * 格式:xxxx年xx月xx日 xx时xx分xx秒 517 | * 518 | * @param date 519 | * 指定日期对象,为null时获取当前系统时间 520 | * @return 返回诸如“xxxx年xx月xx日 xx时xx分xx秒”格式的日期 521 | */ 522 | public static String getChineseDateTime(Date date) { 523 | if (date == null) 524 | date = new Date(); 525 | int yyyy = getCustomYear(date); 526 | int MM = getCustomMonth(date); 527 | int dd = getCustomDay(date); 528 | 529 | int HH = getCustomHour(date); 530 | int mm = getCustomMinute(date); 531 | int ss = getCustomSecond(date); 532 | 533 | StringBuilder sb = new StringBuilder(); 534 | sb.append(yyyy + "年"); 535 | sb.append(MM + "月"); 536 | sb.append(dd + "日"); 537 | sb.append(" "); 538 | sb.append(HH + "时"); 539 | sb.append(mm + "分"); 540 | sb.append(ss + "秒"); 541 | 542 | return sb.toString(); 543 | } 544 | 545 | /** 546 | * add by lipp 547 | *548 | * 获取xxxx年xx月xx日 日期格式。 549 | *
550 | * 551 | * @param date 552 | * 格式必须是2009-03-21字符串 553 | * @return 554 | */ 555 | public static String getChinaDateFormat(String date) { 556 | // 获取yyyy-mm-dd格式日期格式 557 | StringBuffer sb = new StringBuffer(); 558 | if (date != null && date.length() > 0) { 559 | String[] newStr = date.split("-"); 560 | // 获取月 561 | int month = Integer.valueOf(newStr[1]); 562 | // 获取日 563 | int day = Integer.valueOf(newStr[2]); 564 | sb.append(newStr[0]).append("年"); 565 | sb.append(month).append("月").append(day).append("日"); 566 | } 567 | return sb.toString(); 568 | } 569 | 570 | /** 571 | * 判断一个日期字符串是否合法 572 | * 573 | * @param date 574 | * @param format 575 | * @return 576 | * @author liufengyu 577 | */ 578 | public static boolean isDateStringCorrect(String date, String format) { 579 | SimpleDateFormat df = new SimpleDateFormat(format); 580 | 581 | try { 582 | df.setLenient(false); 583 | df.parse(date); 584 | return true; 585 | } catch (Exception e) { 586 | return false; 587 | } 588 | } 589 | 590 | /** 591 | * add by gongtao 592 | *593 | * 将字符串类型的日期格式 转换为 符合要求的日期格式 594 | *
595 | * 596 | * @param date 597 | * @param format 598 | * @return 599 | */ 600 | public static String getStrDate4String(String date, String format) { 601 | if (date == null || date.trim().equals("")) { 602 | return ""; 603 | } else { 604 | SimpleDateFormat df = new SimpleDateFormat(format); 605 | try { 606 | Date d = df.parse(date); 607 | return df.format(d); 608 | } catch (ParseException e) { 609 | System.out.println(e); 610 | return ""; 611 | } 612 | } 613 | } 614 | 615 | /** 616 | * add by gongtao 617 | *618 | * 将Date类型的日期格式 转换为 符合要求的 String日期格式 619 | *
620 | * 621 | * @param date 622 | * @param format 623 | * @return 624 | */ 625 | public static String getStrDate4Date(Date date, String format) { 626 | if (date == null) { 627 | return ""; 628 | } else { 629 | SimpleDateFormat df = new SimpleDateFormat(format); 630 | return df.format(date); 631 | } 632 | } 633 | 634 | /** 635 | * add by gongtao 636 | *637 | * 将字符串类型的日期格式 转换为 符合要求的 Date类型的日期格式 638 | *
639 | * 640 | * @param date 641 | * @param format 642 | * @return 643 | */ 644 | public static Date getDate4StrDate(String date, String format) { 645 | if (date == null || date.trim().equals("")) { 646 | return null; 647 | } else { 648 | SimpleDateFormat df = new SimpleDateFormat(format); 649 | try { 650 | return df.parse(date); 651 | } catch (ParseException e) { 652 | return null; 653 | } 654 | } 655 | } 656 | 657 | /** 658 | * add by gongtao 计算指定日期时间之间的时间差 659 | * 660 | * @param beginStr 661 | * 开始日期字符串 662 | * @param endStr 663 | * 结束日期字符串 664 | * @param f 665 | * 时间差的形式0-秒,1-分种,2-小时,3--天 日期时间字符串格式:yyyyMMddHHmmss 666 | * */ 667 | public static int getInterval(String beginStr, String endStr, int f) { 668 | int hours = 0; 669 | try { 670 | Date beginDate = yMd_Hms.parse(beginStr); 671 | Date endDate = yMd_Hms.parse(endStr); 672 | long millisecond = endDate.getTime() - beginDate.getTime(); // 日期相减获取日期差X(单位:毫秒) 673 | /** 674 | * Math.abs((int)(millisecond/1000)); 绝对值 1秒 = 1000毫秒 675 | * millisecond/1000 --> 秒 millisecond/1000*60 - > 分钟 676 | * millisecond/(1000*60*60) -- > 小时 millisecond/(1000*60*60*24) --> 677 | * 天 678 | * */ 679 | switch (f) { 680 | case 0: // second 681 | return (int) (millisecond / 1000); 682 | case 1: // minute 683 | return (int) (millisecond / (1000 * 60)); 684 | case 2: // hour 685 | return (int) (millisecond / (1000 * 60 * 60)); 686 | case 3: // day 687 | return (int) (millisecond / (1000 * 60 * 60 * 24)); 688 | } 689 | } catch (Exception e) { 690 | e.printStackTrace(); 691 | } 692 | return hours; 693 | } 694 | 695 | /** 696 | * add by lipp 697 | *698 | * 获取起始日期前或后天数的日期 699 | *
700 | * 701 | * @param starttime 702 | * 起始日期 格式:yyyy-MM-dd 703 | * @param days 704 | * @return 705 | * @throws ParseException 706 | */ 707 | public static Date getStartDateInterval(String starttime, int days) { 708 | // 格式化起始时间 yyyyMMdd 709 | Date startDate = null; 710 | try { 711 | startDate = yyyy_MM_dd.parse(starttime); 712 | 713 | } catch (ParseException e) { 714 | e.printStackTrace(); 715 | } 716 | Calendar startTime = Calendar.getInstance(); 717 | startTime.clear(); 718 | startTime.setTime(startDate); 719 | 720 | startTime.add(Calendar.DAY_OF_YEAR, days); 721 | return startTime.getTime(); 722 | } 723 | 724 | /** 725 | * add by lipp 726 | *727 | * 获取起始日期和结束日期之间的天数 728 | *
729 | * 730 | * @param beginStr 731 | * 起始日期 732 | * @param endStr 733 | * 结束日期 734 | * @param format 735 | * 根据 日期参数的格式,传对应的SimpleDateFormat格式 736 | * @return 天数 737 | */ 738 | public static int getDaysInterval(String beginStr, String endStr, 739 | SimpleDateFormat format) { 740 | 741 | try { 742 | Date beginDate = format.parse(beginStr); 743 | Date endDate = format.parse(endStr); 744 | long millisecond = endDate.getTime() - beginDate.getTime(); // 日期相减获取日期差X(单位:毫秒) 745 | return (int) (millisecond / (1000 * 60 * 60 * 24)); 746 | } catch (ParseException e) { 747 | e.printStackTrace(); 748 | } 749 | return 0; 750 | } 751 | 752 | /** 753 | * 获取本月第一天 754 | * 755 | * @return 756 | */ 757 | public static Date getFristDayOfMonth() { 758 | Calendar calendar = Calendar.getInstance(); 759 | calendar.set(Calendar.DAY_OF_MONTH, 1); 760 | calendar.set(Calendar.HOUR_OF_DAY, 0); 761 | calendar.set(Calendar.SECOND, 0); 762 | calendar.set(Calendar.MINUTE, 0); 763 | return calendar.getTime(); 764 | 765 | } 766 | 767 | /** 768 | * 获取本月最后一天 769 | * 770 | * @return 771 | */ 772 | public static Date getLastDayOfMonth() { 773 | Calendar calendar = Calendar.getInstance(); 774 | calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1); 775 | calendar.set(Calendar.DAY_OF_MONTH, 1); 776 | calendar.set(Calendar.HOUR_OF_DAY, 0); 777 | calendar.set(Calendar.SECOND, 0); 778 | calendar.set(Calendar.MINUTE, 0); 779 | return calendar.getTime(); 780 | 781 | } 782 | 783 | /** 784 | * 获得本周一的日期 785 | * 786 | * @return 787 | * @throws ParseException 788 | */ 789 | /* 790 | * public static Date getMondayOFWeek() throws ParseException { int 791 | * mondayPlus = getMondayPlus(); GregorianCalendar currentDate = new 792 | * GregorianCalendar(); currentDate.add(Calendar.DATE, mondayPlus); Date 793 | * monday = currentDate.getTime(); String dateStr = getDateTime_I(monday); 794 | * StringBuffer sb = new StringBuffer(dateStr); 795 | * sb.append(" ").append("00:00:00"); return 796 | * parseDateStrToDate(sb.toString()); } 797 | */ 798 | 799 | /** 800 | * 获得本周星期日的日期 801 | * 802 | * @return 803 | * @throws ParseException 804 | */ 805 | /* 806 | * public static Date getCurrentWeekday() throws ParseException { int 807 | * mondayPlus = getMondayPlus(); GregorianCalendar currentDate = new 808 | * GregorianCalendar(); currentDate.add(Calendar.DATE, mondayPlus + 6); Date 809 | * monday = currentDate.getTime(); String dateStr = getDateTime_I(monday); 810 | * StringBuffer sb = new StringBuffer(dateStr); 811 | * sb.append(" ").append("00:00:00"); return 812 | * parseDateStrToDate(sb.toString()); } 813 | */ 814 | 815 | /** 816 | * 字符串时间格式转换为 Date 817 | * 818 | * @param date 819 | * 此格式 yyyy-MM-dd HH:mm:ss 820 | * @return 821 | * @throws ParseException 822 | */ 823 | /* 824 | * public static Date parseDateStrToDate(String date) throws ParseException{ 825 | * Date date_time = null; if(!StringUtil.isEmpty(date)){ date_time = 826 | * yMd_Hms.parse(date); } return date_time; } 827 | */ 828 | /** 829 | * 字符串时间格式转换为 Date 830 | * 831 | * @param date 832 | * 此格式 yyyy-MM-dd 833 | * @return 834 | * @throws ParseException 835 | */ 836 | /* 837 | * public static Date parseDateFromStr(String date) throws ParseException{ 838 | * Date date_time = null; if(!StringUtil.isEmpty(date)){ date_time = 839 | * yyyy_MM_dd.parse(date); } return date_time; } 840 | */ 841 | 842 | public static int getMondayPlus() { 843 | Calendar cd = Calendar.getInstance(); 844 | // 因为按中国礼拜一作为第一天所以这里减1 845 | int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; 846 | if (dayOfWeek == 1) { 847 | return 0; 848 | } else if (dayOfWeek == 0) { 849 | return 1 - 7; 850 | } else { 851 | return 1 - dayOfWeek; 852 | } 853 | } 854 | 855 | /** 856 | * 857 | * @param beginDate 858 | * @param endDate 859 | * @param f 860 | * 时间差的形式0:秒,1:分种,2:小时,3:天 861 | * @return 862 | */ 863 | public static int getDifferenceNum(Date beginDate, Date endDate, int f) { 864 | int result = 0; 865 | if (beginDate == null || endDate == null) { 866 | return 0; 867 | } 868 | try { 869 | // 日期相减获取日期差X(单位:毫秒) 870 | long millisecond = endDate.getTime() - beginDate.getTime(); 871 | /** 872 | * Math.abs((int)(millisecond/1000)); 绝对值 1秒 = 1000毫秒 873 | * millisecond/1000 --> 秒 millisecond/1000*60 - > 分钟 874 | * millisecond/(1000*60*60) -- > 小时 millisecond/(1000*60*60*24) --> 875 | * 天 876 | * */ 877 | switch (f) { 878 | case 0: // second 879 | return (int) (millisecond / 1000); 880 | case 1: // minute 881 | return (int) (millisecond / (1000 * 60)); 882 | case 2: // hour 883 | return (int) (millisecond / (1000 * 60 * 60)); 884 | case 3: // day 885 | return (int) (millisecond / (1000 * 60 * 60 * 24)); 886 | } 887 | } catch (Exception e) { 888 | e.printStackTrace(); 889 | } 890 | return result; 891 | } 892 | 893 | /** 894 | * 两个时间间的时间戳计算函数 895 | * 896 | * @param beginDate 897 | * @param endDate 898 | * @param f 899 | * 时间差的形式0:秒,1:分种,2:小时,3:天 900 | * @return long 秒 901 | */ 902 | public static long getDifference(Date beginDate, Date endDate, int f) { 903 | long result = 0; 904 | if (beginDate == null || endDate == null) { 905 | return 0; 906 | } 907 | try { 908 | // 日期相减获取日期差X(单位:毫秒) 909 | long millisecond = endDate.getTime() - beginDate.getTime(); 910 | /** 911 | * Math.abs((int)(millisecond/1000)); 绝对值 1秒 = 1000毫秒 912 | * millisecond/1000 --> 秒 millisecond/1000*60 - > 分钟 913 | * millisecond/(1000*60*60) -- > 小时 millisecond/(1000*60*60*24) --> 914 | * 天 915 | * */ 916 | switch (f) { 917 | case 0: // second 918 | return (millisecond / 1000); 919 | case 1: // minute 920 | return (millisecond / (1000 * 60)); 921 | case 2: // hour 922 | return (millisecond / (1000 * 60 * 60)); 923 | case 3: // day 924 | return (millisecond / (1000 * 60 * 60 * 24)); 925 | } 926 | } catch (Exception e) { 927 | e.printStackTrace(); 928 | } 929 | return result; 930 | } 931 | 932 | /** 933 | *934 | * 比较两个日期的大小,精确到秒 935 | *
936 | * 937 | * @param d1 938 | * @param d2 939 | * @author lipp@icloud-edu.com 940 | * @date 2014-06-03 941 | * @return 返回一个long类型的整数,若大于0表示第一个日期晚于第二个日期,小于0表示第一个日期早于第二个日期,否则相等 942 | */ 943 | public static long compareEachOther(Date d1, Date d2) { 944 | if (d1 == null || d2 == null) 945 | return -1; 946 | String d1Str = d1.getTime() + ""; 947 | String d2Str = d2.getTime() + ""; 948 | int l1 = d1Str.length(); 949 | int l2 = d2Str.length(); 950 | d1Str = d1Str.substring(0, l1 - 3) + "000"; 951 | d2Str = d2Str.substring(0, l2 - 3) + "000"; 952 | // System.out.println(d1Str + " " + d2Str); 953 | long long1 = Long.parseLong(d1Str); 954 | long long2 = Long.parseLong(d2Str); 955 | return long1 - long2; 956 | } 957 | 958 | public static Date getPreYearStartTime() { 959 | Calendar cal = Calendar.getInstance(); 960 | cal.add(Calendar.YEAR, -1); 961 | cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), 962 | cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); 963 | cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.YEAR)); 964 | return cal.getTime(); 965 | } 966 | 967 | public static Date getCurrentYearStartTime() { 968 | Calendar cal = Calendar.getInstance(); 969 | cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), 970 | cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0); 971 | cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.YEAR)); 972 | return cal.getTime(); 973 | } 974 | 975 | /** 976 | * 当前季度的结束时间,即2012-03-31 23:59:59 977 | * 978 | * @return 979 | */ 980 | public static Date getCurrentQuarterEndTime() { 981 | Calendar cal = Calendar.getInstance(); 982 | cal.setTime(getCurrentQuarterStartTime()); 983 | cal.add(Calendar.MONTH, 3); 984 | return cal.getTime(); 985 | } 986 | 987 | /** 988 | * 前季度的结束时间,即2012-03-31 23:59:59 989 | * 990 | * @return 991 | */ 992 | public static Date getPreQuarterEndTime() { 993 | Calendar cal = Calendar.getInstance(); 994 | cal.setTime(getPreQuarterStartTime()); 995 | cal.add(Calendar.MONTH, 3); 996 | return cal.getTime(); 997 | } 998 | 999 | /** 1000 | * 当前季度的开始时间,即2012-03-31 23:59:59 1001 | * 1002 | * @return 1003 | */ 1004 | public static Date getCurrentQuarterStartTime() { 1005 | Calendar c = Calendar.getInstance(); 1006 | // c.add(Calendar.MONTH, -3); 1007 | int currentMonth = c.get(Calendar.MONTH) + 1; 1008 | System.out.println("currentMoth" + currentMonth); 1009 | SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 1010 | SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd"); 1011 | Date now = null; 1012 | try { 1013 | if (currentMonth >= 1 && currentMonth <= 3) 1014 | c.set(Calendar.MONTH, 0); 1015 | else if (currentMonth >= 4 && currentMonth <= 6) 1016 | c.set(Calendar.MONTH, 3); 1017 | else if (currentMonth >= 7 && currentMonth <= 9) { 1018 | c.set(Calendar.MONTH, 6); 1019 | System.out.println(new SimpleDateFormat("yyyyMM").format(c 1020 | .getTime())); 1021 | } else if (currentMonth >= 10 && currentMonth <= 12) 1022 | c.set(Calendar.MONTH, 9); 1023 | c.set(Calendar.DATE, 1); 1024 | now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00"); 1025 | } catch (Exception e) { 1026 | e.printStackTrace(); 1027 | } 1028 | return now; 1029 | } 1030 | 1031 | /** 1032 | * 前季度的开始时间,即2012-03-31 23:59:59 1033 | * 1034 | * @return 1035 | */ 1036 | public static Date getPreQuarterStartTime() { 1037 | Calendar c = Calendar.getInstance(); 1038 | c.add(Calendar.MONTH, -3); 1039 | int currentMonth = c.get(Calendar.MONTH) + 1; 1040 | System.out.println("currentMoth" + currentMonth); 1041 | SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 1042 | SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd"); 1043 | Date now = null; 1044 | try { 1045 | if (currentMonth >= 1 && currentMonth <= 3) 1046 | c.set(Calendar.MONTH, 0); 1047 | else if (currentMonth >= 4 && currentMonth <= 6) 1048 | c.set(Calendar.MONTH, 3); 1049 | else if (currentMonth >= 7 && currentMonth <= 9) { 1050 | c.set(Calendar.MONTH, 6); 1051 | System.out.println(new SimpleDateFormat("yyyyMM").format(c 1052 | .getTime())); 1053 | } else if (currentMonth >= 10 && currentMonth <= 12) 1054 | c.set(Calendar.MONTH, 9); 1055 | c.set(Calendar.DATE, 1); 1056 | now = longSdf.parse(shortSdf.format(c.getTime()) + " 00:00:00"); 1057 | } catch (Exception e) { 1058 | e.printStackTrace(); 1059 | } 1060 | return now; 1061 | } 1062 | 1063 | /** 1064 | * 根据指定日期,来运算加减乘除 1065 | * 1066 | * @param date 1067 | * @param format 1068 | * @param value 1069 | * add(new Date(),"yyyy-MM-dd HH:mm:ss",-1 * 1 * 60 * 60 * 1000); 1070 | */ 1071 | public static String add(Date date, String format, long value) { 1072 | SimpleDateFormat df = new SimpleDateFormat(format); 1073 | long newValue = date.getTime() + value; 1074 | return df.format(new Date(newValue)); 1075 | } 1076 | 1077 | public static long addLong(Date date, String format, long value) { 1078 | SimpleDateFormat df = new SimpleDateFormat(format); 1079 | long newValue = date.getTime() + value; 1080 | return newValue; 1081 | } 1082 | 1083 | /** 1084 | * 计算时差 根据 long 返回时间点 1085 | * 1086 | * @param millisecond 1087 | * @return string 0天0时11分55秒 1088 | */ 1089 | public static String parseMillisecone(long millisecond) { 1090 | String time = null; 1091 | try { 1092 | long yushu_day = millisecond % (1000 * 60 * 60 * 24); 1093 | long yushu_hour = (millisecond % (1000 * 60 * 60 * 24)) 1094 | % (1000 * 60 * 60); 1095 | long yushu_minute = millisecond % (1000 * 60 * 60 * 24) 1096 | % (1000 * 60 * 60) % (1000 * 60); 1097 | @SuppressWarnings("unused") 1098 | long yushu_second = millisecond % (1000 * 60 * 60 * 24) 1099 | % (1000 * 60 * 60) % (1000 * 60) % 1000; 1100 | if (yushu_day == 0) { 1101 | return (millisecond / (1000 * 60 * 60 * 24)) + "天"; 1102 | } else { 1103 | if (yushu_hour == 0) { 1104 | return (millisecond / (1000 * 60 * 60 * 24)) + "天" 1105 | + (yushu_day / (1000 * 60 * 60)) + "时"; 1106 | } else { 1107 | if (yushu_minute == 0) { 1108 | return (millisecond / (1000 * 60 * 60 * 24)) + "天" 1109 | + (yushu_day / (1000 * 60 * 60)) + "时" 1110 | + (yushu_hour / (1000 * 60)) + "分"; 1111 | } else { 1112 | return (millisecond / (1000 * 60 * 60 * 24)) + "天" 1113 | + (yushu_day / (1000 * 60 * 60)) + "时" 1114 | + (yushu_hour / (1000 * 60)) + "分" 1115 | + (yushu_minute / 1000) + "秒"; 1116 | 1117 | } 1118 | 1119 | } 1120 | 1121 | } 1122 | 1123 | } catch (Exception e) { 1124 | e.printStackTrace(); 1125 | } 1126 | return time; 1127 | } 1128 | 1129 | public static void main(String[] args) throws ParseException { 1130 | // 获取指定long型的时间 1131 | System.out.println(parseMillisecone(436765000L)); 1132 | ; 1133 | // 获取时间差的秒数 1134 | long diff = getDifference(new Date(), new SimpleDateFormat( 1135 | "yyyy-MM-dd HH:mm:ss").parse("2016-12-10 00:00:00"), 0); 1136 | System.out.println(getDifference(new Date(), new SimpleDateFormat( 1137 | "yyyy-MM-dd HH:mm:ss").parse("2016-12-10 00:00:00"), 0)); 1138 | System.out.println("时间:" + parseMillisecone(diff)); 1139 | System.out.println("时间:" + parseMillisecone(diff * 1000)); 1140 | } 1141 | } 1142 | -------------------------------------------------------------------------------- /src/main/java/com/scienjus/utils/MD5Utils.java: -------------------------------------------------------------------------------- 1 | package com.scienjus.utils; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.security.MessageDigest; 5 | import java.security.NoSuchAlgorithmException; 6 | import java.security.SecureRandom; 7 | import java.util.Arrays; 8 | 9 | /** 10 | * MD5加密解密及字符串对比工具类 11 | * @author jacob_ye 12 | * http://www.blog.csdn.net/zranye 13 | * 盐加密和普通加密 14 | */ 15 | public class MD5Utils { 16 | private final static String HEX_NUMS_STR = "0123456789ABCDEF"; 17 | private final static Integer SALT_LENGTH = 15; 18 | 19 | /** 20 | * 将16进制字符串转换成数组 21 | * 22 | * @return byte[] 23 | * @author jacob 24 | * */ 25 | public static byte[] hexStringToByte(String hex) { 26 | /* len为什么是hex.length() / 2 ? 27 | * 首先,hex是一个字符串,里面的内容是像16进制那样的char数组 28 | * 用2个16进制数字可以表示1个byte,所以要求得这些char[]可以转化成什么样的byte[],首先可以确定的就是长度为这个char[]的一半 29 | */ 30 | int len = (hex.length() / 2); 31 | byte[] result = new byte[len]; 32 | char[] hexChars = hex.toCharArray(); 33 | for (int i = 0; i < len; i++) { 34 | int pos = i * 2; 35 | result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR 36 | .indexOf(hexChars[pos + 1])); 37 | } 38 | return result; 39 | } 40 | 41 | /** 42 | * 将数组转换成16进制字符串 43 | * 44 | * @return String 45 | * @author jacob 46 | * 47 | * */ 48 | public static String byteToHexString(byte[] salt){ 49 | StringBuffer hexString = new StringBuffer(); 50 | for (int i = 0; i < salt.length; i++) { 51 | String hex = Integer.toHexString(salt[i] & 0xFF); 52 | if(hex.length() == 1){ 53 | hex = '0' + hex; 54 | } 55 | hexString.append(hex.toUpperCase()); 56 | } 57 | return hexString.toString(); 58 | } 59 | 60 | /** 61 | * 密码验证 62 | * @param passwd 用户输入密码 63 | * @param dbPasswd 数据库保存的密码 64 | * @return 65 | * @throws NoSuchAlgorithmException 66 | * @throws UnsupportedEncodingException 67 | */ 68 | public static boolean validPasswd(String passwd, String dbPasswd) 69 | throws NoSuchAlgorithmException, UnsupportedEncodingException{ 70 | byte[] pwIndb = hexStringToByte(dbPasswd); 71 | //定义salt 72 | byte[] salt = new byte[SALT_LENGTH]; 73 | System.arraycopy(pwIndb, 0, salt, 0, SALT_LENGTH); 74 | //创建消息摘要对象 75 | MessageDigest md = MessageDigest.getInstance("MD5"); 76 | //将盐数据传入消息摘要对象 77 | md.update(salt); 78 | md.update(passwd.getBytes("UTF-8")); 79 | byte[] digest = md.digest(); 80 | //声明一个对象接收数据库中的口令消息摘要 81 | byte[] digestIndb = new byte[pwIndb.length - SALT_LENGTH]; 82 | //获得数据库中口令的摘要 83 | System.arraycopy(pwIndb, SALT_LENGTH, digestIndb, 0,digestIndb.length); 84 | //比较根据输入口令生成的消息摘要和数据库中的口令摘要是否相同 85 | if(Arrays.equals(digest, digestIndb)){ 86 | //口令匹配相同 87 | return true; 88 | }else{ 89 | return false; 90 | } 91 | } 92 | 93 | 94 | 95 | /** 96 | * 获得md5之后的16进制字符 +盐值加密 97 | * @param passwd 用户输入密码字符 98 | * @return String md5加密后密码字符 99 | * @throws NoSuchAlgorithmException 100 | * @throws UnsupportedEncodingException 101 | */ 102 | public static String getEncryptedPwd(String passwd) 103 | throws NoSuchAlgorithmException, UnsupportedEncodingException{ 104 | //拿到一个随机数组,作为盐 105 | byte[] pwd = null; 106 | SecureRandom sc= new SecureRandom(); 107 | byte[] salt = new byte[SALT_LENGTH]; 108 | sc.nextBytes(salt); 109 | 110 | //声明摘要对象,并生成 111 | MessageDigest md = MessageDigest.getInstance("MD5"); 112 | md.update(salt); 113 | md.update(passwd.getBytes("UTF-8")); 114 | byte[] digest = md.digest(); 115 | 116 | pwd = new byte[salt.length + digest.length]; 117 | System.arraycopy(salt, 0, pwd, 0, SALT_LENGTH); 118 | System.arraycopy(digest, 0, pwd, SALT_LENGTH, digest.length); 119 | return byteToHexString(pwd); 120 | } 121 | 122 | 123 | /** 124 | * 任意一种文字加密为md5(不可逆算法) +不加盐加密 125 | * Can convert a file to MD5 126 | * @param text 127 | * @return md5 128 | */ 129 | public static String encode(String text){ 130 | try { 131 | MessageDigest digest = MessageDigest.getInstance("md5"); 132 | byte[] buffer = digest.digest(text.getBytes()); 133 | // byte -128 ---- 127 134 | StringBuffer sb = new StringBuffer(); 135 | for (byte b : buffer) { 136 | int a = b & 0xff; 137 | // Log.d(TAG, "" + a); 138 | String hex = Integer.toHexString(a); 139 | 140 | if (hex.length() == 1) { 141 | hex = 0 + hex; 142 | } 143 | sb.append(hex); 144 | } 145 | return sb.toString(); 146 | } catch (NoSuchAlgorithmException e) { 147 | e.printStackTrace(); 148 | } 149 | return null; 150 | } 151 | 152 | public static void main(String[] args) { 153 | System.out.println(encode("123456")); 154 | try { 155 | String pwd=getEncryptedPwd("123456"); 156 | System.out.println(pwd); 157 | System.out.println(validPasswd("123456", "9C8C6E5E844BE0E337CECADF2ED6F71E692B8943C5F2AB248194232D7997EB")); 158 | } catch (NoSuchAlgorithmException e) { 159 | e.printStackTrace(); 160 | } catch (UnsupportedEncodingException e) { 161 | e.printStackTrace(); 162 | } 163 | } 164 | } -------------------------------------------------------------------------------- /src/main/java/com/scienjus/utils/RSAUtils.java: -------------------------------------------------------------------------------- 1 | package com.scienjus.utils; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.security.Key; 5 | import java.security.KeyFactory; 6 | import java.security.KeyPair; 7 | import java.security.KeyPairGenerator; 8 | import java.security.PrivateKey; 9 | import java.security.PublicKey; 10 | import java.security.Signature; 11 | import java.security.interfaces.RSAPrivateKey; 12 | import java.security.interfaces.RSAPublicKey; 13 | import java.security.spec.PKCS8EncodedKeySpec; 14 | import java.security.spec.X509EncodedKeySpec; 15 | import java.util.HashMap; 16 | import java.util.Map; 17 | 18 | import javax.crypto.Cipher; 19 | 20 | /** 21 | *22 | * RSA公钥/私钥/签名工具包 23 | *
24 | *25 | * 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman) 26 | *
27 | *
28 | * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式
29 | * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,
30 | * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
31 | *
71 | * 生成密钥对(公钥和私钥) 72 | *
73 | * 74 | * @return 75 | * @throws Exception 76 | */ 77 | public static Map92 | * 用私钥对信息生成数字签名 93 | *
94 | * 95 | * @param data 96 | * 已加密数据 97 | * @param privateKey 98 | * 私钥(BASE64编码) 99 | * 100 | * @return 101 | * @throws Exception 102 | */ 103 | public static String sign(byte[] data, String privateKey) throws Exception { 104 | byte[] keyBytes = Base64Utils.decode(privateKey); 105 | PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); 106 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 107 | PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec); 108 | Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); 109 | signature.initSign(privateK); 110 | signature.update(data); 111 | return Base64Utils.encode(signature.sign()); 112 | } 113 | 114 | /** 115 | *116 | * 校验数字签名 117 | *
118 | * 119 | * @param data 120 | * 已加密数据 121 | * @param publicKey 122 | * 公钥(BASE64编码) 123 | * @param sign 124 | * 数字签名 125 | * 126 | * @return 127 | * @throws Exception 128 | * 129 | */ 130 | public static boolean verify(byte[] data, String publicKey, String sign) 131 | throws Exception { 132 | byte[] keyBytes = Base64Utils.decode(publicKey); 133 | X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes); 134 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 135 | PublicKey publicK = keyFactory.generatePublic(keySpec); 136 | Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); 137 | signature.initVerify(publicK); 138 | signature.update(data); 139 | return signature.verify(Base64Utils.decode(sign)); 140 | } 141 | 142 | /** 143 | *144 | * 私钥解密 145 | *
146 | * 147 | * @param encryptedData 148 | * 已加密数据 149 | * @param privateKey 150 | * 私钥(BASE64编码) 151 | * @return 152 | * @throws Exception 153 | */ 154 | public static byte[] decryptByPrivateKey(byte[] encryptedData, 155 | String privateKey) throws Exception { 156 | byte[] keyBytes = Base64Utils.decode(privateKey); 157 | PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); 158 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 159 | Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); 160 | Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); 161 | cipher.init(Cipher.DECRYPT_MODE, privateK); 162 | int inputLen = encryptedData.length; 163 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 164 | int offSet = 0; 165 | byte[] cache; 166 | int i = 0; 167 | // 对数据分段解密 168 | while (inputLen - offSet > 0) { 169 | if (inputLen - offSet > MAX_DECRYPT_BLOCK) { 170 | cache = cipher 171 | .doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); 172 | } else { 173 | cache = cipher 174 | .doFinal(encryptedData, offSet, inputLen - offSet); 175 | } 176 | out.write(cache, 0, cache.length); 177 | i++; 178 | offSet = i * MAX_DECRYPT_BLOCK; 179 | } 180 | byte[] decryptedData = out.toByteArray(); 181 | out.close(); 182 | return decryptedData; 183 | } 184 | 185 | /** 186 | *187 | * 公钥解密 188 | *
189 | * 190 | * @param encryptedData 191 | * 已加密数据 192 | * @param publicKey 193 | * 公钥(BASE64编码) 194 | * @return 195 | * @throws Exception 196 | */ 197 | public static byte[] decryptByPublicKey(byte[] encryptedData, 198 | String publicKey) throws Exception { 199 | byte[] keyBytes = Base64Utils.decode(publicKey); 200 | X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); 201 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 202 | Key publicK = keyFactory.generatePublic(x509KeySpec); 203 | Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); 204 | cipher.init(Cipher.DECRYPT_MODE, publicK); 205 | int inputLen = encryptedData.length; 206 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 207 | int offSet = 0; 208 | byte[] cache; 209 | int i = 0; 210 | // 对数据分段解密 211 | while (inputLen - offSet > 0) { 212 | if (inputLen - offSet > MAX_DECRYPT_BLOCK) { 213 | cache = cipher 214 | .doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK); 215 | } else { 216 | cache = cipher 217 | .doFinal(encryptedData, offSet, inputLen - offSet); 218 | } 219 | out.write(cache, 0, cache.length); 220 | i++; 221 | offSet = i * MAX_DECRYPT_BLOCK; 222 | } 223 | byte[] decryptedData = out.toByteArray(); 224 | out.close(); 225 | return decryptedData; 226 | } 227 | 228 | /** 229 | *230 | * 公钥加密 231 | *
232 | * 233 | * @param data 234 | * 源数据 235 | * @param publicKey 236 | * 公钥(BASE64编码) 237 | * @return 238 | * @throws Exception 239 | */ 240 | public static byte[] encryptByPublicKey(byte[] data, String publicKey) 241 | throws Exception { 242 | byte[] keyBytes = Base64Utils.decode(publicKey); 243 | X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); 244 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 245 | Key publicK = keyFactory.generatePublic(x509KeySpec); 246 | // 对数据加密 247 | Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); 248 | cipher.init(Cipher.ENCRYPT_MODE, publicK); 249 | int inputLen = data.length; 250 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 251 | int offSet = 0; 252 | byte[] cache; 253 | int i = 0; 254 | // 对数据分段加密 255 | while (inputLen - offSet > 0) { 256 | if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { 257 | cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); 258 | } else { 259 | cache = cipher.doFinal(data, offSet, inputLen - offSet); 260 | } 261 | out.write(cache, 0, cache.length); 262 | i++; 263 | offSet = i * MAX_ENCRYPT_BLOCK; 264 | } 265 | byte[] encryptedData = out.toByteArray(); 266 | out.close(); 267 | return encryptedData; 268 | } 269 | 270 | /** 271 | *272 | * 私钥加密 273 | *
274 | * 275 | * @param data 276 | * 源数据 277 | * @param privateKey 278 | * 私钥(BASE64编码) 279 | * @return 280 | * @throws Exception 281 | */ 282 | public static byte[] encryptByPrivateKey(byte[] data, String privateKey) 283 | throws Exception { 284 | byte[] keyBytes = Base64Utils.decode(privateKey); 285 | PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); 286 | KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 287 | Key privateK = keyFactory.generatePrivate(pkcs8KeySpec); 288 | Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); 289 | cipher.init(Cipher.ENCRYPT_MODE, privateK); 290 | int inputLen = data.length; 291 | ByteArrayOutputStream out = new ByteArrayOutputStream(); 292 | int offSet = 0; 293 | byte[] cache; 294 | int i = 0; 295 | // 对数据分段加密 296 | while (inputLen - offSet > 0) { 297 | if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { 298 | cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); 299 | } else { 300 | cache = cipher.doFinal(data, offSet, inputLen - offSet); 301 | } 302 | out.write(cache, 0, cache.length); 303 | i++; 304 | offSet = i * MAX_ENCRYPT_BLOCK; 305 | } 306 | byte[] encryptedData = out.toByteArray(); 307 | out.close(); 308 | return encryptedData; 309 | } 310 | 311 | /** 312 | *313 | * 获取私钥 314 | *
315 | * 316 | * @param keyMap 317 | * 密钥对 318 | * @return 319 | * @throws Exception 320 | */ 321 | public static String getPrivateKey(Map329 | * 获取公钥 330 | *
331 | * 332 | * @param keyMap 333 | * 密钥对 334 | * @return 335 | * @throws Exception 336 | */ 337 | public static String getPublicKey(Map