20 package net.sf.gridarta.utils;
22 import org.jetbrains.annotations.NotNull;
38 private static final int DELTA = 0x9E3779B9;
43 private final int @NotNull []
k =
new int[4];
49 public Xtea(
final byte @NotNull [] key) {
50 if (key.length != 16) {
51 throw new IllegalArgumentException(
"invalid key length");
65 public void encrypt(
final byte @NotNull [] plaintext,
final byte @NotNull [] ciphertext) {
66 if (plaintext.length != 8) {
67 throw new IllegalArgumentException(
"invalid plaintext length: " + plaintext.length);
69 if (ciphertext.length != 8) {
70 throw new IllegalArgumentException(
"invalid ciphertext length: " + ciphertext.length);
72 int v0 =
getInt(plaintext, 0);
73 int v1 =
getInt(plaintext, 4);
76 v0 += (((v1 << 4) ^ (v1 >>> 5)) + v1) ^ (sum +
k[sum & 3]);
78 v1 += (((v0 << 4) ^ (v0 >>> 5)) + v0) ^ (sum +
k[(sum >>> 11) & 3]);
89 public void decrypt(
final byte @NotNull [] ciphertext,
final byte @NotNull [] plaintext) {
90 if (ciphertext.length != 8) {
91 throw new IllegalArgumentException(
"invalid ciphertext length: " + ciphertext.length);
93 if (plaintext.length != 8) {
94 throw new IllegalArgumentException(
"invalid plaintext length: " + plaintext.length);
96 int v0 =
getInt(ciphertext, 0);
97 int v1 =
getInt(ciphertext, 4);
101 v1 -= (((v0 << 4) ^ (v0 >>> 5)) + v0) ^ (sum +
k[(sum >>> 11) & 3]);
103 v0 -= (((v1 << 4) ^ (v1 >>> 5)) + v1) ^ (sum +
k[sum & 3]);
115 private static int getInt(
final byte @NotNull [] data,
final int offset) {
116 return ((data[offset + 3] & 255) << 24) | ((data[offset + 2] & 255) << 16) | ((data[offset + 1] & 255) << 8) | data[offset] & 255;
125 private static void putInt(
final int value,
final byte @NotNull [] data,
final int offset) {
126 data[offset + 3] = (byte) (value >>> 24);
127 data[offset + 2] = (byte) (value >>> 16);
128 data[offset + 1] = (byte) (value >>> 8);
129 data[offset] = (byte) value;