· 7 years ago · Feb 24, 2018, 04:04 PM
1class GetDigestKey {
2 public $ALGORITHM = 'SHA256';
3 function sayPlainTextHello($filename) {
4 try {
5 $myfile = fopen($filename, "r") or die("Unable to open file!");
6 $iteration=2620;
7 $key="mykey";
8 return $this->generateHash($myfile, $iteration, $key);
9
10 } catch (Exception $e) {
11
12 return "Data Not Found";
13 }
14 }
15
16 function generateHash($file, $iteration, $key){
17 //$hash = hash_hmac('sha256', 'hello, world!', 'mykey');
18
19 $inithash=hash_init($this->ALGORITHM,1,$key);
20
21 //mb_strlen($string, '8bit')
22
23 while ($buffer=fread($file,"2048")) {
24 hash_update($inithash, $buffer);
25 }
26
27 $hash = hash_final($inithash);
28 $hashbyte = unpack('C*',$hash);
29 for($i=0;$i<$iteration;$i++)
30 {
31 //unset($hashbyte);
32 $inithash=hash_init($this->ALGORITHM);
33 $inithash = hash_final($inithash);
34
35 }
36
37 return base64_encode($inithash);
38 }
39
40 }
41 echo "<pre> Response :";
42 $md = new GetDigestKey();
43 $result = $md->sayPlainTextHello("xyz.txt");
44 echo $result;
45
46import java.io.IOException;
47import java.io.InputStream;
48import java.net.URL;
49import java.security.InvalidKeyException;
50import java.security.NoSuchAlgorithmException;
51import javax.crypto.Mac;
52import javax.crypto.spec.SecretKeySpec;
53import javax.ws.rs.GET;
54import javax.ws.rs.Path;
55import javax.ws.rs.PathParam;
56import javax.ws.rs.Produces;
57import javax.ws.rs.core.MediaType;
58import org.apache.commons.codec.binary.Base64;
59
60@Path("/digest")
61
62public class GetDigestKey {
63 @GET
64
65 @Path("/{filename}")
66
67 @Produces(MediaType.TEXT_PLAIN)
68
69 public String sayPlainTextHello(@PathParam("filename") String fileName) {
70
71 try {
72
73 InputStream is = new URL(fileName).openStream();
74
75 int iteration=2620;
76
77 String key="mykey";
78
79 GetDigestKey hlv = new GetDigestKey();
80
81 return hlv.generateHash(is, iteration, key);
82
83 } catch (Exception e) {
84 return "Data Not Found";
85 }
86 }
87
88 final String ALGORITHM = "HmacSHA256";
89
90 private String generateHash(final InputStream is, final int iteration, final String key) throws IOException,NoSuchAlgorithmException, InvalidKeyException {
91
92 Mac sha256_HMAC;
93
94 sha256_HMAC = Mac.getInstance(ALGORITHM);
95
96 final SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(), ALGORITHM);
97
98 sha256_HMAC.init(secret_key);
99
100 byte[] bytesBuffer = new byte[2048];
101
102 int bytesRead = -1;
103
104 while ((bytesRead = is.read(bytesBuffer)) != -1) {
105
106 sha256_HMAC.update(bytesBuffer, 0, bytesRead);
107
108 }
109 byte[] digestValue = sha256_HMAC.doFinal();
110
111 for (int i = 0; i < iteration; i++) {
112
113 sha256_HMAC.reset();
114
115 digestValue = sha256_HMAC.doFinal(digestValue);
116
117 }
118
119 return Base64.encodeBase64String(digestValue);
120 }
121}