java 判断base64编码_如何判断一个字符串是否经过base64加密过?

该Java代码实现了一个名为TestBase64的类,用于检查一个字符串是否为Base64编码。通过读取文件中的每一行,计算等号数量,并验证字符是否属于Base64字符集,来确定字符串是否经过Base64加密。
摘要由CSDN通过智能技术生成

import java.io.BufferedReader;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.nio.ByteBuffer;

/**

*检验一个字符串是否是经过Base64处理过的

*

*/

public class TestBase64

{

public static final char[] BASE64_CODE = new char[] { '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 final int MAX_BUFF_SIZE = 4000000;

public static boolean doCheck() throws IOException

{

final File file = new File("src.txt");

final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

ByteBuffer buffer = ByteBuffer.allocate(1024);

String line = null;

String lastLine = null;

while ((line = br.readLine()) != null)

{

lastLine = line;

final byte[] bytes = line.getBytes();

tryAllocate(buffer, bytes.length);

buffer.put(bytes);

}

// 检查最后两个字节

final byte[] lastLineBytes = lastLine.getBytes();

// 等号个数

int equalsNum = 0;

for (int i = lastLineBytes.length - 1; i >= lastLineBytes.length - 2; i--)

{

if (lastLineBytes[i] == '=')

{

equalsNum++;

}

}

final byte[] src = buffer.toString().getBytes();

for (int i = 0; i < src.length - equalsNum; i++)

{

final char c = (char) src[i];

if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '+' || c == '/')

{

continue;

}

return false;

}

if ((src.length - equalsNum) % 4 != 0)

{

return false;

}

return true;

}

public static ByteBuffer tryAllocate(ByteBuffer buffer, int length)

{

if (length > buffer.remaining())

{

buffer.flip();

return ByteBuffer.allocate(roundup(buffer.limit() + length)).put(buffer);

}

return buffer;

}

public static int roundup(int length)

{

if (length > MAX_BUFF_SIZE)

{

throw new IllegalArgumentException("length too large!");

}

int capacity = 16;

while (length < capacity)

{

capacity = capacity << 1;

}

return capacity;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值