我所做的是,我创建了两个文件 - 一个(message.txt)有消息“hello!”,我创建了它的 Messagedigest 并将其存储在第二个文件(md.txt)中。现在我正在尝试创建一个程序,它同时接受消息及其 md,为消息创建一个新的 md 并比较 md 以检查消息是否被操纵。这是代码:
//getting the original md
String omd="";
FileReader fr= new FileReader("D:\\Ns\\md.txt");
BufferedReader br= new BufferedReader(fr);
while((omd=br.readLine())!=null)
{
System.out.println("original md:"+omd);
}
//creating md of the file
MessageDigest md= MessageDigest.getInstance("MD5");
FileInputStream file =new FileInputStream("D:\\Ns\\message.txt");
byte[] dataBytes= new byte[1024];
int nread=0,nread1;
while((nread=file.read(dataBytes))!=-1)
{
md.update(dataBytes,0,nread);
}
byte[] mdbytes=md.digest();
StringBuffer sb= new StringBuffer();
for(int i=0; i<mdbytes.length; i++)
{
sb.append(Integer.toString((mdbytes[i]& 0xff)+0x100, 16).substring(1));
}
String nmd=sb.toString();
System.out.println("md created:"+nmd);
//comparing both
if(nmd.equals(omd))
{
System.out.println("the file is not manipulated!!");
}
else{
System.out.println("the file is manipulated!!");
}
没有错误并且代码正在运行,当我在文件中操作消息时,它表明它被操作了。但即使它没有被操纵并且两个 mds 相同,它也表明消息被操纵了。
这是输出:
original md:61c1ec2a71e1e72d95ca5a37589dbff3
md created:61c1ec2a71e1e72d95ca5a37589dbff3
the file is manipulated!!
为什么这样?我在这里做错了什么?