Java加密系列之(二)Base64加密

sun.misc.BASE64Encoder/BASE64Decoder类不属于JDK标准库范畴,但在JDK中包含了该类,可以直接使用,但这个没有java doc,属于jdk里不推荐使用的工具类。强烈建议不要用sun.misc,是不安全的。

bouncycastle的jar包下载地址:http://www.bouncycastle.org/latest_releases.html


package com.tvm.mrz.security.base64;

import java.io.IOException;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64Test {

	private static String src = "Mr.Z Security Base64";

	public static void jdkBase64() {
		BASE64Encoder encoder = new BASE64Encoder();
		String encode = encoder.encode( src.getBytes() );
		System.out.println( "encode:" + encode );

		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] decode = decoder.decodeBuffer( encode );
			System.out.println( "decode:" + new String( decode ) );
		} catch( IOException e ) {
			e.printStackTrace();
		}
	}

	public static void commonsCodecBase64() {
		// String encode = Base64.encodeBase64String( src.getBytes() );
		byte[] encode = Base64.encodeBase64( src.getBytes() );
		System.out.println( "encode:" + new String( encode ) );

		byte[] decode = Base64.decodeBase64( encode );
		System.out.println( "decode:" + new String( decode ) );
	}

	public static void bouncyCastleBase64() {
		byte[] encode = org.bouncycastle.util.encoders.Base64.encode( src.getBytes() );
		System.out.println( "encode:" + new String( encode ) );

		byte[] decode = org.bouncycastle.util.encoders.Base64.decode( encode );
		System.out.println( "decode:" + new String( decode ) );
	}

	public static void main( String[] args ) {
		jdkBase64();
		commonsCodecBase64();
		bouncyCastleBase64();
	}
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。