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.implementation.serializer.MapNotifySerializer;
19 import org.opendaylight.lispflowmapping.implementation.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) {
47 ByteBuffer mapRegisterBuffer = MapRegisterSerializer.getInstance().serialize(mapRegister);
48 if (mapRegisterBuffer == null) {
52 mapRegisterBuffer.position(MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
53 mapRegisterBuffer.put(tempAuthenticationData);
54 mapRegisterBuffer.position(0);
55 return Arrays.equals(getAuthenticationData(mapRegisterBuffer.array(), key), mapRegister.getAuthenticationData());
58 protected byte[] getAuthenticationData(byte[] data, String key) {
60 byte[] keyBytes = key.getBytes();
61 SecretKeySpec signingKey = new SecretKeySpec(keyBytes, algorithm);
62 Mac mac = Mac.getInstance(algorithm);
65 return mac.doFinal(data);
66 } catch (InvalidKeyException e) {
67 LOG.warn("Invalid password" + key);
68 } catch (NoSuchAlgorithmException e) {
69 LOG.warn("No such MAC algorithm" + algorithm);
74 public int getAuthenticationLength() {
75 return authenticationLength;
78 public String getAlgorithm() {
82 public void setAlgorithm(String algorithm) {
83 this.algorithm = algorithm;
86 public byte[] getAuthenticationData(MapNotify mapNotify, String key) {
87 return getAuthenticationData(MapNotifySerializer.getInstance().serialize(mapNotify).array(), key);