001/*
002 * jPOS Project [http://jpos.org]
003 * Copyright (C) 2000-2026 jPOS Software SRL
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jpos.space;
020
021import java.io.Serializable;
022import java.io.IOException;
023import java.io.ByteArrayOutputStream;
024import java.io.ObjectOutputStream;
025import java.security.MessageDigest;
026import java.util.Arrays;
027
028import org.jpos.iso.ISOUtil;
029
030public class MD5Template implements Template, Serializable  {
031    private static final long serialVersionUID = -1204861759575740048L;
032    byte[] digest;
033    Object key;
034
035    public MD5Template (Object key, Object value) {
036        super ();
037        this.key    = key;
038        this.digest = digest (value);
039    }
040    public MD5Template (Object key, byte[] digest) {
041        super ();
042        this.key = key;
043        this.digest = digest;
044    }
045    public byte[] digest (Object obj) {
046        try {
047            MessageDigest md = MessageDigest.getInstance ("MD5");
048            return md.digest (serialize (obj));
049        } catch (Exception e) {
050            throw new SpaceError (e);
051        }
052    }
053    @Override
054    public boolean equals (Object obj) {
055        return Arrays.equals (digest (obj), digest);
056    }
057    @Override
058    public int hashCode() {
059        assert false : "hashCode not designed";
060        return 42;
061    }
062    public Object getKey () {
063        return key;
064    }
065    public byte[] getDigest () {
066        return digest;
067    }
068    public String getDigestAsString () {
069        return ISOUtil.hexString (digest);
070    }
071    public String toString () {
072        StringBuilder sb = new StringBuilder();
073        sb.append ("key='");
074        sb.append (key);
075        sb.append ("', digest=");
076        sb.append (getDigestAsString ());
077        return sb.toString();        
078    }
079    public static byte[] serialize (Object obj) throws IOException {
080        ByteArrayOutputStream baos;
081        ObjectOutputStream oos;
082
083        baos = new ByteArrayOutputStream();
084        oos = new ObjectOutputStream (baos);
085        oos.writeObject (obj);
086        oos.close();
087
088        return baos.toByteArray();
089    }
090}