HTTP与Base64编码

Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,也是一种比较可靠的加密方法,能够对电子邮件的明文进行转换,至少要得出一个无法被别人一眼就看出内容来的东西,而且编码/解码的速度还要足够快。它的特点是:1、速度非常快。2、能够将字符串A转换成字符串B,而且如果你光看字符串B,是绝对猜不出字符串A的内容来的。

Base64由来:Base64编码方式可以让中文字或者图片也能在网路上顺利传输。在 BASE64 编码后的字串只包含英文字母大小写、阿拉伯数字、加号与反斜线,共 64 个基本字元,不包含其它特殊的字元,因而才取名 BASE64。编码后的字串比原来的字串长度再加 1/3 左右。

Base64编码算法:

Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3*8 = 4*6 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3。所以,Base64的编码最多会在编码结尾有两个“=”

 三个8位字节->4个6位补全字节->对应码表找到对应的asc字符

                            Table 1: The Base64 Alphabet

      Value Encoding  Value Encoding  Value Encoding  Value Encoding
           0 A            17 R            34 i            51 z
           1 B            18 S            35 j            52 0
           2 C            19 T            36 k            53 1
           3 D            20 U            37 l            54 2
           4 E            21 V            38 m            55 3
           5 F            22 W            39 n            56 4
           6 G            23 X            40 o            57 5
           7 H            24 Y            41 p            58 6
           8 I            25 Z            42 q            59 7
           9 J            26 a            43 r            60 8
          10 K            27 b            44 s            61 9
          11 L            28 c            45 t            62 +
          12 M            29 d            46 u            63 /
          13 N            30 e            47 v
          14 O            31 f            48 w         (pad) =
          15 P            32 g            49 x
          16 Q            33 h            50 y

 顺便贴一个老外用Java实现的Base64编码工具类

