001/* 002 * flattr4j - A Java library for Flattr 003 * 004 * Copyright (C) 2012 Richard "Shred" Körber 005 * http://flattr4j.shredzone.org 006 * 007 * This program is free software: you can redistribute it and/or modify 008 * it under the terms of the GNU General Public License / GNU Lesser 009 * General Public License as published by the Free Software Foundation, 010 * either version 3 of the License, or (at your option) any later version. 011 * 012 * Licensed under the Apache License, Version 2.0 (the "License"); 013 * you may not use this file except in compliance with the License. 014 * 015 * This program is distributed in the hope that it will be useful, 016 * but WITHOUT ANY WARRANTY; without even the implied warranty of 017 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 018 */ 019package org.shredzone.flattr4j.web.partner; 020 021import java.io.Serializable; 022import java.io.UnsupportedEncodingException; 023import java.security.MessageDigest; 024import java.security.NoSuchAlgorithmException; 025 026import org.shredzone.flattr4j.model.UserIdentifier; 027 028/** 029 * A {@link UserIdentifier} for identifying a user by email address. The email address is 030 * stored as md5 hash. 031 * 032 * @author Richard "Shred" Körber 033 * @since 2.0 034 */ 035public class EmailUserIdentifier implements UserIdentifier, Serializable { 036 private static final long serialVersionUID = 201195102581924021L; 037 038 private final String identifier; 039 040 /** 041 * Creates a new {@link UserIdentifier} for email. 042 * 043 * @param email 044 * User's email address 045 */ 046 public EmailUserIdentifier(String email) { 047 identifier = "email:" + computeHash(email); 048 } 049 050 @Override 051 public String getUserIdentifier() { 052 return identifier; 053 } 054 055 /** 056 * Converts an email address to a md5 hash. 057 * 058 * @param email 059 * email address to convert 060 * @return md5 hash 061 */ 062 public static String computeHash(String email) { 063 try { 064 MessageDigest md5 = MessageDigest.getInstance("MD5"); 065 md5.reset(); 066 md5.update(email.trim().toLowerCase().getBytes("UTF-8")); 067 068 StringBuilder digest = new StringBuilder(); 069 for (byte b : md5.digest()) { 070 digest.append(String.format("%02x", b & 0xFF)); 071 } 072 073 return digest.toString(); 074 } catch (NoSuchAlgorithmException ex) { 075 // should never happen since MD5 is a standard digester 076 throw new IllegalStateException("no md5 hashing", ex); 077 } catch (UnsupportedEncodingException ex) { 078 // should never happen since UTF-8 is a standard encoding 079 throw new IllegalStateException("no utf-8 encoding", ex); 080 } 081 } 082 083}