1 20 21 package net.sourceforge.lightcrypto; 22 23 import org.bouncycastle.crypto.Digest; 24 import org.bouncycastle.crypto.digests.MD5Digest; 25 import org.bouncycastle.crypto.digests.SHA1Digest; 26 import org.bouncycastle.crypto.digests.SHA256Digest; 27 import org.bouncycastle.util.encoders.Base64; 28 29 import java.io.*; 30 31 39 40 public class Digesters { 41 private static int BUFFERSIZE_TEXT = 64; 42 private static int BUFFERSIZE_FILE = 8192; 43 44 52 public static StringBuffer digest( 53 StringBuffer text 54 , String algorithm) throws CryptoException { 55 return digest(new ByteArrayInputStream(text.toString().getBytes()), algorithm, BUFFERSIZE_TEXT); 56 } 57 58 66 public static StringBuffer digest( 67 InputStream is 68 , String algorithm 69 , int buffersize 70 ) throws CryptoException { 71 Digest digest; 72 73 try { 74 if (algorithm != null) { 75 if (algorithm.equalsIgnoreCase("SHA1")) { 76 digest = new SHA1Digest(); 77 } else if (algorithm.equalsIgnoreCase("SHA256")) { 78 digest = new SHA256Digest(); 79 } else { 80 digest = new MD5Digest(); 81 } 82 } else { 83 digest = new MD5Digest(); 84 } 85 86 byte[] result = new byte[digest.getDigestSize()]; 87 byte[] buffer = new byte[buffersize]; 88 int length = 0; 89 90 while ((length = is.read(buffer)) != -1) { 92 digest.update(buffer, 0, length); 93 } 94 95 digest.doFinal(result, 0); 96 97 return new StringBuffer (new String (Base64.encode(result))); 98 } catch (Exception ex) { 99 ex.printStackTrace(); 100 throw new CryptoException(ex.getMessage()); 101 } 102 } 103 104 114 public static StringBuffer digestFromFile( 115 String file 116 , String algorithm 117 ) throws CryptoException, FileNotFoundException, IOException { 118 119 FileInputStream fis = new FileInputStream(file); 120 StringBuffer res = digest(fis, algorithm, BUFFERSIZE_FILE); 121 fis.close(); 122 return res; 123 } 124 } 125 | Popular Tags |