/**
   * <p>
   * Encodes and decodes to and from Base64 notation.
   * </p>
   * <p>
   * I am placing this code in the Public Domain. Do with it as you will. This
   * software comes with no guarantees or warranties but with plenty of
   * well-wishing instead! Please visit <a
   * href="http://iharder.net/base64">http://iharder.net/base64</a> periodically
   * to check for updates or to contribute improvements.
   * </p>
   *
   * @author Robert Harder
   * @author rob@iharder.net
   * @version 2.3.7
   */
  public static class Base64 {

    /** The equals sign (=) as a byte. */
    private final static byte EQUALS_SIGN = (byte) '=';

    /** Preferred encoding. */
    private final static String PREFERRED_ENCODING = "US-ASCII";

    /** The 64 valid Base64 values. */
    private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B',
        (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H',
        (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
        (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T',
        (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
        (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
        (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l',
        (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r',
        (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x',
        (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
        (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
        (byte) '+', (byte) '/' };

    /** Defeats instantiation. */
    private Base64() {
    }

    /**
     * <p>
     * Encodes up to three bytes of the array <var>source</var> and writes the
     * resulting four Base64 bytes to <var>destination</var>. The source and
     * destination arrays can be manipulated anywhere along their length by
     * specifying <var>srcOffset</var> and <var>destOffset</var>. This method
     * does not check to make sure your arrays are large enough to accomodate
     * <var>srcOffset</var> + 3 for the <var>source</var> array or
     * <var>destOffset</var> + 4 for the <var>destination</var> array. The
     * actual number of significant bytes in your array is given by
     * <var>numSigBytes</var>.
     * </p>
     * <p>
     * This is the lowest level of the encoding methods with all possible
     * parameters.
     * </p>
     *
     * @param source
     *          the array to convert
     * @param srcOffset
     *          the index where conversion begins
     * @param numSigBytes
     *          the number of significant bytes in your array
     * @param destination
     *          the array to hold the conversion
     * @param destOffset
     *          the index where output will be put
     * @return the <var>destination</var> array
     * @since 1.3
     */
    private static byte[] encode3to4(byte[] source, int srcOffset,
        int numSigBytes, byte[] destination, int destOffset) {

      byte[] ALPHABET = _STANDARD_ALPHABET;

      int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
          | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
          | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);

      switch (numSigBytes) {
      case 3:
        destination[destOffset] = ALPHABET[(inBuff >>> 18)];
        destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
        destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
        destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
        return destination;

      case 2:
        destination[destOffset] = ALPHABET[(inBuff >>> 18)];
        destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
        destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
        destination[destOffset + 3] = EQUALS_SIGN;
        return destination;

      case 1:
        destination[destOffset] = ALPHABET[(inBuff >>> 18)];
        destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
        destination[destOffset + 2] = EQUALS_SIGN;
        destination[destOffset + 3] = EQUALS_SIGN;
        return destination;

      default:
        return destination;
      }
    }

    /**
     * Encode string as a byte array in Base64 annotation.
     *
     * @param string
     * @return The Base64-encoded data as a string
     */
    public static String encode(String string) {
      byte[] bytes;
      try {
        bytes = string.getBytes(PREFERRED_ENCODING);
      } catch (UnsupportedEncodingException e) {
        bytes = string.getBytes();
      }
      return encodeBytes(bytes);
    }

    /**
     * Encodes a byte array into Base64 notation.
     *
     * @param source
     *          The data to convert
     * @return The Base64-encoded data as a String
     * @throws NullPointerException
     *           if source array is null
     * @throws IllegalArgumentException
     *           if source array, offset, or length are invalid
     * @since 2.0
     */
    public static String encodeBytes(byte[] source) {
      return encodeBytes(source, 0, source.length);
    }

    /**
     * Encodes a byte array into Base64 notation.
     *
     * @param source
     *          The data to convert
     * @param off
     *          Offset in array where conversion should begin
     * @param len
     *          Length of data to convert
     * @return The Base64-encoded data as a String
     * @throws NullPointerException
     *           if source array is null
     * @throws IllegalArgumentException
     *           if source array, offset, or length are invalid
     * @since 2.0
     */
    public static String encodeBytes(byte[] source, int off, int len) {
      byte[] encoded = encodeBytesToBytes(source, off, len);
      try {
        return new String(encoded, PREFERRED_ENCODING);
      } catch (UnsupportedEncodingException uue) {
        return new String(encoded);
      }
    }

    /**
     * Similar to {@link #encodeBytes(byte[], int, int)} but returns a byte
     * array instead of instantiating a String. This is more efficient if you're
     * working with I/O streams and have large data sets to encode.
     *
     *
     * @param source
     *          The data to convert
     * @param off
     *          Offset in array where conversion should begin
     * @param len
     *          Length of data to convert
     * @return The Base64-encoded data as a String if there is an error
     * @throws NullPointerException
     *           if source array is null
     * @throws IllegalArgumentException
     *           if source array, offset, or length are invalid
     * @since 2.3.1
     */
    public static byte[] encodeBytesToBytes(byte[] source, int off, int len) {

      if (source == null)
        throw new NullPointerException("Cannot serialize a null array.");

      if (off < 0)
        throw new IllegalArgumentException("Cannot have negative offset: "
            + off);

      if (len < 0)
        throw new IllegalArgumentException("Cannot have length offset: " + len);

      if (off + len > source.length)
        throw new IllegalArgumentException(
            String
                .format(
                    "Cannot have offset of %d and length of %d with array of length %d",
                    off, len, source.length));

      // Bytes needed for actual encoding
      int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0);

      byte[] outBuff = new byte[encLen];

      int d = 0;
      int e = 0;
      int len2 = len - 2;
      for (; d < len2; d += 3, e += 4)
        encode3to4(source, d + off, 3, outBuff, e);

      if (d < len) {
        encode3to4(source, d + off, len - d, outBuff, e);
        e += 4;
      }

      if (e <= outBuff.length - 1) {
        byte[] finalOut = new byte[e];
        System.arraycopy(outBuff, 0, finalOut, 0, e);
        return finalOut;
      } else
        return outBuff;
    }
  }

转载于:https://my.oschina.net/kingguary/blog/127192

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值