Java實現(xiàn)的Base64加密算法示例
本文實例講述了Java實現(xiàn)的Base64加密算法。分享給大家供大家參考,具體如下:
一 算法實現(xiàn)
1、JDK
2、Commonc Codec
3、Bouncy Castle
二 代碼
package com.imooc.security.base64;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class ImoocBase64 {
private static String src = "cakin24 security base64";
public static void main(String[] args) {
jdkBase64();
commonsCodesBase64();
bouncyCastleBase64();
}
public static void jdkBase64() {
try {
BASE64Encoder encoder = new BASE64Encoder();
String encode = encoder.encode(src.getBytes());
System.out.println("encode : " + encode);
BASE64Decoder decoder = new BASE64Decoder();
System.out.println("decode : " + new String(decoder.decodeBuffer(encode)));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void commonsCodesBase64() {
byte[] encodeBytes = Base64.encodeBase64(src.getBytes());
System.out.println("encode : " + new String(encodeBytes));
byte[] decodeBytes = Base64.decodeBase64(encodeBytes);
System.out.println("decode : " + new String(decodeBytes));
}
public static void bouncyCastleBase64() {
byte[] encodeBytes = org.bouncycastle.util.encoders.Base64.encode(src.getBytes());
System.out.println("encode : " + new String(encodeBytes));
byte[] decodeBytes = org.bouncycastle.util.encoders.Base64.decode(encodeBytes);
System.out.println("decode : " + new String(decodeBytes));
}
}
三 運行效果
encode : Y2FraW4yNCBzZWN1cml0eSBiYXNlNjQ=
decode : cakin24 security base64
encode : Y2FraW4yNCBzZWN1cml0eSBiYXNlNjQ=
decode : cakin24 security base64
encode : Y2FraW4yNCBzZWN1cml0eSBiYXNlNjQ=
decode : cakin24 security base64
四 應(yīng)用場景
email、秘鑰、證書文件
五 產(chǎn)生原因
郵件的歷史問題
六 其他
基于64個字符的編碼算法,定義于RFC 2045
補充:這里使用到了sun.misc.BASE64Encoder和sun.misc.BASE64Decoder,可通過如下設(shè)置在Eclipse中使用:
右擊項目 --> Properties --> Java Build Path --> 點開JRE System Library --> 點擊Access rules --> Edit --> Add --> Resolution選擇Accessible --> Rule Pattern填上 ** --> OK
中文版Eclipse設(shè)置如下圖所示:

PS:這里再推薦幾款加密解密相關(guān)在線工具供大家參考使用:
線編碼轉(zhuǎn)換工具(utf-8/utf-32/Punycode/Base64):
http://tools.jb51.net/transcoding/decode_encode_tool
BASE64編碼解碼工具:
http://tools.jb51.net/transcoding/base64
圖片轉(zhuǎn)換為Base64編碼在線工具:
http://tools.jb51.net/transcoding/img2base64
在線MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.jb51.net/password/hash_md5_sha
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java數(shù)學運算技巧總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java字符與字符串操作技巧總結(jié)》、《Java操作DOM節(jié)點技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
相關(guān)文章
spring boot 使用@Async實現(xiàn)異步調(diào)用方法
本篇文章主要介紹了spring boot 使用@Async實現(xiàn)異步調(diào)用方法,具有一定的參考價值,有興趣的可以了解一下。2017-04-04

