Java tutorial
/* * Copyright (c) 2011, Martijn Brinkers, Djigzo. * * This file is part of Djigzo email encryption. * * Djigzo is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3, 19 November 2007 as published by the Free Software * Foundation. * * Djigzo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public * License along with Djigzo. If not, see <http://www.gnu.org/licenses/> * * Additional permission under GNU AGPL version 3 section 7 * * If you modify this Program, or any covered work, by linking or * combining it with aspectjrt.jar, aspectjweaver.jar, tyrex-1.0.3.jar, * freemarker.jar, dom4j.jar, mx4j-jmx.jar, mx4j-tools.jar, * spice-classman-1.0.jar, spice-loggerstore-0.5.jar, spice-salt-0.8.jar, * spice-xmlpolicy-1.0.jar, saaj-api-1.3.jar, saaj-impl-1.3.jar, * wsdl4j-1.6.1.jar (or modified versions of these libraries), * containing parts covered by the terms of Eclipse Public License, * tyrex license, freemarker license, dom4j license, mx4j license, * Spice Software License, Common Development and Distribution License * (CDDL), Common Public License (CPL) the licensors of this Program grant * you additional permission to convey the resulting work. */ package mitm.application.djigzo.james.matchers; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.util.Collection; import java.util.Collections; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.mail.MessagingException; import mitm.application.djigzo.james.MailAddressUtils; import mitm.common.security.SecurityFactory; import mitm.common.security.SecurityFactoryFactory; import mitm.common.util.HexUtils; import mitm.common.util.MiscStringUtils; import org.apache.commons.lang.StringUtils; import org.apache.mailet.Mail; import org.apache.mailet.MailAddress; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Matcher that matches if a certain header has a value that can be verified with * the provided secret and value using the HMAC algorithm. * * @author Martijn Brinkers * */ public class VerifyHMACHeader extends AbstractContextAwareDjigzoMatcher { private final static Logger logger = LoggerFactory.getLogger(VerifyHMACHeader.class); @Override protected Logger getLogger() { return logger; } /* * The hmac algorithm. */ private final String ALGORITHM = "HmacSHA256"; /* * For getting the HMAC instance */ private SecurityFactory securityFactory; /* * The name of the header to add */ private String header; /* * The value which will be HMAC'd. It is assumed that the value only contains * ASCII characters. */ private String value; /* * The secret key for the HMAC. It is assumed that the secret only contains * ASCII characters. It should therefore be long enough. */ private String secret; /* * The parameters extracted from the comma separated condition */ private String[] parameters; /* * Thrown when the secret is not set */ @SuppressWarnings("serial") private static class MissingSecretException extends Exception { } protected String[] getParameters() { return parameters; } protected byte[] getSecret(Mail mail) throws MessagingException { return MiscStringUtils.toAsciiBytes(secret); } @Override public void init() throws MessagingException { getLogger().info("Initializing matcher: " + getMatcherName()); String condition = getCondition(); if (StringUtils.isBlank(condition)) { throw new MessagingException("Usage: header, value [,secret]"); } parameters = StringUtils.split(condition, ','); if (parameters.length < 3) { throw new MessagingException("Usage: header, value ,secret"); } header = StringUtils.trimToNull(parameters[0]); if (header == null) { throw new MessagingException("header is missing"); } value = StringUtils.trimToNull(parameters[1]); if (value == null) { throw new MessagingException("value is missing"); } secret = StringUtils.trimToNull(parameters[2]); if (secret == null) { throw new MessagingException("secret is missing"); } securityFactory = SecurityFactoryFactory.getSecurityFactory(); } private String calculateHMAC(String value, Mail mail) throws MessagingException, MissingSecretException { try { Mac mac = securityFactory.createMAC(ALGORITHM); byte[] secret = getSecret(mail); if (secret == null) { throw new MissingSecretException(); } SecretKeySpec keySpec = new SecretKeySpec(secret, "raw"); mac.init(keySpec); mac.update(MiscStringUtils.toAsciiBytes(value)); return HexUtils.hexEncode(mac.doFinal()); } catch (NoSuchAlgorithmException e) { throw new MessagingException("Error creating HMAC.", e); } catch (NoSuchProviderException e) { throw new MessagingException("Error creating HMAC.", e); } catch (InvalidKeyException e) { throw new MessagingException("Error creating HMAC.", e); } } @Override public Collection<MailAddress> matchMail(Mail mail) throws MessagingException { Collection<MailAddress> recipients = null; String[] messageHMACs = mail.getMessage().getHeader(header); try { if (messageHMACs != null && messageHMACs.length > 0) { if (messageHMACs.length > 1) { getLogger().warn("Multiple HMAC headers found."); } /* * Take the first one and compare it with the newly calculated HMAC */ String messageHMAC = messageHMACs[0]; if (messageHMAC != null) { if (messageHMAC.equals(calculateHMAC(value, mail))) { /* * The HMAC in the message is equal to the calculated HMAC */ recipients = MailAddressUtils.getRecipients(mail); } else { getLogger().warn("HMAC mismatch."); } } else { getLogger().warn("HMAC in message is null."); } } } catch (MissingSecretException e) { getLogger().warn("Secret is not set."); } if (recipients == null) { recipients = Collections.emptyList(); } return recipients; } public String getSecret() { return secret; } }