java - 在 Java 中使用 BigIntegers 进行 BitShifting

标签 java encryption key biginteger des

我正在使用 BigIntegers 在 Java 中实现 DES 加密。

我通过执行 BigInteger.leftShift(int n) 方法使用 Java BigIntegers 左移二进制键。 N的键(Kn)取决于Kn-1的移位结果。我遇到的问题是我在生成每个 key 后打印出结果,并且移位不是预期的输出。 key 分为 2 个 Cn 和 Dn(分别为左和右)。

我专门尝试这样做: “要进行左移,将每个位向左移动一个位置,除了第一个位,它循环到 block 的末尾。”

根据类次,它似乎在最后加上 O。不确定如何解决这个问题。

结果:

c0: 11110101010100110011000011110

d0: 11110001111001100110101010100

c1: 111101010101001100110000111100

d1: 111100011110011001101010101000

c2: 11110101010100110011000011110000

d2: 11110001111001100110101010100000

c3: 1111010101010011001100001111000000

d3: 1111000111100110011010101010000000

c4: 111101010101001100110000111100000000

d4: 111100011110011001101010101000000000

c5: 11110101010100110011000011110000000000

d5: 11110001111001100110101010100000000000

c6: 1111010101010011001100001111000000000000

d6: 1111000111100110011010101010000000000000

c7: 111101010101001100110000111100000000000000

d7: 111100011110011001101010101000000000000000

c8: 1111010101010011001100001111000000000000000

d8: 1111000111100110011010101010000000000000000

c9: 111101010101001100110000111100000000000000000

d9: 111100011110011001101010101000000000000000000

c10: 11110101010100110011000011110000000000000000000

d10: 11110001111001100110101010100000000000000000000

c11: 1111010101010011001100001111000000000000000000000

d11: 1111000111100110011010101010000000000000000000000

c12: 111101010101001100110000111100000000000000000000000

d12: 11110001111001100110101010100000000000000000000000

c13: 11110101010100110011000011110000000000000000000000000

d13: 1111000111100110011010101010000000000000000000000000

c14: 1111010101010011001100001111000000000000000000000000000

d14: 111100011110011001101010101000000000000000000000000000

c15: 11110101010100110011000011110000000000000000000000000000

d15: 1111000111100110011010101010000000000000000000000000000

最佳答案

BigInteger 实现了无限精度的整数,因此向左移动将继续向左侧添加零。你需要轮换:

private static BigInteger rotateLeft(BigInteger bi) {
    BigInteger ret = bi.shiftLeft(1);
    if (ret.testBit(32)) {
        ret = ret.clearBit(32).setBit(0);
    }
    return ret;
}

对于 32 位数字,这将是相当低效的,因此您最好使用原语来旋转 DES 的 28 位一半。我不熟悉 DES 算法,所以我假设您需要 BigInteger 来做其他事情。

private static BigInteger rotateLeftPrimitive(BigInteger bi) {
    int value = bi.intValue();
    return BigInteger.valueOf(((value << 1) & 0xffffffe) | ((value >>> 27) & 1));
}

关于java - 在 Java 中使用 BigIntegers 进行 BitShifting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2727005/

相关文章:

mysql - 在大表中使用用户 ID 作为主键

java - 在 PDFBox 上禁用日志记录

java - 将特定行和列的 .csv 转换为 .xls 值加倍

java - 使用spring boot(安全)和keycloak启用角色身份验证?

java - DES加密文本的大小

.net - 数据库文件无法保护时,如何在.NET中实现本地数据库?

javascript - 在 Javascript 中使用对象作为键时的奇怪行为

java - 构建 SAML IDP

ssl - 使用 orapki/wallet manager 在 oracle 11g 中使用 sha-256 作为哈希算法创建证书

mysql - SQL:KEY id_2 有什么作用?