java中常用的加密算法(實戰教學、非概念)

一、Base64

主要用於Byte數組 和字符串之間的轉換。

在rt.jar 裏的sun.misc裏的兩個類很常用BASE64Encoder 和 BASE64Decoder

        final BASE64Encoder encoder = new BASE64Encoder();
        final BASE64Decoder decoder = new BASE64Decoder();
        final String text = "hello world. 你好世界";
        final byte[] textByte = text.getBytes("UTF-8");
        //編碼
        final String encodedText = encoder.encode(textByte);
        System.out.println(encodedText);
    
        //解碼
        System.out.println(new String(decoder.decodeBuffer(encodedText), "UTF-8"));

二、MD5

可以用於byte[] 之間的轉換

可以使用spring裏 org.springframework.util包下的DigestUtils,也可以使用jdk裏sercurity包內置的DigestUtils

import java.security.MessageDigest;        

System.out.println(new String(DigestUtils.md5Digest(textByte)));




import org.springframework.util.DigestUtils;

String s = DigestUtils.md5DigestAsHex(text.getBytes("UTF-8"));

具體實現邏輯請參考MD5實現過程

需要先填充數據對512取餘,然後算哈希值,還要找非線性函數做映射,循環的加工最後一拼接,很複雜的不可逆算法。

因此   MD5不可解密。

 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章