前言:这是一个家庭作业,我几乎完成了——只是这小块阻碍了我完成。有了这些信息,请不要为我编写任何代码,但请注意我可能做错了什么。
好的,这是一个简单的想法。使用 RSA 通过 ECB 模式加密/解密文件。这意味着如果块大小为 4,并且字符串为“testdata”,则“test”将使用密钥加密,写入文件,然后“数据”将使用密钥加密并写入文件。
我的实现使用 128 作为块大小,但我遇到了一个奇怪的错误。
这是我加密 128 块并附加到文件的代码:
ArrayList<byte[]> bytes = new ArrayList<byte[]>();
String file = read_file(input_file);
int index = 0;
while (index<file.length()) {
byte[] block = file.substring(index, Math.min(index+128,file.length())).getBytes();
cipher = new BigInteger(block).modPow(public_exponent, public_modulus).toByteArray();
bytes.add(cipher);
append_bytes(output_file, cipher);
index+=128;
}
加密工作完美。这就是为什么我认为加密不是问题的原因:
- 解密正在写入文件的数据有效
- 将所有加密数据添加到列表中包含与读取文件相同的数据
- 如果从我上面提到的列表中解密,解密工作完美无缺。
不过,这是最奇怪的问题。
这会产生正确的输出:
for(int i = 0; i < bytes.size(); i++) {
decrypted = new BigInteger(bytes.get(i)).modPow(d, modulus).toByteArray();
System.out.print(new String(decrypted));
}
但这没用,因为只有在加密后才能解密有什么意义。
这并非每次都有效,但有时确实有效:
index = 0;
file = new String(read_bytes(output_file));
while(index < file.length()) {
byte[] block = file.substring(index, Math.min(index+128,file.length())).getBytes();
decrypted = new BigInteger(block).modPow(d, modulus).toByteArray();
System.out.println(new String(decrypted));
index+= 128;
}
我正在以与写入文件相同的方式读取文件;以 128 块为单位。但它没有正确读取它,因此,解密失败!
知道为什么会发生这种情况吗?