Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 3 additions & 9 deletions dubbo-common/src/main/java/org/apache/dubbo/common/io/Bytes.java
Original file line number Diff line number Diff line change
Expand Up @@ -909,15 +909,9 @@ private static byte[] decodeTable(String code) {
private static byte[] getMD5(InputStream is, int bs) throws IOException {
MessageDigest md = getMessageDigest();
byte[] buf = new byte[bs];
while (is.available() > 0) {
int read, total = 0;
do {
if ((read = is.read(buf, total, bs - total)) <= 0) {
break;
}
total += read;
} while (total < bs);
md.update(buf);
int read;
while ((read = is.read(buf)) != -1) {
md.update(buf, 0, read);
}
return md.digest();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
*/
package org.apache.dubbo.common.io;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -124,7 +126,32 @@ void testMD5ForString() {
void testMD5ForFile() throws IOException {
byte[] md5 = Bytes.getMD5(new File(
getClass().getClassLoader().getResource("md5.testfile.txt").getFile()));
assertThat(md5, is(Bytes.base642bytes("iNZ+5qHafVNPLJxHwLKJ3w==")));
assertThat(md5, is(Bytes.base642bytes("/D/5joxqDTCH1RXARz+Gdw==")));
}

@Test
void testMD5ForInputStreamBoundaries() throws IOException {
int[] lengths = {12, 8191, 8192, 8193};
for (int length : lengths) {
byte[] source = new byte[length];
for (int i = 0; i < source.length; i++) {
source[i] = (byte) i;
}
assertThat(Bytes.getMD5(new ByteArrayInputStream(source)), is(Bytes.getMD5(source)));
}
}

@Test
void testMD5ForInputStreamWithNoAvailableBytes() throws IOException {
byte[] source = "hello world!".getBytes();
InputStream inputStream = new ByteArrayInputStream(source) {
@Override
public int available() {
return 0;
}
};

assertThat(Bytes.getMD5(inputStream), is(Bytes.getMD5(source)));
}

@Test
Expand Down
Loading