Subversion Repositories bacoAlunos

Rev

Rev 1 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
1 fvelez 1
/*
2
 * BytesUtils.java
3
 *
4
 * Created on 2 de Dezembro de 2002, 0:24
5
 */
6
 
7
package jomm.utils;
8
 
9
import java.io.*;
10
import java.math.BigInteger;
11
import java.rmi.dgc.VMID;
12
import java.security.*;
13
import java.util.Random;
14
import org.apache.log4j.Logger;
15
 
16
/**
17
 *
18
 * @author  Jorge Machado
19
 */
20
 
21
public class BytesUtils {
22
    private static int counter = 0;
23
    private static 1.5.0/docs/api/java/util/Random.html">Random random = new 1.5.0/docs/api/java/util/Random.html">Random();
24
    private static 1.5.0/docs/api/java/rmi/dgc/VMID.html">VMID vmid = new 1.5.0/docs/api/java/rmi/dgc/VMID.html">VMID();
25
    private static 1.5.0/docs/api/java/util/logging/Logger.html">Logger logger = 1.5.0/docs/api/java/util/logging/Logger.html">Logger.getLogger(BytesUtils.class);
26
 
27
    /** Private Constructor */
28
 
29
    private BytesUtils () {}
30
 
31
 
32
         public static 1.5.0/docs/api/java/lang/String.html">String getMd5FromFile(1.5.0/docs/api/java/lang/String.html">String filepath)
33
         {
34
                        return getMD5(getBytes(filepath));
35
         }
36
 
