Open Kilda Java Documentation
DataSignature.java
Go to the documentation of this file.
1 /* Copyright 2018 Telstra Open Source
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 package org.openkilda.floodlight.utils;
17 
20 
21 import com.auth0.jwt.JWT;
22 import com.auth0.jwt.JWTCreator;
23 import com.auth0.jwt.JWTVerifier;
24 import com.auth0.jwt.algorithms.Algorithm;
25 import com.auth0.jwt.exceptions.JWTVerificationException;
26 import com.auth0.jwt.interfaces.DecodedJWT;
27 
28 import java.io.UnsupportedEncodingException;
29 import java.nio.charset.Charset;
30 
31 public class DataSignature {
32  private final Algorithm signAlgorithm;
33  private final JWTVerifier signVerification;
34 
36  try {
37  signAlgorithm = Algorithm.HMAC256(secret);
38  signVerification = JWT.require(signAlgorithm).build();
39  } catch (UnsupportedEncodingException e) {
40  throw new InvalidSignatureConfigurationException("Can't initialize sing/verify objects", e);
41  }
42  }
43 
44  public byte[] sign(JWTCreator.Builder token) {
45  String payload = token.sign(signAlgorithm);
46  return payload.getBytes(Charset.forName("UTF-8"));
47  }
48 
52  public DecodedJWT verify(byte[] payload) throws CorruptedNetworkDataException {
53  String payloadStr = new String(payload, Charset.forName("UTF-8"));
54  DecodedJWT token;
55  try {
56  token = signVerification.verify(payloadStr);
57  } catch (JWTVerificationException e) {
58  throw new CorruptedNetworkDataException(String.format("Bad signature: %s", e));
59  }
60 
61  return token;
62  }
63 }
byte [] sign(JWTCreator.Builder token)