Added SHA-256 file digest utility methods.

These read the file in small chunks, to reduce memory.
This commit is contained in:
CalDescent
2021-10-09 16:22:21 +01:00
parent f34bdf0f58
commit a78af8f248
2 changed files with 103 additions and 2 deletions

View File

@@ -10,7 +10,12 @@ import org.qortal.utils.Base58;
import static org.junit.Assert.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.SecureRandom;
import java.util.Random;
import org.bouncycastle.crypto.agreement.X25519Agreement;
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
@@ -40,6 +45,37 @@ public class CryptoTests extends Common {
assertArrayEquals(expected, digest);
}
@Test
public void testFileDigest() throws IOException {
byte[] input = HashCode.fromString("00").asBytes();
Path tempPath = Files.createTempFile("", ".tmp");
Files.write(tempPath, input, StandardOpenOption.CREATE);
byte[] digest = Crypto.digest(tempPath.toFile());
byte[] expected = HashCode.fromString("6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d").asBytes();
assertArrayEquals(expected, digest);
Files.delete(tempPath);
}
@Test
public void testFileDigestWithRandomData() throws IOException {
byte[] input = new byte[128];
new Random().nextBytes(input);
Path tempPath = Files.createTempFile("", ".tmp");
Files.write(tempPath, input, StandardOpenOption.CREATE);
byte[] fileDigest = Crypto.digest(tempPath.toFile());
byte[] memoryDigest = Crypto.digest(input);
assertArrayEquals(fileDigest, memoryDigest);
Files.delete(tempPath);
}
@Test
public void testPublicKeyToAddress() {
byte[] publicKey = HashCode.fromString("775ada64a48a30b3bfc4f1db16bca512d4088704975a62bde78781ce0cba90d6").asBytes();