编写一段java 代码 实现 XXTEA加密解密
时间: 2024-01-18 08:10:12 浏览: 77
以下是 Java XXTEA 加密解密的示例代码:
```java
import java.io.UnsupportedEncodingException;
public class XXTEA {
private static int delta = 0x9E3779B9;
private static int[] toIntArray(byte[] data, boolean includeLength) {
int n = (((data.length & 3) == 0) ? (data.length >>> 2) : ((data.length >>> 2) + 1));
int[] result;
if (includeLength) {
result = new int[n + 1];
result[n] = data.length;
} else {
result = new int[n];
}
int i;
for (i = 0; i < data.length; i++) {
result[i >>> 2] |= (0x000000ff & data[i]) << ((i & 3) << 3);
}
return result;
}
private static byte[] toByteArray(int[] data, boolean includeLength) {
int n = data.length << 2;
if (includeLength) {
int m = data[data.length - 1];
n -= 4;
if ((m < n - 3) || (m > n)) {
return null;
}
n = m;
}
byte[] result = new byte[n];
for (int i = 0; i < n; i++) {
result[i] = (byte) ((data[i >>> 2] >>> ((i & 3) << 3)) & 0xff);
}
return result;
}
private static int mx(int sum, int y, int z, int p, int e, int[] k) {
return ((z >>> 5 ^ y << 2) + (y >>> 3 ^ z << 4)) ^ ((sum ^ y) + (k[(p & 3) ^ e] ^ z));
}
public static byte[] encrypt(byte[] data, byte[] key) {
if (data.length == 0) {
return data;
}
return toByteArray(encrypt(toIntArray(data, true), toIntArray(key, false)), false);
}
public static byte[] decrypt(byte[] data, byte[] key) {
if (data.length == 0) {
return data;
}
return toByteArray(decrypt(toIntArray(data, false), toIntArray(key, false)), true);
}
public static int[] encrypt(int[] v, int[] k) {
int n = v.length - 1;
if (n < 1) {
return v;
}
if (k.length < 4) {
int[] key = new int[4];
System.arraycopy(k, 0, key, 0, k.length);
k = key;
}
int z = v[n], y = v[0], sum = 0, e, p, q = 6 + 52 / (n + 1);
while (q-- > 0) {
sum += delta;
e = sum >>> 2 & 3;
for (p = 0; p < n; p++) {
y = v[p + 1];
z = v[p] += mx(sum, y, z, p, e, k);
}
y = v[0];
z = v[n] += mx(sum, y, z, p, e, k);
}
return v;
}
public static int[] decrypt(int[] v, int[] k) {
int n = v.length - 1;
if (n < 1) {
return v;
}
if (k.length < 4) {
int[] key = new int[4];
System.arraycopy(k, 0, key, 0, k.length);
k = key;
}
int z = v[n], y = v[0], sum, e, p, q = 6 + 52 / (n + 1);
sum = q * delta;
while (sum != 0) {
e = sum >>> 2 & 3;
for (p = n; p > 0; p--) {
z = v[p - 1];
y = v[p] -= mx(sum, y, z, p, e, k);
}
z = v[n];
y = v[0] -= mx(sum, y, z, p, e, k);
sum -= delta;
}
return v;
}
public static void main(String[] args) throws UnsupportedEncodingException {
String data = "Hello, world!";
String key = "1234567890abcdef";
byte[] encrypted = encrypt(data.getBytes("UTF-8"), key.getBytes("UTF-8"));
byte[] decrypted = decrypt(encrypted, key.getBytes("UTF-8"));
System.out.println("Encrypted: " + new String(encrypted, "UTF-8"));
System.out.println("Decrypted: " + new String(decrypted, "UTF-8"));
}
}
```
以上代码中,`encrypt` 方法用于加密数据,`decrypt` 方法用于解密数据。在加密和解密时,需要指定加密密钥。在示例代码中,密钥使用字符串表示,然后转换为字节数组。加密和解密方法的输入和输出都是字节数组。在主函数中,我们对一个字符串进行加密和解密,并打印出加密和解密后的结果。
阅读全文