base64_encode和base64_decode的JAVA实现

作者:暗之幻影 时间:2023-08-25 07:56:49 

Base64是网络上最常见的用于传输8Bit字节代码的编码方式之一,大家可以查看RFC2045~RFC2049,上面有MIME的详细规范。 Base64要求把每三个8Bit的字节转换为四个6Bit的字节(3*8 = 4*6 = 24),然后把6Bit再添两位高位0,组成四个8Bit的字节,也就是说,转换后的字符串理论上将要比原来的长1/3

php 的函数:base64_encode() 和 base64_decode()

base64的编,解码原理

Base64 编码其实是将3个8位字节转换为4个6位字节,( 3*8 = 4*6 = 24 ) 这4个六位字节 其实仍然是8位,只不过高两位被设置为0. 当一个字节只有6位有效时,它的取值空间为0 到 2的6次方减1 即63,也就是说被转换的Base64编码的每一个编码的取值空间为(0~63) 。

事实上,0~63之间的ASCII码有许多不可见字符,所以应该再做一个映射,映射表为

'A' ~ 'Z' ? ASCII(0 ~ 25)

'a' ~ 'z' ? ASCII(26 ~ 51)

'0' ~ '9' ? ASCII(52 ~ 61)

' ' ? ASCII(62)

'/' ? ASCII(63)

这样就可以将3个8位字节,转换为4个可见字符。

具体的字节拆分方法为:(图(画得不好,领会精神 :-))

aaaaaabb ccccdddd eeffffff    //abcdef其实就是1或0,为了看的清楚就用abcdef代替

~~~~~~~~ ~~~~~~~~ ~~~~~~~~

字节 1 字节 2 字节 3

||
\/

00aaaaaa 00bbcccc 00ddddee 00ffffff

注:上面的三个字节位原文,下面四个字节为Base64编码,其前两位均为0。

这样拆分的时候,原文的字节数量应该是3的倍数,当这个条件不能满足时,用全零字节

补足,转化时Base64编码用=号代替,这就是为什么有些Base64编码以一个或两个等号结

束的原因,但等号最多有两个,因为:如果F(origin)代表原文的字节数,F(remain)代

表余数,则

F(remain) = F(origin) MOD 3 成立。

所以F(remain)的可能取值为0,1,2.

如果设 n = [F(origin) – F(remain)] / 3

当F(remain) = 0 时,恰好转换为4*n个字节的Base64编码。

当F(remain) = 1 时,由于一个原文字节可以拆分为属于两个Base64编码的字节,为了

让Base64编码是4的倍数,所以应该为补2个等号。

当F(remain) = 2 时,由于两个原文字节可以拆分为属于3个Base64编码的字节,同理,

应该补上一个等号。

base64 编码后的字符串末尾会有0到2个等号,这些等号在解码是并不必要,所以可以删除。
在网络GET 和 POST参数列表的时候,‘+'不能正常传输,可以把它替换成‘|'
这样经过base64编码后的字符串就只有‘|'和‘/‘,所以经过这样处理base64编码的字符串可以作为参数列表的以个参数值来传输

========================================================================
以下是老外写的一个实现:
package   com.meterware.httpunit;


/********************************************************************************************************************
* $Id: Base64.java,v 1.4 2002/12/24 15:17:17 russgold Exp $
*
* Copyright (c) 2000-2002 by Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software "), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS ", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*******************************************************************************************************************/

/**
* A utility class to convert to and from base 64 encoding.
*
* @author <a href= "mailto:russgold@httpunit.org "> Russell Gold </a>
**/

