java给我写一个base64算法工具类,不能调用其他类
时间: 2024-03-01 22:55:51 浏览: 51
java Base64工具类
好的,下面是 Java 实现的 Base64 工具类,不依赖其他类库:
```java
public class Base64Util {
private static final char[] BASE64_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
private static final int[] BASE64_INVERT_TABLE = new int[256];
static {
for (int i = 0; i < BASE64_INVERT_TABLE.length; i++) {
BASE64_INVERT_TABLE[i] = -1; // 初始化为 -1
}
for (int i = 0; i < BASE64_TABLE.length; i++) {
BASE64_INVERT_TABLE[BASE64_TABLE[i]] = i;
}
}
public static String encode(String s) {
byte[] data = s.getBytes(StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
int len = data.length;
for (int i = 0; i < len; i += 3) {
int b1 = data[i] & 0xFF;
int b2 = i + 1 < len ? data[i + 1] & 0xFF : 0;
int b3 = i + 2 < len ? data[i + 2] & 0xFF : 0;
int c1 = b1 >>> 2;
int c2 = ((b1 & 0x03) << 4) | (b2 >>> 4);
int c3 = ((b2 & 0x0F) << 2) | (b3 >>> 6);
int c4 = b3 & 0x3F;
sb.append(BASE64_TABLE[c1]).append(BASE64_TABLE[c2]);
sb.append(i + 1 < len ? BASE64_TABLE[c3] : "=");
sb.append(i + 2 < len ? BASE64_TABLE[c4] : "=");
}
return sb.toString();
}
public static String decode(String s) {
byte[] data = s.getBytes(StandardCharsets.UTF_8);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = data.length;
for (int i = 0; i < len; i += 4) {
int c1 = BASE64_INVERT_TABLE[data[i]];
int c2 = i + 1 < len ? BASE64_INVERT_TABLE[data[i + 1]] : -1;
int c3 = i + 2 < len ? BASE64_INVERT_TABLE[data[i + 2]] : -1;
int c4 = i + 3 < len ? BASE64_INVERT_TABLE[data[i + 3]] : -1;
if (c1 == -1 || c2 == -1 || c3 == -1 || c4 == -1) {
throw new IllegalArgumentException("Invalid Base64 string");
}
int b1 = (c1 << 2) | (c2 >>> 4);
int b2 = ((c2 & 0x0F) << 4) | (c3 >>> 2);
int b3 = ((c3 & 0x03) << 6) | c4;
bos.write(b1);
if (c3 != -1) {
bos.write(b2);
}
if (c4 != -1) {
bos.write(b3);
}
}
return new String(bos.toByteArray(), StandardCharsets.UTF_8);
}
}
```
使用示例:
```java
String text = "hello, world!";
String encoded = Base64Util.encode(text);
System.out.println(encoded); // aGVsbG8sIHdvcmxkIQ==
String decoded = Base64Util.decode(encoded);
System.out.println(decoded); // hello, world!
```
注意:这只是一个简单的示例,实际场景中还需要考虑编码格式、异常处理等问题。
阅读全文