Base64转化过程

 什么是base64?

Base64是网络上最常见的用于传输8Bit字节码的编码方式之一,Base64就是一种基于64个可打印字符来表示二进制数据的方法。可查看RFC2045~RFC2049,上面有MIME的详细规范。Base64编码是从二进制到字符的过程

查询百度,解释了编码过程的原理:

 

然后在将原理翻译成代码。


/**
 * 3*8=4*6
 * Base64 转化过程 首先,讲数据转化为byte数组,然后对数组中的byte依次转化为根据 ASCII码表转化为2进制,
 * 然后 将二进制 拼接,3个8位,拼接成 4个6位,然后 对4个进行补0 然后转化为10进制,然后查询ASCII码表,得到
 * 英文
 */
public class Base64Test {

    /**
     * BASE64解密
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    /**
     * BASE64加密
     * @param key
     * @return
     * @throws Exception
     */
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    /**
     * 十进制转2进制
     * @param b 接收的10进制数字
     * @throws Exception
     */
    private static String TenToSend(byte b){
        List<Integer> aByte = getByte(b);
        StringBuffer stringBuffer = new StringBuffer();
        if(aByte.size()<8){
            int loopcount = 8 - aByte.size(); //循环次数
            for (int i = 0; i< loopcount; i ++){
                stringBuffer.append("0");
            }
        }
        for (int i = 0; i< aByte.size(); i ++){
            stringBuffer.append(aByte.get(i));
        }
        return stringBuffer.toString();
    }

    /**
     * 转化
     * @param b
     * @return
     */
    private static List<Integer> getByte(int b){
        List<Integer> list = new ArrayList<Integer>();
        while(b>=1){
            int i = b % 2;
            b = b / 2;
            list.add(i);
        }

        for(int i = 0;i<list.size()/2;i++){
            Integer end = list.get(list.size() - 1 - i);
            Integer oldEnd = list.set(i, end);
            list.set(list.size()- 1 - i,oldEnd);
        }
        return list;
    }


    public static void main(String[] args) throws Exception {

        byte[] bytes = "s13".getBytes();
        for (int i = 0 ;i<bytes.length;i++){
            System.out.println(bytes[i]);
            System.out.println(TenToSend(bytes[i]));
        }
        String base64 = encryptBASE64(bytes);
        System.out.println(base64);
    }




}

自己研究研究的,嘻嘻

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值