Enquiry regarding Sticky Module's hash functions

ramindeja nginx-forum at nginx.us
Thu Oct 6 20:37:41 UTC 2011


Merci Jérôme, we resolved the solution by writing the following class.
It's not super but does the job:

import java.io.UnsupportedEncodingException; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
 
public class IPEncryptor
{ 
 
    public static String MD5(String ip) 
    throws NoSuchAlgorithmException, UnsupportedEncodingException
    { 
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");

        byte[] md5hash = new byte[32];
        byte[] ipParts = parseIP(ip);
        
        md.update(ipParts, 0, ipParts.length);
        
        md5hash = md.digest();
        return convertToHex(md5hash);
    } 
    
    
    private static String convertToHex(byte[] data)
    { 
        StringBuffer buf = new StringBuffer();
        
        for (int i = 0; i < data.length; i++)
        { 
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do 
            { 
                if ((0 <= halfbyte) && (halfbyte <= 9)) 
                    buf.append((char) ('0' + halfbyte));
                else 
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        } 
        
        return buf.toString();
    } 
    
    // Parses the input
    private static byte[] parseIP(String address)
    {
    	String[] addressParts = address.split(":");
    	
    	String[] ipParts = addressParts[0].split("\\.");
    	int portHiByte = Integer.parseInt(addressParts[1]) / 256;
    	int portLoByte = Integer.parseInt(addressParts[1]) % 256;
    	
    	int i = 0;
    	int j = 0;
    	
    	byte[] ip = new byte[16];
    	ip[i++] = 0;
    	ip[i++] = 2;
    	ip[i++] = (byte)portHiByte;
    	ip[i++] = (byte)portLoByte;
    	
    	for (j = 0; j < ipParts.length; j++, i++)
    	{
    		ip[i] = (byte)Integer.parseInt(ipParts[j]);
    	}

    	// pad the rest with ZEROs
    	for (; i < ip.length; ++i)
    	{
    		ip[i] = 0;
    	}    	
    	
    	return ip;
    }
}

Posted at Nginx Forum: http://forum.nginx.org/read.php?2,207455,216339#msg-216339



More information about the nginx mailing list