1. 生成MD5
1.1 使用 Spring自带的DigestUtils
包: org.springframework.util.DigestUtils
package com.hui.javalearn;
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.util.DigestUtils;
@SpringBootTest class JavaLearnApplicationTests { @Test void md5(){ String token = "123"; String s = DigestUtils.md5DigestAsHex(token.getBytes()).toUpperCase(); System.out.println(s); } }
|
1.2 使用JDK自带MessageDigest
包: java.security.MessageDigest
package com.hui.javalearn;
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest;
import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;
@SpringBootTest class JavaLearnApplicationTests {
@Test void md52() throws NoSuchAlgorithmException { String token = "123"; MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] digest = md5.digest(token.getBytes()); String s = new BigInteger(1,digest).toString(16); System.out.println("md52=>"+s); } }
|
1.3 使用Apache开源组织提供commons-codec
包: org.apache.commons.codec.digest.DigestUtils
package com.hui.javalearn;
import org.apache.commons.codec.digest.DigestUtils; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest public class TestDigest {
@Test void testMd5ByCommonCodec() { String s = "123"; String s1 = DigestUtils.md5Hex(s); System.out.println(s1); } }
|
2. 生成Sha1
2.1 使用Apache开源组织提供commons-codec
包: org.apache.commons.codec.digest.DigestUtils
String str = "abc"; String s1 = DigestUtils.sha1Hex(str);
|
2.2 使用Jdk 生成: 方式1
包: java.security.MessageDigest
public String testSha1ByJDK(String str) { if (str == null || str.length() == 0) { return null; } try { char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; MessageDigest sha1 = MessageDigest.getInstance("SHA1"); sha1.update(str.getBytes("UTF-8")); byte[] digest = sha1.digest(); int length = digest.length; char[] buf = new char[length * 2]; int k = 0; for (int i = 0; i < length; i++) { byte b = digest[i]; buf[k++] = hexDigits[b >>> 4 & 0xf]; buf[k++] = hexDigits[b & 0xf]; } return new String(buf); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { e.printStackTrace(); return null; } }
|
2.3 使用Jdk 生成: 方式2
public String testSha1ByJDK2(String str){ MessageDigest sha1 = null; try { sha1 = MessageDigest.getInstance("SHA1"); sha1.update(str.getBytes("UTF-8")); byte[] digest = sha1.digest(); return String.format("%040x", new BigInteger(1, digest)); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e ) { e.printStackTrace(); return null; } }
|
3.Base64
包: java.util.Base64
String str = "abc"; String encodeStr = Base64.getEncoder().encodeToString(str.getBytes());
byte[] decode = Base64.getDecoder().decode(encodeStr.getBytes()); String decodeStr = new String(decode);
|