Spring keystore bean

Viewed 1320

In spring.application I've specified keystore name and password. I'd like to sign some data with Signature.sign() from java security, but to do that I'd need Keystore. Is there a way to get Spring managed keystore bean, or do I have to create my own keystore, even when it's already used by spring?

2 Answers

Spring Boot 2.4.x:

import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class KeyStoreConfiguration {

    private static final String KEY_STORE = "keystore.p12";
    private static final String KEY_STORE_TYPE = "PKCS12";
    private static final String KEY_STORE_PASSWORD = "password";
    
    @Bean
    public KeyStore keyStore() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
        KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
        keyStore.load(new ClassPathResource(KEY_STORE).getInputStream(), KEY_STORE_PASSWORD.toCharArray());
        
        return keyStore;
    }
}
Related