我正在尝试创建一个涉及密码学的简单Java程序。
首先,我从文件clearmsg.txt中读取一个32字节的数据块,然后将其转换为整数,并用于加密。不幸的是,密文大小并不是固定的;有时返回30个字节,有时返回26个字节。这似乎与加法操作的结果无关。
如何确保它变成一个32字节的密码块?如何添加位/字节到此块中?因为当我尝试解密此块时,需要读取32个密文字节。
首先,我从文件clearmsg.txt中读取一个32字节的数据块,然后将其转换为整数,并用于加密。不幸的是,密文大小并不是固定的;有时返回30个字节,有时返回26个字节。这似乎与加法操作的结果无关。
如何确保它变成一个32字节的密码块?如何添加位/字节到此块中?因为当我尝试解密此块时,需要读取32个密文字节。
private void ENC_add() {
final File clearmsg = new File("F:/java_projects/clearmsg.txt");
final File ciphermsg = new File("F:/java_projects/ciphermsg.txt");
final byte[] block = new byte[32];
try {
final FileInputStream fis = new FileInputStream(clearmsg);
final FileOutputStream fcs = new FileOutputStream(ciphermsg);
int i;
while ((i = fis.read(block)) != -1) {
// Is this process true
// here M2 (Plain text) shuld be 32 byte
M2 = new BigInteger(block);
// here encrypt M2 by add k1 where k1 any number less than P
CM2 = M2.add(K1).mod(P);
// here my problem some time Cipher CM2 length 31 , some time CM2 length 32 ,some time CM2 length 30
System.out.println("THE CM2=" + CM2.toByteArray().Length);
fcs.write(CM2.toByteArray(), 0, i);
}
fcs.close();
}
catch (final IOException e) {
e.printStackTrace();
}
}
// Here problem for decrypt
private void DEC_ADD() {
// DECREPT METHOD
final File ciphermsg = new File("F:/java_projects/ciphermsg.txt");
final File clearmsg = new File("F:/java_projects/rciphermsg.txt");
final byte[] block = new byte[32];
try {
final FileInputStream fis = new FileInputStream(ciphermsg);
final FileOutputStream fos = new FileOutputStream(clearmsg);
int i;
while ((i = fis.read(block)) != -1) {
// CM2 NOT STATIC BITS NUMBER BECAUSE INDEPENDET ON RESULT ADDITIONAL AND PRIME NUMBER P through ENCRYPT
// Process
CM2 = new BigInteger(block);
// here RM2 is decrypt cipher (CM2) NOTE When encrypt above M2 WAS 32 bytes and Cipher CM2 was 30 bytes
// and When I read from file 32 bytes then this is my problem
RM2 = CM2.subtract(K1).mod(P);
fos.write(RM2.toByteArray(), 0, i);
}
fos.close();
System.out.println("THE RM2=" + CM2.bitLength());
} catch (final IOException e) {
e.printStackTrace();
}
}
BigInteger
,它需要在数字前面带有值为00
的字节。否则,该数字将被解释为负数(二进制补码)。尝试从上面的new BigInteger(1, data)
中删除1
,你可能会看到负数…以十六进制或二进制数编码可以获得更好的视图。 - Maarten Bodewes