Base64加密与解密的三种方法

前言:

加密与解密一直是程序猿经常需要面对的东东,下面了解一下常见的base64的三种加密与解密的方法。

public static final String str="zhangtao";

1. 基于JDK

public static void  JdkBase64(){
        try {
            //加密
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(str.getBytes());
            System.out.println("encode-->:"+encode);
            //解密
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] str = decoder.decodeBuffer(encode);
            System.out.println("decode-->:"+new String(str));
        } catch (IOException e) {
            e.printStackTrace();
        }
    } 

2. 基于commonsCodes

public static void commonsCodesBase64() {
        byte[] encodeBytes = org.apache.commons.codec.binary.Base64.encodeBase64(str.getBytes());
        String encode = new String(encodeBytes);
        System.out.println("encode-->:"+encode);

        byte[] decode = org.apache.commons.codec.binary.Base64.decodeBase64(encode);
        System.out.println("decode-->:"+new String(decode));

    }

3. 基于bouncyCastle

public static void bouncyCastleBase64() {
        byte[] encode = org.bouncycastle.util.encoders.Base64.encode(str.getBytes());
        System.out.println("encode-->:"+new String(encode));

        byte[] decode = org.bouncycastle.util.encoders.Base64.decode(encode);
        System.out.println("decode-->:"+new String(decode));

    }

4. 三种结果

    public static void main(String[] args){
        JdkBase64(); 
        commonsCodesBase64();
        bouncyCastleBase64();
    }
    encode-->:emhhbmd0YW8=
    decode-->:zhangtao
    encode-->:emhhbmd0YW8=
    decode-->:zhangtao
    encode-->:emhhbmd0YW8=
    decode-->:zhangtao

5. 需要的包
加解密包的引入地址

你可能感兴趣的:(Java基础知识)