- package com.aarony.test;
- import java.io.IOException;
- import java.security.MessageDigest;
- import sun.misc.BASE64Decoder;
- import sun.misc.BASE64Encoder;
- public class DigestDemo {
- /**
- *
- * 此方法描述的是: base64 解码
- *
- * @author: Aarony
- * @version: 2018 年 6 月 20 日 下午 9:16:57
- */
- public static byte[] base642byte(String base64) throws IOException {
- BASE64Decoder decoder = new BASE64Decoder();
- return decoder.decodeBuffer(base64);
- }
- /**
- *
- * 此方法描述的是: base 64 编码
- *
- * @author: Aarony
- * @version: 2018 年 6 月 20 日 下午 9:15:14
- */
- public static String byte2base64(byte[] bytes) {
- BASE64Encoder base = new BASE64Encoder();
- return base.encode(bytes);
- }
- /**
- *
- * 此方法描述的是: 16 位数转换成 byte
- *
- * @author: Aarony
- * @version: 2018 年 6 月 20 日 下午 9:17:43
- */
- public static byte[] hex2bytes(String hex) {
- byte[] bytes = new byte[hex.length() / 2];
- for (int i = 0; i <hex.length(); i = i + 2) {
- String subStr = hex.substring(i, i + 2);
- boolean negative = false;
- int inte = Integer.parseInt(subStr, 16);
- if (inte> 127) {
- negative = true;
- }
- if (inte == 128) {
- inte = -128;
- } else if (negative) {
- inte = 0 - (inte & 0x7f);
- }
- byte b = (byte) inte;
- bytes[i / 2] = b;
- }
- return bytes;
- }
- /**
- *
- * 此方法描述的是: byte 转换成 16 位
- *
- * @author: Aarony
- * @version: 2018 年 6 月 20 日 下午 9:17:16
- */
- public static String bytes2hex(byte[] bytes) {
- StringBuilder sBuilder = new StringBuilder();
- for (int i = 0; i < bytes.length; i++) {
- byte b = bytes[i];
- boolean negative = false;
- if (b < 0) {
- negative = true;
- }
- int inte = Math.abs(b);
- if (negative) {
- inte = inte | 0x80;
- }
- String temp = Integer.toHexString(inte & 0xff);
- if (temp.length() == 1) {
- sBuilder.append("0");
- }
- sBuilder.append(temp.toLowerCase());
- }
- return sBuilder.toString();
- }
- /**
- *
- * 此方法描述的是: sha
- *
- * @author: Aarony
- * @version: 2018 年 6 月 20 日 下午 9:18:11
- */
- public static byte[] testSHA(String content) throws Exception {
- MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
- return messageDigest.digest(content.getBytes("utf-8"));
- }
- /**
- *
- * 此方法描述的是: md5
- *
- * @author: Aarony
- * @version: 2018 年 6 月 20 日 下午 9:18:20
- */
- public static byte[] testMD5(String content) throws Exception {
- MessageDigest messageDigest = MessageDigest.getInstance("MD5");
- byte[] bytes = messageDigest.digest(content.getBytes("utf-8"));
- return bytes;
- }
- }
来源: http://www.bubuko.com/infodetail-2652423.html