· 4 years ago · Jan 17, 2021, 07:40 PM
1public class KeyGenerationHandler {
2 private final HashMap<String,GeneratedKey> keyMap = new HashMap<>();
3 private final Object lock = new Object();
4
5 private byte[] createKey() throws java.security.NoSuchAlgorithmException{
6 final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
7 keyGenerator.init(256);
8 final SecretKey key = keyGenerator.generateKey();
9 return key.getEncoded();
10 }
11
12 public byte[] getKey(String userId, String partnerId) throws java.security.NoSuchAlgorithmException {
13
14 String existingSessionId = partnerId + userId;
15
16 synchronized (lock){
17 if(keyMap.containsKey(existingSessionId)){
18 return keyMap.remove(existingSessionId).keyBytes;
19 }else{
20 String newSessionId = userId + partnerId;
21 byte[] newKey = createKey();
22 GeneratedKey generatedKey = new GeneratedKey(newKey);
23 keyMap.put(newSessionId,generatedKey);
24 return newKey;
25 }
26 }
27 }
28}