Android -- base64 encryption and decryption algorithm

Keywords: Java encoding network Hibernate

Base64 is one of the most common encoding methods used to transmit 8Bit bytecode on the network. Base64 is a method based on 64 printable characters to represent binary data. You can view RFC2045 ~ RFC2049, which has the detailed specification of MIME.


Base64 encoding is a binary to character process that can be used to pass long identity information in an HTTP environment. For example, in the Java Persistence system Hibernate, Base64 is used to encode a long unique identifier (usually a 128 bit UUID) into a string, which is used as a parameter in the HTTP form and HTTP GET URL. In other applications, binary data is often encoded in a form suitable for placement in URLs, including hidden form fields. At this time, Base64 encoding is unreadable and can only be read after decoding.

 

Before Java 8.0, add Jar package


What to do after Java 8
In the java.util suite of Java 8, a new category of Base64 is added, which can be used to process the encoding and decoding of Base64. The usage is as follows:

import java.nio.charset.StandardCharsets;

public class ABase64 {

    public static void main(String[] args) {
        String password = "Hello 123456";
        //encryption
        String encoded = java.util.Base64.getEncoder().encodeToString(password.getBytes(StandardCharsets.UTF_8));
        //Decrypt
        String decoded = new String(java.util.Base64.getDecoder().decode(encoded), StandardCharsets.UTF_8);
        System.out.println(encoded);
        System.out.println(decoded);
        showBase64();
    }


    private static void showBase64() {

        try {
            final java.util.Base64.Decoder decoder = java.util.Base64.getDecoder();
            final java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
            final String text = "Hello Little fool";
            final byte[] textByte = text.getBytes("UTF-8");
            //Code
            final String encodedText = encoder.encodeToString(textByte);
            System.out.println(encodedText);
            //Decode
            System.out.println(new String(decoder.decode(encodedText), "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Journal:

Posted by Francois on Tue, 15 Oct 2019 08:52:31 -0700