xuekang
2024-05-11 bac0878349a1db23e7b420ea164e22fb9db73a99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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<String, Key> 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;
    }
}