37
     public static byte[] getBytes(1.5.0/docs/api/java/lang/String.html">String fileName)
38
    {
39
 
40
        byte[] data = null;
41
        try{
42
 
43
            1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream r = new 1.5.0/docs/api/java/io/FileInputStream.html">FileInputStream(fileName);
44
 
45
            1.5.0/docs/api/java/io/File.html">File f = new 1.5.0/docs/api/java/io/File.html">File(fileName);
46
 
47
            //this value is never bigger than a integer
48
            int len =(int) f.length();
49
 
50
            data = new byte[len];
51
 
52
            int bytesRead = 0;
53
 
54
            bytesRead = r.read(data);
55
 
56
            r.close();
57
 
58
            if(bytesRead == -1)
59
                return null;
60
 
61
 
62
        }
63
        catch(1.5.0/docs/api/java/io/FileNotFoundException.html">FileNotFoundException e)
64
        {
65
            logger.error("Files getBytes()",e);
66
            return null;
67
        }
68
        catch(1.5.0/docs/api/java/io/IOException.html">IOException e)
69
        {
70
            logger.error("Files getData()",e);
71
            return null;
72
        }
73
        return data;
74
    }
75
 
76
    public static 1.5.0/docs/api/java/lang/String.html">String getMD5(1.5.0/docs/api/java/lang/String.html">String data)
77
    {
78
        return getMD5(data.getBytes());
79
    }
80
 
81
    public static 1.5.0/docs/api/java/lang/String.html">String getMD5(byte[] data)
82
    {
83
        return toHex(getMD5Bytes(data));
84
    }
85
 
86
    public static 1.5.0/docs/api/java/lang/String.html">String getDigestMD5Hex(1.5.0/docs/api/java/lang/String.html">String str){
87
        byte[] digest = getDigestMD5(str.getBytes());
88
        if(digest != null)
89
            return toHex(digest);
90
 
91
        return null;
92
    }
93
    public static byte[] getDigestMD5(byte[] data)
94
    {
95
        byte[] result = null;
96
        try{
97
            1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest md5 = 1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest.getInstance("MD5");
98
 
99
            md5.update(data);
100
 
101
            result = md5.digest();            
102
 
103
        }
104
        catch(1.5.0/docs/api/java/security/NoSuchAlgorithmException.html">NoSuchAlgorithmException e)
105
        {
106
            //this never hapens beacause MD5 is a correct algoritm
107
             logger.fatal("MD5 function does not exists",e);
108
        }
109
 
110
        return result;
111
    }
112
    /*********************************************************
113
     *Returns true if the two digests are equal
114
     *
115
     *******************************************************/
116
    public static boolean isDigestEqual(byte[] b1,byte[] b2)
117
    {
118
 
119
        try{
120
            1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest md5 = 1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest.getInstance("MD5");
121
 
122
            return md5.isEqual(b1,b2);
123
 
124
        }
125
        catch(1.5.0/docs/api/java/security/NoSuchAlgorithmException.html">NoSuchAlgorithmException e)
126
        {
127
            //this never hapens beacause MD5 is a correct algoritm
128
             logger.fatal("MD5 function does not exists",e);
129
        }
130
 
131
        return false;
132
 
133
    }
134
 
135
    public static byte[] getMD5Bytes(byte[] data)
136
    {
137
        try
138
        {
139
            1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest digest = 1.5.0/docs/api/java/security/MessageDigest.html">MessageDigest.getInstance("MD5");
140
 
141
            return digest.digest(data);
142
        }
143
        catch (1.5.0/docs/api/java/security/NoSuchAlgorithmException.html">NoSuchAlgorithmException e)
144
        {
145
            logger.fatal("MD5 function does not exists",e);
146
        }
147
        return null;
148
    }
149
 
150
    /**
151
     * Return a hex representation of the byte array
152
     *
153
     * @param data The data to transform.
154
     * @return A hex representation of the data.
155
     */
156
    public static 1.5.0/docs/api/java/lang/String.html">String toHex(byte[] data)
157
    {
158
        if ((data == null) || (data.length == 0))
159
            return null;
160
 
161
        1.5.0/docs/api/java/lang/StringBuffer.html">StringBuffer result = new 1.5.0/docs/api/java/lang/StringBuffer.html">StringBuffer();
162
 
163
        // This is far from the most efficient way to do things...
164
        for (int i = 0; i < data.length; i++)
165
        {
166
            int low =  (int) (data[i] & 0x0F);
167
            int high = (int) (data[i] & 0xF0);
168
 
169
            result.append(1.5.0/docs/api/java/lang/Integer.html">Integer.toHexString(high).substring(0, 1));
170
            result.append(1.5.0/docs/api/java/lang/Integer.html">Integer.toHexString(low));
171
        }
172
 
173
        return result.toString();
174
    }
175
 
176
    /**
177
     * Generate a unique key.
178
     * The key is a long (length 38 to 40) sequence of digits.
179
     *
180
     * @return A unique key as a long sequence of base-10 digits.
181
     */
182
    public static 1.5.0/docs/api/java/lang/String.html">String generateKey()
183
    {
184
        return new 1.5.0/docs/api/java/math/BigInteger.html">BigInteger(generateBytesKey()).abs().toString();
185
    }
186
 
187
    /**
188
     * Generate a unique key.
189
     * The key is a 32-character long sequence of hex digits.
190
     *
191
     * @return A unique key as a long sequence of hex digits.
192
     */
193
    public static 1.5.0/docs/api/java/lang/String.html">String generateHexKey()
194
    {
195
        return toHex(generateBytesKey());
196
    }
197
 
198
    /**
199
     * Generate a unique key as a byte array.
200
     *
201
     * @return A unique key as a byte array.
202
     */
203
    public static synchronized byte[] generateBytesKey()
204
    {
205
        byte[] junk = new byte[16];
206
 
207
        random.nextBytes(junk);
208
 
209
        1.5.0/docs/api/java/lang/String.html">String input = new 1.5.0/docs/api/java/lang/StringBuffer.html">StringBuffer().append(vmid).append(new java.util.5+0%2Fdocs%2Fapi+Date">Date()).append(junk).append(counter++).toString();
210
 
211
        return getMD5Bytes(input.getBytes());
212
    }
213
 
214
    // The following two methods are taken from the Jakarta IOUtil class.
215
 
216
    /**
217
     * Copy stream-data from source to destination. This method does not
218
     * buffer, flush or close the streams, as to do so would require making
219
     * non-portable assumptions about the streams' origin and further use. If
220
     * you wish to perform a buffered copy, use {@link #bufferedCopy}.
221
     *
222
     * @param input The InputStream to obtain data from.
223
     * @param output The OutputStream to copy data to.
224
     */
225
    public static void copy( final 5+0%2Fdocs%2Fapi+InputStream">InputStream input, final 5+0%2Fdocs%2Fapi+OutputStream">OutputStream output )
226
        throws 1.5.0/docs/api/java/io/IOException.html">IOException
227
    {
228
        final int BUFFER_SIZE = 1024 * 4;
229
        final byte[] buffer = new byte[ BUFFER_SIZE ];
230
 
231
        while( true )
232
        {
233
            final int count = input.read( buffer, 0, BUFFER_SIZE );
234
            if( -1 == count ) break;
235
 
236
            // write out those same bytes
237
            output.write( buffer, 0, count );
238
        }
239
 
240
        //needed to flush cache
241
        //output.flush();
242
    }
243
 
244
 
245
    public static void bufferedCopy( final 5+0%2Fdocs%2Fapi+InputStream">InputStream source, final 5+0%2Fdocs%2Fapi+OutputStream">OutputStream destination )
246
        throws 1.5.0/docs/api/java/io/IOException.html">IOException
247
    {
248
        final 1.5.0/docs/api/java/io/BufferedInputStream.html">BufferedInputStream input = new 1.5.0/docs/api/java/io/BufferedInputStream.html">BufferedInputStream( source );
249
        final 1.5.0/docs/api/java/io/BufferedOutputStream.html">BufferedOutputStream output = new 1.5.0/docs/api/java/io/BufferedOutputStream.html">BufferedOutputStream( destination );
250
        copy( input, output );
251
        output.flush();
252
    }
253
 
254
}