I want to compare the content in cis and resStream. My target is to check if the reEncryption gave me the same data or different.
Any leads would be really great. Thanks
final InputStream cis = test.getEncryptingInputStream(is);
final InputStream resStream = test.reEncrypt(cis, "");
How can we check the content of InputStreams?
The idea is to read the whole stream as a String, then md5 the string, and finally check if the hashes are the same. MD5 guarantees that hashing the same string will produce the same result.
public String readInputStreamAsString(InputStream stream) {
int bufferSize = 1024;
char[] buffer = new char[bufferSize];
StringBuilder out = new StringBuilder();
Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
for (int numRead; (numRead = in.read(buffer, 0, buffer.length)) > 0; ) {
out.append(buffer, 0, numRead);
}
return out.toString();
}
public String hashMD5(String input) {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
return hashtext;
}
public void TestMe() {
final InputStream cis = test.getEncryptingInputStream(is);
final InputStream resStream = test.reEncrypt(cis, "");
String cisAsString = readInputStreamAsString(cis);
String resStreamAsString = readInputStreamAsString(resStream);
String cisMD5 = hashMD5(cisAsString);
String resMD5 = hashMD5(resStreamAsString);
if(cisMD5.equals(resMD5)) {
System.out.println("Streams contents are equal");
} else {
System.out.println("Stream contents are NOT equal :(");
}
}