package com.nuvole.hnnx.hnnxPay; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.Key; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author awlwen * @since 2017/11/30 */ public class KeyRegistryImpl implements KeyRegistry { private Map cache = new ConcurrentHashMap<>(); private Logger logger = LoggerFactory.getLogger(this.getClass()); private volatile boolean sync = false; @Override public Key getKey(KeyMetadata metadata) { Assert.notNull(metadata, "[Assertion failed] - metadata is required; it must not be null"); Key key = cache.get(metadata.getId()); if (key == null || sync) { key = getKeyInternal(metadata); cache.put(metadata.getId(), key); } return key; } @Override public Certificate getCertificate(String base64) { Assert.hasText(base64, "[Assertion failed] - base64 must have text; it must not be null, empty, or blank"); BufferedInputStream is = null; try { is = new BufferedInputStream(new ByteArrayInputStream(base64.trim().getBytes())); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate cert = cf.generateCertificate(is); return cert; } catch (CertificateException ex) { throw new RuntimeException(ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { logger.error("close stream error.", ex); } } } } private Key getKeyInternal(KeyMetadata metadata) { KeyProvider provider = new KeyProviderImpl(metadata.getFile(), metadata.getKeyStorePassword()); Key key = provider.getKey(metadata.getKeyAlias(), metadata.getKeyPassword()); Assert.notNull(key, "[Assertion failed] - key must not be null"); return key; } }