public class Base64 {
final static String encodingChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ "; /**
 * Returns the base 64 encoded equivalent of a supplied string.
 * @param source the string to encode
 */
public static String encode( String source ) {
 char[] sourceBytes = getPaddedBytes( source );
 int numGroups = (sourceBytes.length + 2) / 3;
 char[] targetBytes = new char[4];
 char[] target = new char[ 4 * numGroups ];

for (int group = 0; group < numGroups; group++) {
  convert3To4( sourceBytes, group*3, targetBytes );
  for (int i = 0; i < targetBytes.length; i++) {
   target[ i + 4*group ] = encodingChar.charAt( targetBytes[i] );
  }
 }

int numPadBytes = sourceBytes.length - source.length();

for (int i = target.length-numPadBytes; i < target.length; i++) target[i] = '= ';
 return new String( target );
}

private static char[] getPaddedBytes( String source ) {
 char[] converted = source.toCharArray();
 int requiredLength = 3 * ((converted.length+2) /3);
 char[] result = new char[ requiredLength ];
 System.arraycopy( converted, 0, result, 0, converted.length );
 return result;
}

private static void convert3To4( char[] source, int sourceIndex, char[] target ) {
 target[0] = (char) ( source[ sourceIndex ] > > > 2);
 target[1] = (char) (((source[ sourceIndex ] & 0x03) < < 4) | (source[ sourceIndex+1 ] > > > 4));
 target[2] = (char) (((source[ sourceIndex+1 ] & 0x0f) < < 2) | (source[ sourceIndex+2 ] > > > 6));
 target[3] = (char) ( source[ sourceIndex+2 ] & 0x3f);
}

/**
 * Returns the plaintext equivalent of a base 64-encoded string.
 * @param source a base 64 string (which must have a multiple of 4 characters)
 */
public static String decode( String source ) {
 if (source.length()%4 != 0) throw new RuntimeException( "valid Base64 codes have a multiple of 4 characters " );
 int numGroups = source.length() / 4;
 int numExtraBytes = source.endsWith( "== " ) ? 2 : (source.endsWith( "= " ) ? 1 : 0);
 byte[] targetBytes = new byte[ 3*numGroups ];
 byte[] sourceBytes = new byte[4];
 for (int group = 0; group < numGroups; group++) {
  for (int i = 0; i < sourceBytes.length; i++) {
   sourceBytes[i] = (byte) Math.max( 0, encodingChar.indexOf( source.charAt( 4*group+i ) ) );
  }
  convert4To3( sourceBytes, targetBytes, group*3 );
 }
 return new String( targetBytes, 0, targetBytes.length - numExtraBytes );
}

private static void convert4To3( byte[] source, byte[] target, int targetIndex ) {
 target[ targetIndex ] = (byte) (( source[0] < < 2) | (source[1] > > > 4));
 target[ targetIndex+1 ] = (byte) (((source[1] & 0x0f) < < 4) | (source[2] > > > 2));
 target[ targetIndex+2 ] = (byte) (((source[2] & 0x03) < < 6) | (source[3]));
}

}
标签:base64,encode,base64,decode
0
投稿

猜你喜欢

  • Java事件处理步骤讲解

    2023-10-14 11:49:57
  • java 避免出现NullPointerException(空指针)的方法总结

    2022-08-31 04:15:51
  • Java实现InputStream的任意拷贝方式

    2022-04-08 10:11:32
  • springboot+mybatis-plus 两种方式打印sql语句的方法

    2022-12-29 13:41:11
  • Android jni调试打印char阵列的实例详解

    2022-06-18 14:55:40
  • mybatis如何实现saveOrUpdate

    2021-07-18 10:33:11
  • C#使用iTextSharp添加PDF水印

    2021-10-09 08:59:27
  • 通过IDEA快速定位和排除依赖冲突问题

    2021-06-07 02:01:16
  • java final 和instanceof 关键字的区别

    2021-11-03 13:52:43
  • JavaBean和SpringBean的区别及创建SpringBean方式

    2022-05-23 03:32:14
  • Java面向对象基础,类,变量,方法

    2023-04-08 13:21:49
  • c# 引用类型与值类型的区别详解

    2021-05-27 00:34:33
  • 详解Android应用中ListView列表选项栏的编写方法

    2023-09-03 15:01:25
  • Android控件系列之EditText使用方法

    2021-06-19 19:09:20
  • VS.net VSS时,编译报错:未能向文件“.csproj.FileListAbsolute.txt”写入命令行 对路径 的访问被拒绝。

    2021-10-01 18:29:12
  • java面试常问的Runnable和Callable的区别

    2023-11-23 09:23:28
  • Android实现App中导航Tab栏悬浮的功能

    2021-11-22 23:11:31
  • Android 6.0指纹识别App开发案例

    2021-06-05 10:30:07
  • Idea中SpringBoot多模块项目的建立实现

    2023-11-08 07:52:34
  • 详解在Spring Boot中使用JPA

    2022-08-03 15:44:13
  • asp之家 软件编程 m.aspxhome.com