首页 > 解决方案 > 将 BitSet 转换为具有相同表示的 byte[]

问题描述

我正在为 DES 生成一个 64 位密钥,其中只有 20 位有效,即其余部分用零填充。我试图接近它的方法是使用BitSet23 位,其中每 8 位被跳过(即保持为假),其余的被确定为SecureRandom.nextBoolean(). 因此,我的 BitSet 的输出是 23 位,其中每 8 位为假。我这样做的原因是确保奇偶校验位不是 20 位有效密钥的一部分。之后,我尝试BitSet通过 using转换Bitset.toByteArray(),这给了我 3 个字节,然后我用零填充其余 5 个字节。但是,当我尝试将BitSeta转换byte[]为表示形式时,就会出现问题。

public static byte[] generateDesKey() {
        BitSet temp = new BitSet();
        byte[] zeroByteKey = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        Random r = new SecureRandom();

        for (int i = 0; i < 64; i++) {
            if (i % 8 != 0 && i < 23) {

                temp.set(i, r.nextBoolean());
            }
        }

          StringBuilder sb = new StringBuilder();
          for( int i = 0; i < temp.length();  i++ )
          {
              sb.append( temp.get( i ) == true ? 1: 0 );
          }

          System.out.println("Bitset " +sb );

        byte[] tempByteKey = temp.toByteArray();

        for (byte b : tempByteKey) {
            System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1));
        }

        for (int i = 0; i < tempByteKey.length; i++) {
            zeroByteKey[i] = tempByteKey[i];
        }

        return zeroByteKey;
    }

输出示例:

Bitset 00010100011110010011101 // 23 bits where parity bits are skipped
Converted BitSet to byte[] in binary 101101000000111001011100 // 24 bits where every 8 bits are reversed

BitSet我假设第二个输出是 24 位的原因是因为 23 位在从 转换为时四舍五入为 3 个字节byte[]

标签: javaarraysbytebitset

解决方案


推荐阅读