Base64 encoding and decoding, garbled

 

1. Coding

 

1.1. Screenshot of encoded content

1.2. Encoding code

import java.util.Base64; 导入java util包


 public static void main(String[] args) {
        String content = "这是需要编码的一些内容1";
        //Base64编码
                Base64.Encoder encoder = Base64.getEncoder();
        //根据指定字符编码对数据进行Base64编码
        try {
            String encodeContent = encoder.encodeToString(content.getBytes("UTF-8"));
            System.out.println("Base64编码后的内容为:"+encodeContent);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

1.3. Output encoding result

 

2. Decoding

 

2.1. Decoded content screenshot

Use the encrypted content above to decode

2.2. Decoding code

 public static void main(String[] args) {
        String b="6L+Z5piv6ZyA6KaB57yW56CB55qE5LiA5Lqb5YaF5a65MQ==";
        try {
            Base64.Decoder decoder = Base64.getDecoder();
            byte[] bytes = decoder.decode(b);
            String text = new String(bytes,"UTF-8");
            System.out.println("这是解码之后的内容:"+text);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

2.3. Output decoding result

 

3. Encoding garbled

 

If the encrypted character encoding is UTF-8 and the decoded character encoding is GBK, garbled characters will occur

Such as:

Output result:

Therefore, when encoding and decoding, the same character encoding is used to avoid garbled characters in Chinese

Published 115 original articles · Like 58 · Visits 160,000+

Guess you like

Origin blog.csdn.net/luChenH/article/details/101058615