zoukankan      html  css  js  c++  java
  • Java 加密 base64 encode

    【前言】

    计算机中的数据都是二进制的,不管是字符串还是文件,而加密后的也是二进制的,

    而我们要看到的往往是字符串,本文就介绍了将byte[]转为各种进制以及base64编码。


    【base64】

    是一种编码方式,可以理解为复杂的进制,很多算法加密后输出的都是byte[],而这个byte[]对我们显示的形式是不友好的(乱码),

    所以一般都是转为base64的,当然也可以转为其他进制。。


    【代码】

    1. package com.uikoo9.util.encrypt;  
    2.   
    3. import java.math.BigInteger;  
    4.   
    5. import sun.misc.BASE64Decoder;  
    6. import sun.misc.BASE64Encoder;  
    7.   
    8. import com.uikoo9.util.QStringUtil;  
    9.   
    10. /** 
    11.  * 编码工具类 
    12.  * 1.将byte[]转为各种进制的字符串 
    13.  * 2.base 64 encode 
    14.  * 3.base 64 decode 
    15.  * @author uikoo9 
    16.  * @version 0.0.5.20140601 
    17.  */  
    18. public class QEncodeUtil {  
    19.       
    20.     public static void main(String[] args) throws Exception {  
    21.         String s = "我爱你";  
    22.         System.out.println("转换前:" + s);  
    23.           
    24.         String encode = base64Encode(s.getBytes());  
    25.         System.out.println("转换后:" + encode);  
    26.           
    27.         System.out.println("解码后:" + new String(base64Decode(encode)));  
    28.     }  
    29.       
    30.     /** 
    31.      * 将byte[]转为各种进制的字符串 
    32.      * @param bytes byte[] 
    33.      * @param radix 可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制 
    34.      * @return 转换后的字符串 
    35.      */  
    36.     public static String binary(byte[] bytes, int radix){  
    37.         return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数  
    38.     }  
    39.       
    40.     /** 
    41.      * base 64 encode 
    42.      * @param bytes 待编码的byte[] 
    43.      * @return 编码后的base 64 code 
    44.      */  
    45.     public static String base64Encode(byte[] bytes){  
    46.         return new BASE64Encoder().encode(bytes);  
    47.     }  
    48.       
    49.     /** 
    50.      * base 64 decode 
    51.      * @param base64Code 待解码的base 64 code 
    52.      * @return 解码后的byte[] 
    53.      * @throws Exception 
    54.      */  
    55.     public static byte[] base64Decode(String base64Code) throws Exception{  
    56.         return QStringUtil.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);  
    57.     }  
    58.       
    59. }  


    【输出】

      1. 转换前:我爱你  
      2. 转换后:5oiR54ix5L2g  
      3. 解码后:我爱你 
  • 相关阅读:
    colock
    ToggleButton 和 Switch
    radioButon的使用
    kotlin中val和var的区别
    textEdit
    c++ 网络编程基础
    网格布局 GridLayout
    数组、指针和引用
    Hello Word
    Win7-U盘安装出现"We were unable to copy your files. "
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/5824629.html
Copyright © 2011-2022 走看看