Reputation: 3362
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?
Upvotes: 3
Views: 2087
Reputation: 7779
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;
}
}
Upvotes: 0
Reputation: 1366
You can just use the
@Autowired
private KeyStore keyStore;
if you've configured it correctly in your XML/Java configuration like so
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:crypt="http://springcryptoutils.com/schema/crypt"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://springcryptoutils.com/schema/crypt http://springcryptoutils.com/schema/crypt.xsd">
<crypt:keystore id="keystore"
location="somePath}"
password="somePassword"/>
</beans>
Upvotes: 3