1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.owasp.dependencycheck.utils;
19
20 import java.io.File;
21 import java.io.IOException;
22 import java.security.NoSuchAlgorithmException;
23
24 import org.junit.Assert;
25 import org.junit.Rule;
26 import org.junit.Test;
27 import org.junit.rules.ExpectedException;
28 import org.owasp.dependencycheck.utils.Checksum;
29 import org.owasp.dependencycheck.utils.Checksum;
30
31
32
33
34
35 public class ChecksumTest {
36
37 @Rule
38 public ExpectedException expectedException = ExpectedException.none();
39
40
41
42
43
44
45 @Test
46 public void testGetChecksum() throws Exception {
47 String algorithm = "MD5";
48 File file = new File(this.getClass().getClassLoader().getResource("checkSumTest.file").getPath());
49 byte[] expResult = {-16, -111, 92, 95, 70, -72, -49, -94, -125, -27, -83, 103, -96, -101, 55, -109};
50 byte[] result = Checksum.getChecksum(algorithm, file);
51 boolean arraysAreEqual = true;
52 if (expResult.length == result.length) {
53 for (int i = 0; arraysAreEqual && i < result.length; i++) {
54 arraysAreEqual = result[i] == expResult[i];
55 }
56 } else {
57 Assert.fail("Checksum results do not match expected results.");
58 }
59 Assert.assertTrue(arraysAreEqual);
60 }
61
62
63
64
65
66
67 @Test
68 public void testGetChecksum_FileNotFound() throws Exception {
69 String algorithm = "MD5";
70 File file = new File("not a valid file");
71
72 expectedException.expect(IOException.class);
73 Checksum.getChecksum(algorithm, file);
74 }
75
76
77
78
79
80
81
82 @Test
83 public void testGetChecksum_NoSuchAlgorithm() throws Exception {
84 String algorithm = "some unknown algorithm";
85 File file = new File(this.getClass().getClassLoader().getResource("checkSumTest.file").getPath());
86
87 expectedException.expect(NoSuchAlgorithmException.class);
88 Checksum.getChecksum(algorithm, file);
89 }
90
91
92
93
94
95
96 @Test
97 public void testGetMD5Checksum() throws Exception {
98 File file = new File(this.getClass().getClassLoader().getResource("checkSumTest.file").getPath());
99
100 String expResult = "f0915c5f46b8cfa283e5ad67a09b3793";
101 String result = Checksum.getMD5Checksum(file);
102 Assert.assertEquals(expResult, result);
103 }
104
105
106
107
108
109
110 @Test
111 public void testGetSHA1Checksum() throws Exception {
112 File file = new File(this.getClass().getClassLoader().getResource("checkSumTest.file").getPath());
113
114 String expResult = "b8a9ff28b21bcb1d0b50e24a5243d8b51766851a";
115 String result = Checksum.getSHA1Checksum(file);
116 Assert.assertEquals(expResult, result);
117 }
118
119
120
121
122 @Test
123 public void testGetHex() {
124 byte[] raw = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
125
126 String expResult = "000102030405060708090a0b0c0d0e0f10";
127 String result = Checksum.getHex(raw);
128 Assert.assertEquals(expResult, result);
129 }
130 }