View Javadoc
1   package civitas.crypto;
2   
3   import java.security.NoSuchAlgorithmException;
4   import java.security.NoSuchProviderException;
5   import java.util.HashMap;
6   import java.util.Map;
7   
8   import javax.crypto.KeyGenerator;
9   
10  import org.springframework.stereotype.Service;
11  
12  @Service
13  public class GetSharedKeyGeneratorService {
14  	private final Map<String, KeyGenerator> sharedKeyGenerators = new HashMap<>();
15  
16  	public KeyGenerator apply(final int keyLength) {
17  		String genKey = String.valueOf(keyLength);
18  		KeyGenerator g = sharedKeyGenerators.get(genKey);
19  		if (g != null) {
20  			return g;
21  		}
22  		try {
23  			g = KeyGenerator.getInstance(Constants.SHARED_KEY_ALG, Constants.SHARED_KEY_PROVIDER);
24  		} catch (NoSuchAlgorithmException | NoSuchProviderException impossible) {
25  			throw new CryptoError(impossible);
26  		}
27  
28  		g.init(keyLength);
29  		sharedKeyGenerators.put(genKey, g);
30  		return g;
31  	}
32  }