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.implementation.authentication;
10 import java.nio.ByteBuffer;
11 import java.security.InvalidKeyException;
12 import java.security.NoSuchAlgorithmException;
13 import java.util.Arrays;
15 import javax.crypto.Mac;
16 import javax.crypto.spec.SecretKeySpec;
18 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
19 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
20 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapNotify;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.control.plane.rev150314.MapRegister;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
25 public class LispMACAuthentication implements ILispAuthentication {
27 protected static final Logger LOG = LoggerFactory.getLogger(LispMACAuthentication.class);
29 protected String algorithm;
30 private byte[] tempAuthenticationData;
31 private int authenticationLength;
33 public LispMACAuthentication(String algorithm) {
34 this.algorithm = algorithm;
36 authenticationLength = Mac.getInstance(algorithm).getMacLength();
37 tempAuthenticationData = new byte[authenticationLength];
38 } catch (NoSuchAlgorithmException e) {
39 LOG.warn("No such MAC algorithm" + algorithm);
43 public boolean validate(MapRegister mapRegister, String key) {
45 LOG.warn("The authentication key is null!");
48 ByteBuffer mapRegisterBuffer = MapRegisterSerializer.getInstance().serialize(mapRegister);
49 if (mapRegisterBuffer == null) {
53 mapRegisterBuffer.position(MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
54 mapRegisterBuffer.put(tempAuthenticationData);
55 mapRegisterBuffer.position(0);
56 return Arrays.equals(getAuthenticationData(mapRegisterBuffer.array(), key), mapRegister.getAuthenticationData());
59 protected byte[] getAuthenticationData(byte[] data, String key) {
61 byte[] keyBytes = key.getBytes();
62 SecretKeySpec signingKey = new SecretKeySpec(keyBytes, algorithm);
63 Mac mac = Mac.getInstance(algorithm);
66 return mac.doFinal(data);
67 } catch (InvalidKeyException e) {
68 LOG.warn("Invalid password" + key);
69 } catch (NoSuchAlgorithmException e) {
70 LOG.warn("No such MAC algorithm" + algorithm);
75 public int getAuthenticationLength() {
76 return authenticationLength;
79 public String getAlgorithm() {
83 public void setAlgorithm(String algorithm) {
84 this.algorithm = algorithm;
87 public byte[] getAuthenticationData(MapNotify mapNotify, String key) {
88 return getAuthenticationData(MapNotifySerializer.getInstance().serialize(mapNotify).array(), key);