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.lisp.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.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
19 public class LispMACAuthentication implements ILispAuthentication {
21 protected static final Logger LOG = LoggerFactory.getLogger(LispMACAuthentication.class);
23 protected String algorithm;
24 private byte[] tempAuthenticationData;
25 private int authenticationLength;
27 public LispMACAuthentication(String algorithm) {
28 this.algorithm = algorithm;
30 authenticationLength = Mac.getInstance(algorithm).getMacLength();
31 tempAuthenticationData = new byte[authenticationLength];
32 } catch (NoSuchAlgorithmException e) {
33 LOG.warn("No such MAC algorithm {}", algorithm, e);
38 public boolean validate(ByteBuffer mapRegisterBuffer, byte[] expectedAuthData, String key) {
40 LOG.warn("Authentication failed: mapping authentication password is null!");
43 if (mapRegisterBuffer == null) {
47 mapRegisterBuffer.position(ILispAuthentication.MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
48 mapRegisterBuffer.put(tempAuthenticationData);
49 mapRegisterBuffer.position(0);
50 byte[] mapRegisterArray;
51 if (mapRegisterBuffer.hasArray()) {
52 mapRegisterArray = mapRegisterBuffer.array();
54 mapRegisterArray = new byte[mapRegisterBuffer.remaining()];
55 mapRegisterBuffer.get(mapRegisterArray);
57 return Arrays.equals(getAuthenticationData(mapRegisterArray, key), expectedAuthData);
60 protected byte[] getAuthenticationData(byte[] data, String key) {
62 byte[] keyBytes = key.getBytes();
63 SecretKeySpec signingKey = new SecretKeySpec(keyBytes, algorithm);
64 Mac mac = Mac.getInstance(algorithm);
67 return mac.doFinal(data);
68 } catch (InvalidKeyException e) {
69 LOG.warn("Invalid password {}", key, e);
70 } catch (NoSuchAlgorithmException e) {
71 LOG.warn("No such MAC algorithm {}", algorithm, e);
76 public byte[] getAuthenticationData(final ByteBuffer buffer, final String key) {
78 if (buffer.hasArray()) {
79 bufferAsArray = buffer.array();
81 bufferAsArray = new byte[buffer.limit()];
84 return getAuthenticationData(bufferAsArray, key);
87 public int getAuthenticationLength() {
88 return authenticationLength;
91 public String getAlgorithm() {
95 public void setAlgorithm(String algorithm) {
96 this.algorithm = algorithm;