zoukankan      html  css  js  c++  java
  • Java Base64加密、解密原理Java代码

    Java Base64加密、解密原理Java代码

    转自:http://blog.csdn.net/songylwq/article/details/7578905

    Base64是什么:

    Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。Base64编码可用于在HTTP环境下传递较长的标识信息。例如,在Java Persistence系统Hibernate中,就采用了Base64来将一个较长的唯一标识符(一般为128-bit的UUID)编码为一个字符串,用作HTTP表单和HTTP GET URL中的参数。在其他应用程序中,也常常需要把二进制数据编码为适合放在URL(包括隐藏表单域)中的形式。此时,采用Base64编码不仅比较简短,同时也具有不可读性,即所编码的数据不会被人用肉眼所直接看到

    简介
      标准的Base64并不适合直接放在URL里传输,因为URL编码器会把标准Base64中的“/”和“+”字符变为形如“%XX”的形式,而这些“%”号在存入数据库时还需要再进行转换,因为ANSI SQL中已将“%”号用作通配符。
      为解决此问题,可采用一种用于URL的改进Base64编码,它不在末尾填充'='号,并将标准Base64中的“+”和“/”分别改成了“*”和“-”,这样就免去了在URL编解码和数据库存储时所要作的转换,避免了编码信息长度在此过程中的增加,并统一了数据库、表单等处对象标识符的格式。
      另有一种用于正则表达式的改进Base64变种,它将“+”和“/”改成了“!”和“-”,因为“+”,“*”以及前面在IRCu中用到的“[”和“]”在正则表达式中都可能具有特殊含义。
      此外还有一些变种,它们将“+/”改为“_-”或“._”(用作编程语言中的标识符名称)或“.-”(用于XML中的Nmtoken)甚至“_:”(用于XML中的Name)。
      Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3*8 = 4*6 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。
    规则
      关于这个编码的规则:
      ①.把3个字符变成4个字符..
      ②每76个字符加一个换行符..
      ③.最后的结束符也要处理..
      这样说会不会太抽象了?不怕,我们来看一个例子:
      转换前 aaaaaabb ccccdddd eeffffff
      转换后 00aaaaaa 00bbcccc 00ddddee 00ffffff
      应该很清楚了吧?上面的三个字节是原文,下面的四个字节是转换后的Base64编码,其前两位均为0。
      转换后,我们用一个码表来得到我们想要的字符串(也就是最终的Base64编码),这个表是这样的:(摘自RFC2045)

    java代码示例:

    [java] view plaincopyprint?
     
    1. public final class Base64 {  
    2.   
    3.     static private final int BASELENGTH = 255;  
    4.     static private final int LOOKUPLENGTH = 64;  
    5.     static private final int TWENTYFOURBITGROUP = 24;  
    6.     static private final int EIGHTBIT = 8;  
    7.     static private final int SIXTEENBIT = 16;  
    8.     static private final int SIXBIT = 6;  
    9.     static private final int FOURBYTE = 4;  
    10.     static private final int SIGN = -128;  
    11.     static private final char PAD = '=';  
    12.     static private final boolean fDebug = false;  
    13.     static final private byte[] base64Alphabet = new byte[BASELENGTH];  
    14.     static final private char[] lookUpBase64Alphabet = new char[LOOKUPLENGTH];  
    15.   
    16.     static {  
    17.   
    18.         for (int i = 0; i < BASELENGTH; i++) {  
    19.             base64Alphabet[i] = -1;  
    20.         }  
    21.         for (int i = 'Z'; i >= 'A'; i--) {  
    22.             base64Alphabet[i] = (byte) (i - 'A');  
    23.         }  
    24.         for (int i = 'z'; i >= 'a'; i--) {  
    25.             base64Alphabet[i] = (byte) (i - 'a' + 26);  
    26.         }  
    27.   
    28.         for (int i = '9'; i >= '0'; i--) {  
    29.             base64Alphabet[i] = (byte) (i - '0' + 52);  
    30.         }  
    31.   
    32.         base64Alphabet['+'] = 62;  
    33.         base64Alphabet['/'] = 63;  
    34.   
    35.         for (int i = 0; i <= 25; i++)  
    36.             lookUpBase64Alphabet[i] = (char) ('A' + i);  
    37.   
    38.         for (int i = 26, j = 0; i <= 51; i++, j++)  
    39.             lookUpBase64Alphabet[i] = (char) ('a' + j);  
    40.   
    41.         for (int i = 52, j = 0; i <= 61; i++, j++)  
    42.             lookUpBase64Alphabet[i] = (char) ('0' + j);  
    43.         lookUpBase64Alphabet[62] = (char) '+';  
    44.         lookUpBase64Alphabet[63] = (char) '/';  
    45.   
    46.     }  
    47.   
    48.     protected static boolean isWhiteSpace(char octect) {  
    49.         return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);  
    50.     }  
    51.   
    52.     protected static boolean isPad(char octect) {  
    53.         return (octect == PAD);  
    54.     }  
    55.   
    56.     protected static boolean isData(char octect) {  
    57.         return (base64Alphabet[octect] != -1);  
    58.     }  
    59.   
    60.     protected static boolean isBase64(char octect) {  
    61.         return (isWhiteSpace(octect) || isPad(octect) || isData(octect));  
    62.     }  
    63.   
    64.     /** 
    65.      * Encodes hex octects into Base64 
    66.      *  
    67.      * @param binaryData 
    68.      *            Array containing binaryData 
    69.      * @return Encoded Base64 array 
    70.      */  
    71.     public static String encode(byte[] binaryData) {  
    72.   
    73.         if (binaryData == null)  
    74.             return null;  
    75.   
    76.         int lengthDataBits = binaryData.length * EIGHTBIT;  
    77.         if (lengthDataBits == 0) {  
    78.             return "";  
    79.         }  
    80.   
    81.         int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;  
    82.         int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;  
    83.         int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1  
    84.                 : numberTriplets;  
    85.         int numberLines = (numberQuartet - 1) / 19 + 1;  
    86.         char encodedData[] = null;  
    87.   
    88.         encodedData = new char[numberQuartet * 4 + numberLines];  
    89.   
    90.         byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;  
    91.   
    92.         int encodedIndex = 0;  
    93.         int dataIndex = 0;  
    94.         int i = 0;  
    95.         if (fDebug) {  
    96.             System.out.println("number of triplets = " + numberTriplets);  
    97.         }  
    98.   
    99.         for (int line = 0; line < numberLines - 1; line++) {  
    100.             for (int quartet = 0; quartet < 19; quartet++) {  
    101.                 b1 = binaryData[dataIndex++];  
    102.                 b2 = binaryData[dataIndex++];  
    103.                 b3 = binaryData[dataIndex++];  
    104.   
    105.                 if (fDebug) {  
    106.                     System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= "  
    107.                             + b3);  
    108.                 }  
    109.   
    110.                 l = (byte) (b2 & 0x0f);  
    111.                 k = (byte) (b1 & 0x03);  
    112.   
    113.                 byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)  
    114.                         : (byte) ((b1) >> 2 ^ 0xc0);  
    115.   
    116.                 byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)  
    117.                         : (byte) ((b2) >> 4 ^ 0xf0);  
    118.                 byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)  
    119.                         : (byte) ((b3) >> 6 ^ 0xfc);  
    120.   
    121.                 if (fDebug) {  
    122.                     System.out.println("val2 = " + val2);  
    123.                     System.out.println("k4 = " + (k << 4));  
    124.                     System.out.println("vak = " + (val2 | (k << 4)));  
    125.                 }  
    126.   
    127.                 encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
    128.                 encodedData[encodedIndex++] = lookUpBase64Alphabet[val2  
    129.                         | (k << 4)];  
    130.                 encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2)  
    131.                         | val3];  
    132.                 encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];  
    133.   
    134.                 i++;  
    135.             }  
    136.             encodedData[encodedIndex++] = 0xa;  
    137.         }  
    138.   
    139.         for (; i < numberTriplets; i++) {  
    140.             b1 = binaryData[dataIndex++];  
    141.             b2 = binaryData[dataIndex++];  
    142.             b3 = binaryData[dataIndex++];  
    143.   
    144.             if (fDebug) {  
    145.                 System.out.println("b1= " + b1 + ", b2= " + b2 + ", b3= " + b3);  
    146.             }  
    147.   
    148.             l = (byte) (b2 & 0x0f);  
    149.             k = (byte) (b1 & 0x03);  
    150.   
    151.             byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)  
    152.                     : (byte) ((b1) >> 2 ^ 0xc0);  
    153.   
    154.             byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)  
    155.                     : (byte) ((b2) >> 4 ^ 0xf0);  
    156.             byte val3 = ((b3 & SIGN) == 0) ? (byte) (b3 >> 6)  
    157.                     : (byte) ((b3) >> 6 ^ 0xfc);  
    158.   
    159.             if (fDebug) {  
    160.                 System.out.println("val2 = " + val2);  
    161.                 System.out.println("k4 = " + (k << 4));  
    162.                 System.out.println("vak = " + (val2 | (k << 4)));  
    163.             }  
    164.   
    165.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
    166.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];  
    167.             encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3];  
    168.             encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f];  
    169.         }  
    170.   
    171.         // form integral number of 6-bit groups  
    172.         if (fewerThan24bits == EIGHTBIT) {  
    173.             b1 = binaryData[dataIndex];  
    174.             k = (byte) (b1 & 0x03);  
    175.             if (fDebug) {  
    176.                 System.out.println("b1=" + b1);  
    177.                 System.out.println("b1<<2 = " + (b1 >> 2));  
    178.             }  
    179.             byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)  
    180.                     : (byte) ((b1) >> 2 ^ 0xc0);  
    181.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
    182.             encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4];  
    183.             encodedData[encodedIndex++] = PAD;  
    184.             encodedData[encodedIndex++] = PAD;  
    185.         } else if (fewerThan24bits == SIXTEENBIT) {  
    186.             b1 = binaryData[dataIndex];  
    187.             b2 = binaryData[dataIndex + 1];  
    188.             l = (byte) (b2 & 0x0f);  
    189.             k = (byte) (b1 & 0x03);  
    190.   
    191.             byte val1 = ((b1 & SIGN) == 0) ? (byte) (b1 >> 2)  
    192.                     : (byte) ((b1) >> 2 ^ 0xc0);  
    193.             byte val2 = ((b2 & SIGN) == 0) ? (byte) (b2 >> 4)  
    194.                     : (byte) ((b2) >> 4 ^ 0xf0);  
    195.   
    196.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val1];  
    197.             encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)];  
    198.             encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2];  
    199.             encodedData[encodedIndex++] = PAD;  
    200.         }  
    201.   
    202.         encodedData[encodedIndex] = 0xa;  
    203.   
    204.         return new String(encodedData);  
    205.     }  
    206.   
    207.     /** 
    208.      * Decodes Base64 data into octects 
    209.      *  
    210.      * @param binaryData 
    211.      *            Byte array containing Base64 data 
    212.      * @return Array containind decoded data. 
    213.      */  
    214.     public static byte[] decode(String encoded) {  
    215.   
    216.         if (encoded == null)  
    217.             return null;  
    218.   
    219.         char[] base64Data = encoded.toCharArray();  
    220.         // remove white spaces  
    221.         int len = removeWhiteSpace(base64Data);  
    222.   
    223.         if (len % FOURBYTE != 0) {  
    224.             return null;// should be divisible by four  
    225.         }  
    226.   
    227.         int numberQuadruple = (len / FOURBYTE);  
    228.   
    229.         if (numberQuadruple == 0)  
    230.             return new byte[0];  
    231.   
    232.         byte decodedData[] = null;  
    233.         byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;  
    234.         char d1 = 0, d2 = 0, d3 = 0, d4 = 0;  
    235.   
    236.         int i = 0;  
    237.         int encodedIndex = 0;  
    238.         int dataIndex = 0;  
    239.         decodedData = new byte[(numberQuadruple) * 3];  
    240.   
    241.         for (; i < numberQuadruple - 1; i++) {  
    242.   
    243.             if (!isData((d1 = base64Data[dataIndex++]))  
    244.                     || !isData((d2 = base64Data[dataIndex++]))  
    245.                     || !isData((d3 = base64Data[dataIndex++]))  
    246.                     || !isData((d4 = base64Data[dataIndex++])))  
    247.                 return null;// if found "no data" just return null  
    248.   
    249.             b1 = base64Alphabet[d1];  
    250.             b2 = base64Alphabet[d2];  
    251.             b3 = base64Alphabet[d3];  
    252.             b4 = base64Alphabet[d4];  
    253.   
    254.             decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
    255.             decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
    256.             decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);  
    257.         }  
    258.   
    259.         if (!isData((d1 = base64Data[dataIndex++]))  
    260.                 || !isData((d2 = base64Data[dataIndex++]))) {  
    261.             return null;// if found "no data" just return null  
    262.         }  
    263.   
    264.         b1 = base64Alphabet[d1];  
    265.         b2 = base64Alphabet[d2];  
    266.   
    267.         d3 = base64Data[dataIndex++];  
    268.         d4 = base64Data[dataIndex++];  
    269.         if (!isData((d3)) || !isData((d4))) {// Check if they are PAD characters  
    270.             if (isPad(d3) && isPad(d4)) { // Two PAD e.g. 3c[Pad][Pad]  
    271.                 if ((b2 & 0xf) != 0)// last 4 bits should be zero  
    272.                     return null;  
    273.                 byte[] tmp = new byte[i * 3 + 1];  
    274.                 System.arraycopy(decodedData, 0, tmp, 0, i * 3);  
    275.                 tmp[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);  
    276.                 return tmp;  
    277.             } else if (!isPad(d3) && isPad(d4)) { // One PAD e.g. 3cQ[Pad]  
    278.                 b3 = base64Alphabet[d3];  
    279.                 if ((b3 & 0x3) != 0)// last 2 bits should be zero  
    280.                     return null;  
    281.                 byte[] tmp = new byte[i * 3 + 2];  
    282.                 System.arraycopy(decodedData, 0, tmp, 0, i * 3);  
    283.                 tmp[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
    284.                 tmp[encodedIndex] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
    285.                 return tmp;  
    286.             } else {  
    287.                 return null;// an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX"  
    288.                             // where X is non data  
    289.             }  
    290.         } else { // No PAD e.g 3cQl  
    291.             b3 = base64Alphabet[d3];  
    292.             b4 = base64Alphabet[d4];  
    293.             decodedData[encodedIndex++] = (byte) (b1 << 2 | b2 >> 4);  
    294.             decodedData[encodedIndex++] = (byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));  
    295.             decodedData[encodedIndex++] = (byte) (b3 << 6 | b4);  
    296.   
    297.         }  
    298.   
    299.         return decodedData;  
    300.     }  
    301.   
    302.     /** 
    303.      * remove WhiteSpace from MIME containing encoded Base64 data. 
    304.      *  
    305.      * @param data 
    306.      *            the byte array of base64 data (with WS) 
    307.      * @return the new length 
    308.      */  
    309.     protected static int removeWhiteSpace(char[] data) {  
    310.         if (data == null)  
    311.             return 0;  
    312.   
    313.         // count characters that's not whitespace  
    314.         int newSize = 0;  
    315.         int len = data.length;  
    316.         for (int i = 0; i < len; i++) {  
    317.             if (!isWhiteSpace(data[i]))  
    318.                 data[newSize++] = data[i];  
    319.         }  
    320.         return newSize;  
    321.     }  
    322.     public static void main(String[] args) {  
    323.         System.out.println(encode("中华人民共和国".getBytes()));  
    324.     }  
    325. }  
    逃避不一定躲得过,面对不一定最难过
  • 相关阅读:
    获取汉字信息(结合正则就可以得到想要的详细啦)
    压缩图片(递归结合pillow)通过改变图片尺寸实现;tinify 需要付费
    实现两个视频同时播放,利用到opencv模块 (线程进程开启)
    切换pip下载源头
    516. 最长回文子序列
    87.扰乱字符串
    Maximum Likelihood ML
    数组右边第一个比当前元素大的数
    4. 寻找两个正序数组的中位数
    min-hash
  • 原文地址:https://www.cnblogs.com/yangzhenlong/p/4797776.html
Copyright © 2011-2022 走看看