Bagi temen2 programmer Java yang ingin menggunakan enkripsi SHA-1, namun tidak tau bagaimana caranya, saya akan membuat metode sendiri untuk membuat enkripsi tersebut.
01 | package com.wordpress.aliongz.utility; |
03 | import java.io.UnsupportedEncodingException; |
04 | import java.security.MessageDigest; |
05 | import java.security.NoSuchAlgorithmException; |
07 | public class SHA1Utility { |
09 | private static String convertToHex( byte [] data) { |
10 | StringBuffer buf = new StringBuffer(); |
11 | for ( int i = 0 ; i < data.length; i++) { |
12 | int halfbyte = (data[i] >>> 4 ) & 0x0F ; |
15 | if (( 0 <= halfbyte) && (halfbyte <= 9 )) { |
16 | buf.append(( char ) ( '0' + halfbyte)); |
18 | buf.append(( char ) ( 'a' + (halfbyte - 10 ))); |
20 | halfbyte = data[i] & 0x0F ; |
21 | } while (two_halfs++ < 1 ); |
23 | return buf.toString(); |
26 | public static String getSHA1(String text) |
27 | throws NoSuchAlgorithmException, UnsupportedEncodingException { |
29 | md = MessageDigest.getInstance( "SHA-1" ); |
30 | byte [] sha1hash = new byte [ 40 ]; |
31 | md.update(text.getBytes( "iso-8859-1" ), 0 , text.length()); |
32 | sha1hash = md.digest(); |
33 | return convertToHex(sha1hash); |
Berikut salah satu contoh dalam penggunaannya.
01 | package com.wordpress.aliongz.main; |
03 | import com.wordpress.aliongz.utility.SHA1Utility; |
06 | public static void main(String[] args) { |
08 | System.out.println( "SHA-1 dari " + s + " adalah " + SHA1Utility.getSHA1(s)); |
0 komentar:
Posting Komentar