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.interfaces.lisp.ILispAuthentication;
19 import org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer;
20 import org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer;
21 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapNotify;
22 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MapRegister;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
26 public class LispMACAuthentication implements ILispAuthentication {
28 protected static final Logger LOG = LoggerFactory.getLogger(LispMACAuthentication.class);
30 protected String algorithm;
31 private byte[] tempAuthenticationData;
32 private int authenticationLength;
34 public LispMACAuthentication(String algorithm) {
35 this.algorithm = algorithm;
37 authenticationLength = Mac.getInstance(algorithm).getMacLength();
38 tempAuthenticationData = new byte[authenticationLength];
39 } catch (NoSuchAlgorithmException e) {
40 LOG.warn("No such MAC algorithm" + algorithm);
44 public boolean validate(MapRegister mapRegister, String key) {
46 LOG.warn("The authentication key is null!");
49 ByteBuffer mapRegisterBuffer = MapRegisterSerializer.getInstance().serialize(mapRegister);
50 if (mapRegisterBuffer == null) {
54 mapRegisterBuffer.position(MAP_REGISTER_AND_NOTIFY_AUTHENTICATION_POSITION);
55 mapRegisterBuffer.put(tempAuthenticationData);
56 mapRegisterBuffer.position(0);
57 return Arrays.equals(getAuthenticationData(mapRegisterBuffer.array(), key), mapRegister.getAuthenticationData());
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);
70 } catch (NoSuchAlgorithmException e) {
71 LOG.warn("No such MAC algorithm" + algorithm);
76 public int getAuthenticationLength() {
77 return authenticationLength;
80 public String getAlgorithm() {
84 public void setAlgorithm(String algorithm) {
85 this.algorithm = algorithm;
88 public byte[] getAuthenticationData(MapNotify mapNotify, String key) {
89 return getAuthenticationData(MapNotifySerializer.getInstance().serialize(mapNotify).array(), key);