JAVA常用函数6

//替换字符
   public static String replace(String inString, String oldPattern, String newPattern)
   {
       
if(inString == null)
           
return null;
       
if(oldPattern == null || newPattern == null)
           
return inString;
       StringBuffer sbuf 
= new StringBuffer();
       
int pos = 0;
       
int index = inString.indexOf(oldPattern);
       
int patLen = oldPattern.length();
       
for(; index >= 0; index = inString.indexOf(oldPattern, pos))
       {
           sbuf.append(inString.substring(pos, index));
           sbuf.append(newPattern);
           pos 
= index + patLen;
       }

       sbuf.append(inString.substring(pos));
       
return sbuf.toString();
   }


/**
 * The Class Md5.
 
*/
public class Md5 {
    
    
/**
     * 32位加密算法.
     * 
     * 
@param plainText the plain text
     * 
     * 
@return the string
     
*/
    
public static String make32(String plainText) {
        
try {
            MessageDigest md 
= MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            
byte b[] = md.digest();
            
int i;
            StringBuffer buf 
= new StringBuffer("");
            
for (int offset = 0; offset < b.length; offset++) {
                i 
= b[offset];
                
if (i < 0)
                    i 
+= 256;
                
if (i < 16)
                    buf.append(
"0");
                buf.append(Integer.toHexString(i));
            }
            
return buf.toString();
        } 
catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        
return null;
    }
    
    
/**
     * 16位加密算法.
     * 
     * 
@param plainText the plain text
     * 
     * 
@return the string
     
*/
    
public static String make16(String plainText) {
        
try {
            MessageDigest md 
= MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            
byte b[] = md.digest();
            
int i;
            StringBuffer buf 
= new StringBuffer("");
            
for (int offset = 0; offset < b.length; offset++) {
                i 
= b[offset];
                
if (i < 0)
                    i 
+= 256;
                
if (i < 16)
                    buf.append(
"0");
                buf.append(Integer.toHexString(i));
            }
            
return buf.toString().substring(824);
        } 
catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        
return null;
    }
    
    
/**
     * The main method.
     * 
     * 
@param agrs the arguments
     
*/
    
public static void main(String agrs[]) {
        System.out.println(Md5.make32(
"1"));// 加密4
        System.out.println(Md5.make16("1"));

    }

}
posted @ 2009-10-09 23:22  angushine  阅读(205)  评论(0编辑  收藏  举报