为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法使用 Guava 获取 InputStream 的哈希码?

有没有办法使用 Guava 获取 InputStream 的哈希码?

弑天下 2022-05-12 18:46:02
有没有办法在 Java 中获取 InputStream 的 HashCode,我正在尝试使用<p:fileUpload/>PrimeFaces 上传图片,将其转换为 HashCode 并将其与另一张图片进行比较。目前我正在尝试这个: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();        }    }有没有办法把它InputStream变成哈希码?
查看完整描述

3 回答

?
POPMUISE

TA贡献1765条经验 获得超5个赞

你想要做的是从ByteStreams.copy(input, Funnels.asOutputStream(hasher))哪里hasher获得例如Hashing.sha256().newHasher()。然后,调用hasher.hash()以获取结果HashCode



查看完整回答
反对 回复 2022-05-12
?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

如果要计算其包含的字节的哈希值,则必须读取 InputStream。首先将 InputSteam 读取到 byte[]。


使用 Guava 使用 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 流式传输到磁盘到数据库中。Guava 提供了一个封装了 InputStream 的类,它为您执行此操作 HashingInputStream:


首先用 HashinInputStream 包装你的 InputStream


HashingInputStream hin = new HashingInputStream(Hashing.sha256(), in);

然后让 HashingInputStream 以您喜欢的任何方式读取


while(hin.read() != -1);

然后从 HashingInputStream 中获取哈希


byte[] sha256Hash = hin.hash().asBytes();


查看完整回答
反对 回复 2022-05-12
?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

我建议使用 Files.asByteSource(fileSource.getFile()).hash(hashFunction).padToLong()



查看完整回答
反对 回复 2022-05-12
  • 3 回答
  • 0 关注
  • 195 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信