https://everleaf.blogspot.com/search/label/PHP

10/24/2023

Java base64 text encoding

Dibawah ini adalah fungsi statis untuk memanggil base64 encode dengan data type return String plaintext
1
2
3
4
5
6
7
8
private static String encodeData(String e) {
    try {
        return new String(Base64.getEncoder().encode(e.getBytes()));
    } catch (Exception ex) {
        return e;
    }
}
Dibawah ini adalah fungsi statis untuk memanggil base64 decode dengan data type return String plaintext
1
2
3
4
5
6
7
8
private static String decodeData(String e) {
    try {
        return new String(Base64.getDecoder().decode(e.getBytes()));
    } catch (Exception ex) {
        return e;
    }
}}
}
Simpan script java dibawah ini dengan nama HelloWorld.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.util.Base64;
 
class HelloWorld {
     
    private static String encodeData(String e) {
        try {
            return new String(Base64.getEncoder().encode(e.getBytes()));
        } catch (Exception ex) {
            return e;
        }
    }
     
    private static String decodeData(String e) {
        try {
            return new String(Base64.getDecoder().decode(e.getBytes()));
        } catch (Exception ex) {
            return e;
        }
    }
 
 
    public static void main(String[] args) {
        String mytext = "hello world java";
         
        String encoded_string = encodeData(mytext);
        System.out.println("base64 encoded text : "+encoded_string+"\n");
         
        String decoded_string = decodeData(encoded_string);
        System.out.println("base64 decoded text : "+decoded_string+"\n");
    }
}
Jalankan script java : java HelloWorld.java, hasilnya:
1
2
3
base64 encoded text : aGVsbG8gd29ybGQgamF2YQ==
 
base64 decoded text : hello world java

No comments:

Post a Comment

Diharapkan berkomentar dengan sopan dan santun, terimakasih.