Is there a way to get the HashCode of an InputStream in Java,
I am trying to upload a picture using the <p:fileUpload/>
from PrimeFaces, converting it into a HashCode and comparing it to another picture.
At the moment I'm trying this:
public void save(FileUploadEvent event) throws IOException {
HashCode hashCode = null;
HashCode hashCodeCompare = null;
hashCode = Files.asByteSource(new File(event.toString())).hash(Hashing.murmur3_128(50));
hashCodeCompare = Files.asByteSource(new File(FilePathOfFileToCompare)).hash(Hashing.murmur3_128(50));
boolean hashTrueFalse;
if(hashCode.equals(hashCodeCompare)) {
System.out.println("true");
} else{
System.out.println("false");
}
try (InputStream input = event.getFile().getInputstream()) {
String imageName = generateFileName() + "." + fileExtensions(event.getFile().getFileName());
String imageLink = PICTURE_DESTINATION + "\\" + imageName;
Picture picture = new Picture();
picture.setPictureUrl(imageLink);
pictureService.createOrUpdate(picture);
personForm.getCurrentPersonDTO().setPictureDTO(pictureMapper.toDTO(picture));
} catch (IOException e) {
e.printStackTrace();
}
}
Is there any way to turn the InputStream
into a hashcode?
答案 0 :(得分:2)
如果要计算包含在其上的字节的哈希值,则必须阅读InputStream。首先将InputSteam读取为byte []。
在番石榴中使用ByteStreams:
InputStream in = ...;
byte[] bytes = ByteStreams.toByteArray(in);
一种流行的替代方法是使用Commons IO:
InputStream in = ...;
byte[] bytes = IOUtils.toByteArray(in);
然后您可以在字节数组上调用Arrays.hashCode():
int hash = java.util.Arrays.hashCode(bytes);
但是您可能会考虑使用SHA256作为哈希函数,因为您不太可能发生冲突:
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] sha256Hash = digest.digest(bytes);
如果您不想将整个流读取到内存中的字节数组,则可以计算哈希值,因为其他人正在读取InputStream。例如,您可能想将InputStream流式传输到磁盘并传输到db中。 Guava提供了一个包装InputStream的类,该类为您HashingInputStream:
首先用HashinInputStream包装您的InputStream
HashingInputStream hin = new HashingInputStream(Hashing.sha256(), in);
然后以您喜欢的任何方式读取HashingInputStream
while(hin.read() != -1);
然后从HashingInputStream获取哈希
byte[] sha256Hash = hin.hash().asBytes();
答案 1 :(得分:2)
您想要做的是ByteStreams.copy(input, Funnels.asOutputStream(hasher))
,其中hasher
是从Hashing.sha256().newHasher()
。然后,调用hasher.hash()
以得到生成的HashCode
。
答案 2 :(得分:0)
我建议使用Files.asByteSource(fileSource.getFile()).hash(hashFunction).padToLong()