代码如下,不多说。先这样,如果合成四个字节加密一次是否会更快。
public class EncryptUncrypt {
public static byte[] encryptAndUncrypt(byte[] valueBuf, byte[] secret) {
// 对value加密,secret密文字符
// 将需要加密的内容转换为字节数组
final int valLen = valueBuf.length;
for (int i = 0; i < valLen; ) {
for (int j = 0; j < secret.length; j++) {
int index = i * valLen + j;
if (index < valLen) {
valueBuf[index] = (byte) (valueBuf[index] ^ secret[j]); // 通过异或运算进行加密
}
}
i++;
}
return valueBuf;
// 返回加密后的字符串
}
public static void main(String[] args) {
String value = "学习Java";
// 需要加密的内容
byte[] secret = new byte[]{32,93,9};
// 密文字符
System.out.println("原字符串为:" + value);
// 加密
byte[] encryptResult = EncryptUncrypt.encryptAndUncrypt(value.getBytes(), secret);
System.out.println("加密后的值:" + new String(encryptResult, 0, encryptResult.length));
// 解密
byte[] uncryptResult = EncryptUncrypt.encryptAndUncrypt(encryptResult, secret);
System.out.println("解密后的值:" + new String(uncryptResult, 0, uncryptResult.length));
}
}