【Java/加解密】不算加密的加密-base64加解密(使用Java8的Base64实现)

前篇讲述了使用Apache的Codec来进行Base64加解密的情况,这回来看直接使用JDK1.8的Base64方案。

代码:

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Base64_Test {
    public static void main(String[] args) {
        String originalText="Let’s Build a Giant Airship 青海长云暗雪山";
        System.out.println("原文=	"+originalText);
        
        // 原文数组
        byte[] byteContent = originalText.getBytes(StandardCharsets.UTF_8);
        
        // 经base64“加密”后的数组
        byte[] encodedArr=Base64.getEncoder().encode(byteContent);
        
        // 供传递的“密文”
        String cipheredTxt=new String(encodedArr,StandardCharsets.UTF_8);
        System.out.println("密文=	"+cipheredTxt);
        
        // 将收到的“密文”用base64“解密”
        byte[] decodedArr=Base64.getDecoder().decode(cipheredTxt);
        
        // 最终结果
        String cipherTxt=new String(decodedArr,StandardCharsets.UTF_8);
        System.out.println("解密后=	"+cipherTxt); 
    }
}

输出:

原文=    Let’s Build a Giant Airship 青海长云暗雪山
密文=    TGV04oCZcyBCdWlsZCBhIEdpYW50IEFpcnNoaXAg6Z2S5rW36ZW/5LqR5pqX6Zuq5bGx
解密后=    Let’s Build a Giant Airship 青海长云暗雪山

与前篇两相对比以下,发现生成的密文是不一样的,也就是说两种实现使用的符号映射表是不一样的,看来codec和JDK1.8的实现不能互通。即codec加密的JDK1.8不能解,反之亦然,这点值得注意。

END

原文地址:https://www.cnblogs.com/heyang78/p/15367879.html