java手写base64加密
时间: 2023-06-23 16:10:26 浏览: 104
可以通过以下代码实现Java手写Base64加密:
```
public class Base64Encoder {
private static final char[] BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
public static String encode(String input) {
byte[] bytes = input.getBytes();
StringBuilder sb = new StringBuilder();
int index;
for (int i = 0; i < bytes.length; i += 3) {
index = (bytes[i] & 0xFF) << 16;
if (i + 1 < bytes.length) {
index |= (bytes[i + 1] & 0xFF) << 8;
}
if (i + 2 < bytes.length) {
index |= bytes[i + 2] & 0xFF;
}
sb.append(BASE64_ALPHABET[(index >> 18) & 0x3F]);
sb.append(BASE64_ALPHABET[(index >> 12) & 0x3F]);
sb.append(BASE64_ALPHABET[(index >> 6) & 0x3F]);
sb.append(BASE64_ALPHABET[index & 0x3F]);
}
int padding = 0;
switch (bytes.length % 3) {
case 1:
padding = 2;
break;
case 2:
padding = 1;
break;
default:
break;
}
for (int i = 0; i < padding; i++) {
sb.setCharAt(sb.length() - 1 - i, '=');
}
return sb.toString();
}
}
```
使用示例:
```
String input = "Hello, World!";
String encoded = Base64Encoder.encode(input);
System.out.println(encoded); // SGVsbG8sIFdvcmxkIQ==
```
需要注意的是,这里的实现是没有进行URL安全处理和解码功能的,仅供参考。
阅读全文