1 20 21 package net.sourceforge.lightcrypto; 22 23 import org.bouncycastle.crypto.digests.SHA1Digest; 24 import org.bouncycastle.crypto.macs.HMac; 25 import org.bouncycastle.util.encoders.Base64; 26 27 import java.io.*; 28 29 37 38 public class HMacs { 39 private static int BUFFERSIZE_TEXT = 64; 40 private static int BUFFERSIZE_FILE = 8192; 41 42 49 public static StringBuffer mac( 50 StringBuffer text 51 ) throws CryptoException { 52 return mac(new ByteArrayInputStream(text.toString().getBytes()), BUFFERSIZE_TEXT); 53 } 54 55 63 public static StringBuffer mac( 64 InputStream is 65 , int buffersize 66 ) throws CryptoException { 67 68 try { 69 HMac hmac = new HMac(new SHA1Digest()); 70 71 byte[] result = new byte[hmac.getMacSize()]; 72 byte[] buffer = new byte[buffersize]; 73 int length = 0; 74 75 while ((length = is.read(buffer)) != -1) { 77 hmac.update(buffer, 0, length); 78 } 79 80 hmac.doFinal(result, 0); 81 82 return new StringBuffer (new String (Base64.encode(result))); 83 } catch (Exception ex) { 84 ex.printStackTrace(); 85 throw new CryptoException(ex.getMessage()); 86 } 87 } 88 89 98 public static StringBuffer macFromFile( 99 String file 100 ) throws CryptoException, FileNotFoundException, IOException { 101 102 FileInputStream fis = new FileInputStream(file); 103 StringBuffer res = mac(fis, BUFFERSIZE_FILE); 104 fis.close(); 105 return res; 106 } 107 } 108 | Popular Tags |