|
| 1 | +package com.uid2.operator.service; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
| 5 | +import com.amazon.corretto.crypto.provider.AmazonCorrettoCryptoProvider; |
| 6 | + |
| 7 | +import javax.crypto.KeyAgreement; |
| 8 | +import java.security.NoSuchAlgorithmException; |
| 9 | +import java.security.NoSuchProviderException; |
| 10 | +import java.security.Security; |
| 11 | + |
| 12 | +public class CryptoProviderService { |
| 13 | + private static final Logger LOGGER = LoggerFactory.getLogger(CryptoProviderService.class); |
| 14 | + |
| 15 | + // ECDH provider selection: tries ACCP first, falls back to default (SunEC) |
| 16 | + private static final String ECDH_PROVIDER_NAME = initEcdhProvider(); |
| 17 | + |
| 18 | + private static String initEcdhProvider() { |
| 19 | + // Try ACCP (Amazon Corretto Crypto Provider) first |
| 20 | + try { |
| 21 | + // Add ACCP at lowest priority so it doesn't become default for other algorithms |
| 22 | + Security.addProvider(AmazonCorrettoCryptoProvider.INSTANCE); |
| 23 | + |
| 24 | + // Verify it works for ECDH |
| 25 | + KeyAgreement ka = KeyAgreement.getInstance("ECDH", AmazonCorrettoCryptoProvider.PROVIDER_NAME); |
| 26 | + LOGGER.info("ECDH using AmazonCorrettoCryptoProvider (added at lowest priority)"); |
| 27 | + return AmazonCorrettoCryptoProvider.PROVIDER_NAME; |
| 28 | + } catch (Throwable e) { |
| 29 | + // ACCP not available |
| 30 | + LOGGER.info("AmazonCorrettoCryptoProvider is not available: {}", e.getMessage()); |
| 31 | + } |
| 32 | + |
| 33 | + // Fall back to default provider |
| 34 | + LOGGER.info("ECDH using default provider (SunEC)"); |
| 35 | + return null; |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Create ECDH Key Agreement using ACCP if available, fall back to SunEC if not |
| 40 | + * @return ECDH KeyAgreement |
| 41 | + * @throws NoSuchAlgorithmException |
| 42 | + */ |
| 43 | + public static KeyAgreement createKeyAgreement() throws NoSuchAlgorithmException { |
| 44 | + if (ECDH_PROVIDER_NAME != null) { |
| 45 | + try { |
| 46 | + return KeyAgreement.getInstance("ECDH", ECDH_PROVIDER_NAME); |
| 47 | + } catch (NoSuchProviderException e) { |
| 48 | + LOGGER.info("{} is not available: {}", ECDH_PROVIDER_NAME, e.getMessage()); |
| 49 | + } |
| 50 | + } |
| 51 | + return KeyAgreement.getInstance("ECDH"); |
| 52 | + } |
| 53 | +} |
0 commit comments