1

我想加密 4 个数字,但到目前为止只有 2 个被加密。我曾尝试将该encrypt方法放入循环中,但它不会加密和解密超过 2 个数字。任何人都可以在这方面提供帮助吗?

public class TEA {

    private static int delta = 0x9E3779B9; /* a key schedule constant */

    private static int[] key = { 78945677, 87678687, 234234, 234234 };

    public void encrypt(int[] v, int[] k) {

        int v0 = v[0], v1 = v[1], sum = 0, n = 32;
        int k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; /* cache key */
        while (n-- > 0) {
            sum += delta;
            v0 += ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >>> 5) + k1);
            v1 += ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >>> 5) + k3);
        }
        v[0] = v0;
        v[1] = v1;
        System.out.println(v0 + "," + v1);

    }

    public void decrypt(int[] v, int[] k) {
        int v0 = v[0], v1 = v[1], sum = 0xC6EF3720, n = 32; /* set up */
        int k0 = k[0], k1 = k[1], k2 = k[2], k3 = k[3]; /* cache key */
        while (n-- > 0) {
            v1 -= ((v0 << 4) + k2) ^ (v0 + sum) ^ ((v0 >>> 5) + k3);
            v0 -= ((v1 << 4) + k0) ^ (v1 + sum) ^ ((v1 >>> 5) + k1);
            sum -= delta;
        }
        v[0] = v0;
        v[1] = v1;

        System.out.println(v0 + "," + v1);
    }

    public static void main(String[] args) throws IOException {

        TEA tea = new TEA();
        int n = 0;
        int cc[] = new int[100];

        Scanner input = new Scanner(System.in);

        for (int i = 0; i < 4; i++) {
            System.out.println("Enter 4 number to encrypt: ");
            n = input.nextInt();
            cc[i] = n;

        }

        tea.encrypt(cc, key);
        tea.decrypt(cc, key);

    }

}
4

1 回答 1

2

两者都encrypt()使用decrypt()前两个元素。

因此,您必须在循环中移动调用方法中的数组,或者在加密/解密方法中在连续对上引入循环,例如

for (int idx = 0; idx < v.length; idx *= 2)
{
    int v0 = v[idx], v1 = v[idx + 1], sum = 0, n = 32;
    ...
}

更新 根据维基百科的例子,该方法只需要两个整数(而不是任何长度的数组)。你需要成对传递你的数字,比如

for (int idx = 0; idx < 4; idx =* 2)
{
    int[] tmp = {cc[idx], cc[idx + 1};
    tea.encrypt(tmp, key);
    cc[idx] = tmp[0];
    cc[idx + 1] = tmp[1];
}

结果,对于每一对整数,您将收到另一对整数,但已加密。

于 2013-05-10T07:56:20.317 回答