2018年10月10日 星期三

【Java】Base64編碼與解碼


程式碼:
package ciphertest;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import java.util.Scanner;

public class Base64_Test {

    public static void main(String[] args) {
        Scanner src = new Scanner(System.in);
        while (true) {
            System.out.print("mode:");
            String mode = src.nextLine();
            if (mode.equals("x")) {
                System.exit(0);
            }

            System.out.print("input:");
            String contain = src.nextLine();

            if (mode.equals("e")) {
                System.out.println(encode(contain));
            } else if (mode.equals("d")) {
                try {
                    System.out.println(decode(contain));
                } catch (Base64DecodingException e) {
                    System.err.println(e.getMessage());
                }
            }

        }
    }

    static String encode(String msg) {
        byte[] bytes_str = msg.getBytes();
        return Base64.encode(bytes_str);
    }

    static String decode(String msg) throws Base64DecodingException {
        return new String(Base64.decode(msg));
    }
}



執行


Console
mode:e
input:Hello!! I am Vincent Yeh.
SGVsbG8hISBJIGFtIFZpbmNlbnQgWWVoLg==
mode:d
input:SGVsbG8hISBJIGFtIFZpbmNlbnQgWWVoLg==
Hello!! I am Vincent Yeh. mode:x

參考資料

沒有留言:

張貼留言