随笔-86  评论-33  文章-0  trackbacks-0

 

import  java.security. * ;

public   class  Security {
    
    
/**
     * 字符串加密方法。传入一个字符串,返回经过SHA-1加密后的一个字符串
     * 
@param  strInput
     * 
@return
     
*/
    
public   static  String encryptSHA(String strInput) {
        String strOutput 
=   new  String( "" );
        
try  {
            MessageDigest md 
=  MessageDigest.getInstance( " SHA-1 " );
            md.update(strInput.getBytes());
            
byte  b[]  =  md.digest();
            
for ( int  i = 0 ;i < b.length;i ++ ) {
                
char [] digit  =  {  ' 0 ' , ' 1 ' , ' 2 ' , ' 3 ' , ' 4 ' , ' 5 ' , ' 6 ' , ' 7 ' , ' 8 ' , ' 9 ' , ' A ' , ' B ' , ' C ' , ' D ' , ' E ' , ' F '  };
                
char  [] ob  =   new   char [ 2 ];
                ob[
0 =  digit[(b[i]  >>>   4 &   0X0F ];
                ob[
1 =  digit[b[i]  &   0X0F ];
                strOutput 
+=   new  String(ob);
            }
        }
        
catch (NoSuchAlgorithmException nsae) {
            ex.printStackTrace();
        }        
        
        
return  strOutput;
    }
    
    
/**
     * 字符串加密方法。传入一个字符串,返回经过MD5加密后的一个字符串
     * 
@param  strInput
     * 
@return
     
*/
    
public   static  String encryptMD5(String strInput) {
        StringBuffer buf=null;       
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(strInput.getBytes());
            byte b[] = md.digest();   
             buf = new StringBuffer(b.length * 2);
            for(int i=0;i<b.length;i++) {
                if (((int)b[i] & 0xff) < 0x10) { // & 0xff转换无符号整型
                    buf.append("0");
                }
               // buf.append(Long.toString((int) b[i] & 0xff, 16));//转换16进制,下方法同
               buf.append(Long.toHexString((int)b[i] & 0xff));
            }
        }catch(NoSuchAlgorithmException ex) {
             ex.printStackTrace();
        }   
       return buf.toString();
    }
    
    
public   static   void  main(String args[]) {
        String test 
=   " Derek.G " ;
        System.out.print(encryptSHA(test));
    }
}
posted on 2006-05-17 15:42 Derek.Guo 阅读(481) 评论(1)  编辑  收藏 所属分类: Java

评论:
# re: SHA-1&MD5 2006-10-13 16:00 | Paul
好。多谢!!  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 
MSN:envoydada@hotmail.com QQ:34935442