import java.nio.ByteBuffer;
import java.nio.ByteOrder;public class TeaUtils {private static final int DELTA = 0x9E3779B9;private static final int ROUND = 32;private static final String KEY = "password";/*** 加密字符串,使用 TEA 加密算法*/public static String encrypt(String source) {ByteBuffer sourceBuffer = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);sourceBuffer.put(source.getBytes());sourceBuffer.clear();// 8字节明文int[] plaintext = {sourceBuffer.getInt(), sourceBuffer.getInt()};ByteBuffer keyBuffer = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN);keyBuffer.put(KEY.getBytes());keyBuffer.clear();// 16字节密钥int[] key = {keyBuffer.getInt(), keyBuffer.getInt(), keyBuffer.getInt(), keyBuffer.getInt()};int y = plaintext[0];int z = plaintext[1];int a = key[0];int b = key[1];int c = key[2];int d = key[3];int sum = 0;for (int i = 0; i < ROUND; i++) {sum += DELTA;// 此处必须用 >>> 不能照搬 C++ 用 >>// 参考 https://blog.51cto.com/u_16213450/9390405y += ((z << 4) + a) ^ (z + sum) ^ ((z >>> 5) + b);z += ((y << 4) + c) ^ (y + sum) ^ ((y >>> 5) + d);}ByteBuffer buffer = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);buffer.putInt(y);buffer.putInt(z);buffer.clear();StringBuilder builder = new StringBuilder();while (buffer.hasRemaining()) {builder.append(String.format("%#04x", buffer.get()).replace("0x", ""));}return builder.toString().toUpperCase();}/*** 解密字符串,使用 TEA 加密算法*/public static String decrypt(String source) {int length = source.length();byte[] data = new byte[length / 2];for (int i = 0; i < length; i += 2) {data[i / 2] = (byte) ((Character.digit(source.charAt(i), 16) << 4)+ Character.digit(source.charAt(i + 1), 16));}ByteBuffer sourceBuffer = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);sourceBuffer.put(data);sourceBuffer.clear();// 8字节明文int[] plaintext = {sourceBuffer.getInt(), sourceBuffer.getInt()};ByteBuffer keyBuffer = ByteBuffer.allocate(16).order(ByteOrder.LITTLE_ENDIAN);keyBuffer.put(KEY.getBytes());keyBuffer.clear();// 16字节密钥int[] key = {keyBuffer.getInt(), keyBuffer.getInt(), keyBuffer.getInt(), keyBuffer.getInt()};int y = plaintext[0];int z = plaintext[1];int a = key[0];int b = key[1];int c = key[2];int d = key[3];// sum = DELTA * ROUNDint sum = 0xC6EF3720;for (int i = 0; i < ROUND; i++) {// 此处必须用 >>> 不能照搬 C++ 用 >>// 参考 https://blog.51cto.com/u_16213450/9390405z -= ((y << 4) + c) ^ (y + sum) ^ ((y >>> 5) + d);y -= ((z << 4) + a) ^ (z + sum) ^ ((z >>> 5) + b);sum -= DELTA;}ByteBuffer buffer = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);buffer.putInt(y);buffer.putInt(z);buffer.clear();return new String(buffer.array());}
}
算法参考 java tea加密