2 * Copyright (c) 2014 Contextream, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.lispflowmapping.southbound.authentication;
10 import java.nio.ByteBuffer;
11 import java.security.InvalidKeyException;
12 import java.security.NoSuchAlgorithmException;
13 import java.util.Arrays;
14 import javax.crypto.Mac;
15 import javax.crypto.spec.SecretKeySpec;
16 import org.opendaylight.lispflowmapping.interfaces.lisp.ILispAuthentication;
17 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
18 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
22 public class LispMACAuthentication implements ILispAuthentication {
24 protected static final Logger LOG = LoggerFactory.getLogger(LispMACAuthentication.class);
26 protected String algorithm;
27 private byte[] tempAuthenticationData;
28 private int authenticationLength;
30 public LispMACAuthentication(String algorithm) {
31 this.algorithm = algorithm;
33 authenticationLength = Mac.getInstance(algorithm).getMacLength();
34 tempAuthenticationData = new byte[authenticationLength];
35 } catch (NoSuchAlgorithmException e) {
36 LOG.warn("No such MAC algorithm {}", algorithm, e);
41 public boolean validate(ByteBuffer mapRegisterBuffer, byte[] expectedAuthData, String key) {
43 LOG.warn("Authentication failed: mapping authentication password is null!");
46 if (mapRegisterBuffer == null) {
50 mapRegisterBuffer.position(ILispAuthentication.MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
51 mapRegisterBuffer.put(tempAuthenticationData);
52 mapRegisterBuffer.position(0);
53 return Arrays.equals(getAuthenticationData(mapRegisterBuffer.array(), key), expectedAuthData);
56 protected byte[] getAuthenticationData(byte[] data, String key) {
58 byte[] keyBytes = key.getBytes();
59 SecretKeySpec signingKey = new SecretKeySpec(keyBytes, algorithm);
60 Mac mac = Mac.getInstance(algorithm);
63 return mac.doFinal(data);
64 } catch (InvalidKeyException e) {
65 LOG.warn("Invalid password {}", key, e);
66 } catch (NoSuchAlgorithmException e) {
67 LOG.warn("No such MAC algorithm {}", algorithm, e);
72 public int getAuthenticationLength() {
73 return authenticationLength;
76 public String getAlgorithm() {
80 public void setAlgorithm(String algorithm) {
81 this.algorithm = algorithm;
84 public byte[] getAuthenticationData(MapNotify mapNotify, String key) {
85 return getAuthenticationData(MapNotifySerializer.getInstance().serialize(mapNotify).array(), key);