📄 base64.java
字号:
/*
*实验名称:Base64加密的理解及实现
*实验目的:了解Base64加密原理
*实验结果:实现了Base64加密
*加密原理:写在附件了
*/
package base64;
import javax.swing.JOptionPane;
public class Base64{
public static final char[] base64_alphabet = { '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', '+', '/', '=' };
/**
* 读取数据3字节?用AND取前6位,放入新的变量中?右移两位,
* 高两位清0?AND取第一个字节的后2位和第二个字节的前4位
* 移位放入新变量中?右移两位,清0……依此类推。
*
* @param bytes
*/
public static void encode(byte[] bytes) {
String str="";
int len = (int) Math.ceil(bytes.length / 3) + 1; //按照3个字符进行分组的分组数
int[] buf = new int[4];
byte[] temp = new byte[3];
if((int) Math.ceil(bytes.length % 3)==0) len--;
//p(len);
for (int i = 0; i < len; i++) {
int base = i * 3;
//需要处理补全字符 ,处理不够3倍的情况
for (int j = 0; j < 3; j++) {
if (i == len - 1 && base + j > bytes.length - 1) {
temp[j] = (byte) 0x00;
} else {
temp[j] = bytes[base + j];
}
}
//将三个字节分解成为4个字节
buf[0] = (((int) temp[0]) >>> 2);//右移两位
buf[1] = ((temp[0] & 0x03) << 4 | (((int) temp[1]) >>> 4));//和0000 0011"与"保留最后两位,并左移四位+左移四位
buf[2] = ((temp[1] & 0x0f) << 2 | (((int) temp[2]) >>> 6));
buf[3] = (temp[2] & 0x3f);//取最后六位
if(i==len-1&&(int) Math.ceil(bytes.length % 3)!=0)
{
for (int j = 0; j <= (int) Math.ceil(bytes.length % 3); j++)
str += base64_alphabet[buf[j]];
for(int j = 0;j<3-(int) Math.ceil(bytes.length % 3);j++)
str+="=";
break;
}
for (int j = 0; j < 4; j++)
str += base64_alphabet[buf[j]];
}
JOptionPane.showMessageDialog(null,"Base64:"+str,"加密结果",JOptionPane.INFORMATION_MESSAGE);
}
public static void main(String[] args) throws Exception{
String s = JOptionPane.showInputDialog("请输入一个字符串:");
Base64.encode(s.getBytes());
//System.out.println(Base64Util.encode(s));
}
private static void p(String s) {
System.out.print(s);
}
private static void p(int s) {
System.out.println(s);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -