Java語言實現 Base64 加密 & 解密

  • Base64是網絡上最常見的用於傳輸8Bit字節碼的編碼方式之一,Base64就是一種基於64個可打印字符來表示二進制數據的方法。
  • Base64編碼是從二進制到字符的過程,可用於在HTTP環境下傳遞較長的標識信息。
  • 採用Base64編碼具有不可讀性,需要解碼後才能閱讀。
  • Base64由於以上優點被廣泛應用於計算機的各個領域。
  • 本文講解如何使用Java語言實現Base64的加密和解密。(基於 JDK 1.8 的新增功能 Base64 特性)

初始版本

代碼如下:

import java.io.UnsupportedEncodingException;
import java.util.Base64;

/**
 * @author Miracle Luna
 * @version 1.0
 * @date 2019/7/3 18:55
 */
public class Base64Converter {

    final static Base64.Encoder encoder = Base64.getEncoder();
    final static Base64.Decoder decoder = Base64.getDecoder();

    /**
     * 給字符串加密
     * @param text
     * @return
     */
    public static String encode(String text) {
        byte[] textByte = new byte[0];
        try {
            textByte = text.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String encodedText = encoder.encodeToString(textByte);
        return encodedText;
    }

    /**
     * 將加密後的字符串進行解密
     * @param encodedText
     * @return
     */
    public static String decode(String encodedText) {
        String text = null;
        try {
            text = new String(decoder.decode(encodedText), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return text;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {

        String username = "Miracle Luna";
        String password = "p@sSW0rd";

        // 加密
        System.out.println("====  [加密後] 用戶名/密碼  =====");
        System.out.println(Base64Converter.encode(username));
        System.out.println(Base64Converter.encode(password));

        // 解密
        System.out.println("\n====  [解密後] 用戶名/密碼  =====");
        System.out.println(Base64Converter.decode(Base64Converter.encode(username)));
        System.out.println(Base64Converter.decode(Base64Converter.encode(password)));
    }
}

運行結果如下:

====  [加密後] 用戶名/密碼  =====
TWlyYWNsZSBMdW5h
cEBzU1cwcmQ=

====  [解密後] 用戶名/密碼  =====
Miracle Luna
p@sSW0rd

改進版本(推薦)

代碼如下:

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

/**
 * @author Miracle Luna
 * @version 1.0
 * @date 2019/7/3 18:55
 */
public class Base64Util {

    final static Base64.Encoder encoder = Base64.getEncoder();
    final static Base64.Decoder decoder = Base64.getDecoder();

    /**
     * 給字符串加密
     * @param text
     * @return
     */
    public static String encode(String text) {
//        byte[] textByte = text.getBytes(StandardCharsets.UTF_8);
//        String encodedText = encoder.encodeToString(textByte);
//        return encodedText;
        return encoder.encodeToString(text.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 將加密後的字符串進行解密
     * @param encodedText
     * @return
     */
    public static String decode(String encodedText) {
        return new String(decoder.decode(encodedText), StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {

        String username = "Miracle Luna";
        String password = "p@sSW0rd";

        // 加密
        System.out.println("====  [加密後] 用戶名/密碼  =====");
        System.out.println(Base64Util.encode(username));
        System.out.println(Base64Util.encode(password));

        // 解密
        System.out.println("\n====  [解密後] 用戶名/密碼  =====");
        System.out.println(Base64Util.decode(Base64Util.encode(username)));
        System.out.println(Base64Util.decode(Base64Util.encode(password)));
    }
}

運行結果如下:

====  [加密後] 用戶名/密碼  =====
TWlyYWNsZSBMdW5h
cEBzU1cwcmQ=

====  [解密後] 用戶名/密碼  =====
Miracle Luna
p@sSW0rd

 

PS:

改進版本使用了 StandardCharsets.UTF_8 代替了 "UTF-8"

所以,沒有拋出初始版本的 UnsupportedEncodingException 異常。

StandardCharsets.java 源碼如下:

/*
 * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 */
package java.nio.charset;

/**
 * Constant definitions for the standard {@link Charset Charsets}. These
 * charsets are guaranteed to be available on every implementation of the Java
 * platform.
 *
 * @see <a href="Charset#standard">Standard Charsets</a>
 * @since 1.7
 */
public final class StandardCharsets {

    private StandardCharsets() {
        throw new AssertionError("No java.nio.charset.StandardCharsets instances for you!");
    }
    /**
     * Seven-bit ASCII, a.k.a. ISO646-US, a.k.a. the Basic Latin block of the
     * Unicode character set
     */
    public static final Charset US_ASCII = Charset.forName("US-ASCII");
    /**
     * ISO Latin Alphabet No. 1, a.k.a. ISO-LATIN-1
     */
    public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
    /**
     * Eight-bit UCS Transformation Format
     */
    public static final Charset UTF_8 = Charset.forName("UTF-8");
    /**
     * Sixteen-bit UCS Transformation Format, big-endian byte order
     */
    public static final Charset UTF_16BE = Charset.forName("UTF-16BE");
    /**
     * Sixteen-bit UCS Transformation Format, little-endian byte order
     */
    public static final Charset UTF_16LE = Charset.forName("UTF-16LE");
    /**
     * Sixteen-bit UCS Transformation Format, byte order identified by an
     * optional byte-order mark
     */
    public static final Charset UTF_16 = Charset.forName("UTF-16");
}

推薦一個在線 Base64 加密&解密的網頁:https://base64.supfree.net/

對 p@sSW0rd 進行加密,效果如下:

加密前:

加密後:

 

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