没有使用Java内部存在现成的base64加密的实现方法的情况下钻研了一下琢磨着写了一下练一下手。代码:
public static void main(String[] args) {
// TODO Auto-generated method stub
String before="A";
String erjinzhiString=new String();
String result="";
//转换字符串并进行一次补位,不足8位
for(int i=0;i<before.length();i++){
char c=before.charAt(i);
String erjinzhic=buweiFirst(erjinzhi(c));
erjinzhiString+=erjinzhic;
}
System.out.println("字符转二进制后不足8位进行补0"+erjinzhiString);
System.out.println(erjinzhiString.length());
//二次补位,队尾不足6位的补0
/*队尾不足24位的字符串的长度*/
int endLength=erjinzhiString.length()%24;
//不足24位的字符串
System.out.println("长度"+endLength);
System.out.println(endLength%6);
if(endLength!=0){
if(endLength%6!=0){
for(int i=0;i<6-(endLength%6);i++){
erjinzhiString+="0";
}
}
}
System.out.println("不足6位进行补0"+erjinzhiString);
System.out.println(erjinzhiString.length());
//补完6位后依然不足24位的进行补x
for (int i=erjinzhiString.length()/24;i<erjinzhiString.length()%24;i++) {
erjinzhiString+="x";
}
System.out.println(erjinzhiString);
System.out.println(erjinzhiString.length());
int row=erjinzhiString.length()/24;
String [][]chaifen=new String[row][4];
String erveyBase="";
for(int i=0;i<row;i++){
for(int j=0;j<4;j++){
String everyGroup="";
for(int k=0;k<6;k++){
int xiabiao=i*24+j*6+k;
if(erjinzhiString.charAt(xiabiao)!='x'){
everyGroup+=erjinzhiString.charAt(xiabiao);
}else{
break;
}
}
if("".equals(everyGroup)){
erveyBase+="=";
}else{
//字符串二进制转10进制
int shi=erzhuanshi(everyGroup);
//进行base64转码
char a=basezhuanma(shi);
System.out.println("转码"+a);
erveyBase+=a;
}
}
}
System.out.println(erveyBase);
}
//字符转二进制
public static String erjinzhi(char c){
int b=(int)c;
String string=Integer.toBinaryString(b);
return string;
}
//二进制数不足8位进行补位
public static String buweiFirst(String s){
int a=Integer.parseInt(s);
s = String.format("%08d", a);
System.out.println(s);
return s;
}
//对输入字符不足24位的进行补位
public static String buweiThird(String s){
if(s.length()%24!=0){
int n=((int)s.length()/24)+1;
for(int i=s.length();i<n*24;i++){
s+='0';
}
}
return s;
}
//字符串二进制转十进制
public static int erzhuanshi(String s){
int result=0;
for(int i=0;i<s.length();i++){
int cifang=(int)Math.pow(2,i);
char c=s.charAt(s.length()-1-i);
int everyBitNum=Integer.parseInt(c+"");
int bitResult=cifang*everyBitNum;
result=result+bitResult;
}
return result;
}
public static char basezhuanma(int a){
if(a<=25){
a+=65;
}else if(a<=51){
a+=71;
}else if(a<=61){
a-=13;
}else if(a==62){
a-=19;
}else if(a==63){
a-=16;
}
char c=(char)a;
return c;
}