2 * ============LICENSE_START====================================================
4 * ===========================================================================
5 * Copyright (c) 2018 AT&T Intellectual Property. All rights reserved.
6 * ===========================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END====================================================
22 package org.onap.aaf.cadi.oauth;
24 import java.nio.ByteBuffer;
25 import java.security.SecureRandom;
26 import java.util.UUID;
28 import org.onap.aaf.cadi.Hash;
30 public class AAFToken {
31 private static final int CAPACITY = (Long.SIZE*2+Byte.SIZE*3)/8;
32 private static final SecureRandom sr = new SecureRandom();
34 public static final String toToken(UUID uuid) {
35 long lsb = uuid.getLeastSignificantBits();
36 long msb = uuid.getMostSignificantBits();
38 for (int i=0;i<Long.SIZE;i+=8) {
39 sum+=((lsb>>i) & 0xFF);
41 for (int i=0;i<Long.SIZE;i+=8) {
42 sum+=((((msb>>i) & 0xFF))<<0xB);
44 sum+=(sr.nextInt()&0xEFC00000); // this is just to not leave zeros laying around
46 ByteBuffer bb = ByteBuffer.allocate(CAPACITY);
49 bb.put((byte)(sum>>8));
51 bb.put((byte)(sum>>16));
52 return Hash.toHexNo0x(bb.array());
55 public static final UUID fromToken(String token) {
56 byte[] bytes = Hash.fromHexNo0x(token);
60 ByteBuffer bb = ByteBuffer.wrap(bytes);
61 if (bb.capacity()!=CAPACITY ) {
62 return null; // not a CADI Token
65 long msb = bb.getLong();
67 long lsb = bb.getLong();
68 byte b3 = (byte)(0x3F&bb.get());
71 for (int i=0;i<Long.SIZE;i+=8) {
72 sum+=((lsb>>i) & 0xFF);
74 for (int i=0;i<Long.SIZE;i+=8) {
75 sum+=((((msb>>i) & 0xFF))<<0xB);
78 if (b1!=((byte)sum) ||
79 b2!=((byte)(sum>>8)) ||
80 b3!=((byte)((sum>>16)))) {
81 return null; // not a CADI Token
83 return new UUID(msb, lsb);