Base64编码

何时使用:加密后通常配合Base64进行编码
Base64编码 – 在线工具
Base64
java8 Base64

package com.example.demo.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * @description: Base64编码
 * @create: 2020/05/14 21:34
 **/
public class EncryptBase64AndDecryptBase64 {

    /** 字符编码. */
    private static final String CHARSET = "UTF-8";

    public static void main(String[] args) throws Exception{
        byte[] encryptAES = "你好".getBytes(CHARSET);
        String encryptBase64 = encryptBase64(encryptAES);
        System.out.println("encryptBase64 = " + encryptBase64);

        byte[] decryptBase64 = decryptBase64(encryptBase64);
        System.out.println(new String(decryptBase64));
    }

    /**
     * BASE64 加密
     *
     * @param cleartext 明文
     * @return 密文
     */
    public static String encryptBase64(byte[] cleartext) {
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String cipherText = base64Encoder.encode(cleartext);
        return cipherText;
    }

    /**
     * BASE64 解密
     *
     * @param cipherText 密文
     * @return 明文
     */
    public static byte[] decryptBase64(String cipherText) {
        try {
            BASE64Decoder base64Decoder = new BASE64Decoder();
            byte[] cipherTextBytes = base64Decoder.decodeBuffer(cipherText);
            return cipherTextBytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 解密错误返回 null
        return null;
    }
}

运行结果:

encryptBase64 = 5L2g5aW9
你好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值