Base64位java加密算法

package mains;

import java.util.ArrayList;
import java.util.List;

import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64DecoderStream;
import com.sun.xml.internal.messaging.saaj.packaging.mime.util.BASE64EncoderStream;

import sun.misc.BASE64Encoder;

/***
* Base64位加密算法.
* @author Administrator xlaohe1
*
*/
public class Base64Test {
/*
Base64 使用US-ASCII子集的64个字符,即大小写的26个英文字母,0-9,+,/。
编码总是基于3个字符,每个字符用8位二进制表示,因此一共24位,再分为4四组,每组6位,表示一个Base64的值。
Base64值为0就是A,为27的就是b。这样,每3个字符产生4位的Base64字符。如果被加密的字符串每3个一组,还剩1或2个字符,
使用特殊字符"="补齐Base64的4字。

*/

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


public static void main(String[] args) {
String src = "Man is distinguished, not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure.";
StringBuffer sb = new StringBuffer();
byte[] buf = src.getBytes();
for(byte b : buf) {
sb.append(to8len(Integer.toBinaryString(b&0xff), 8));
}
String bin = toNstr(sb.toString(), 6, "0");
StringBuffer newBuf = new StringBuffer(bin.length() / 6);
for(int i = 0, len = bin.length(); i < len; i += 6) {
newBuf.append(BASE64ARR[Integer.parseInt(bin.substring(i, i + 6), 2)]);
}
//System.out.println(toNstr(newBuf.toString(), 3, "="));
System.out.println(newBuf.toString());
}
private static String to8len(String src, int n) {
if(null == src || "".equals(src)) return "";
if(src.length() >= n) return src;
return to8len("0" + src, n);
}
private static String toNstr(String src, int mod, String c) {
if(src.length() % mod == 0) return src;
StringBuffer sb = new StringBuffer();
sb.append(src);
int i = 0, len = mod - src.length() % mod;
while(i ++ < len) {
sb.append(c);
}
return sb.toString();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值