· 9 years ago · Sep 30, 2016, 06:26 AM
1import javax.crypto.Mac;
2import javax.crypto.spec.SecretKeySpec;
3import javax.xml.bind.DatatypeConverter;
4
5import java.security.InvalidKeyException;
6import java.security.NoSuchAlgorithmException;
7import org.apache.commons.codec.binary.Hex;
8
9import java.io.File;
10import java.io.FileInputStream;
11import java.io.UnsupportedEncodingException;
12import java.math.BigInteger;
13import java.nio.charset.StandardCharsets;
14
15
16public class ABCHash{
17 public static void main(String[] args) throws Exception
18 {
19 try{
20 int character;
21 StringBuffer buffer = new StringBuffer("");
22 FileInputStream inputStream = new FileInputStream(new File("C:/EncPDF.txt"));
23
24 while( (character = inputStream.read()) != -1)
25 buffer.append((char) character);
26
27 inputStream.close();
28 System.out.println("Fetching data from the file"+buffer);
29
30 StringBuffer sbuf = new StringBuffer(buffer);
31
32 String str=sbuf.toString();
33
34 System.out.println( "Data = "+ str);
35 if(str!=null)
36 {
37 String key = "0123456789ABCDEF0123456789ABCDEF"; // Assuming the key as 0123456789ABCDEF
38
39 byte[] hexvalue= stringToHexByte(str);
40 byte[] hexkey=stringToHexByte(key);
41 byte[] byHMAC = encode(hexkey, hexvalue);
42 String stEncryptedData = Hex.encodeHexString(byHMAC).toUpperCase();
43
44 System.out.println("Encrypted data =n "+stEncryptedData);
45 }
46 }
47 catch(Exception e)
48 {
49 System.out.println("Exception in the file reading"+e);
50 }
51
52 }
53
54 private static byte[] encode(byte[] hexkey, byte[] hexvalue) {
55 try {
56 Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
57 SecretKeySpec secret_key = new SecretKeySpec(hexkey, "HmacSHA256");
58 sha256_HMAC.init(secret_key);
59
60 return sha256_HMAC.doFinal(hexvalue);
61
62 } catch (NoSuchAlgorithmException e) {
63 e.printStackTrace();
64 } catch (InvalidKeyException e) {
65 e.printStackTrace();
66 }
67
68 return null;
69 }
70
71 public static String stringToHex(String base) throws UnsupportedEncodingException
72 {
73 return String.format("%040x", new BigInteger(1, base.getBytes(StandardCharsets.US_ASCII)));
74 }
75
76 public static byte[] stringToHexByte(String base) throws UnsupportedEncodingException
77 {
78 System.out.println(stringToHex(base).toUpperCase());
79 return DatatypeConverter.parseHexBinary(stringToHex(base).toUpperCase());
80 }
81
82}