java - 将 BitSet 转换为具有相同表示的 byte[]
问题描述
我正在为 DES 生成一个 64 位密钥,其中只有 20 位有效,即其余部分用零填充。我试图接近它的方法是使用BitSet
23 位,其中每 8 位被跳过(即保持为假),其余的被确定为SecureRandom.nextBoolean()
. 因此,我的 BitSet 的输出是 23 位,其中每 8 位为假。我这样做的原因是确保奇偶校验位不是 20 位有效密钥的一部分。之后,我尝试BitSet
通过 using转换Bitset.toByteArray()
,这给了我 3 个字节,然后我用零填充其余 5 个字节。但是,当我尝试将BitSet
a转换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[]
。
解决方案
推荐阅读
- python - 如何在没有多重拟合的情况下将最佳拟合线拟合到曲线,或者是否有替代方法
- linux - Ubuntu Docker 安装;什么是稳定的存储库?
- javascript - 显示空内容的弹出模型
- python - 是否可以在虚拟环境中启动作业并在作业在后台运行时停用虚拟环境?
- java - 当我从 mysql 迁移到 postgresql 时,login 总是读取 null
- jenkins - APM-Agent 附加到 Jenkins 应用程序返回 403 No Valid Crumb was included in request
- python - 从 Pandas 数据框中的序列中查找缺失的数字
- javascript - 如何将数组的一个元素与其他元素进行比较并在 JavaSript 中创建一个新组
- python - 为什么我在这里没有出现超出范围的错误?
- c - 如何在 Eclipse 中使用 Json-c 解析器或任何其他解析器在 Windows 中进行 C 编程