Skip to content

Commit 263009f

Browse files
adrianprecubpivovarit
authored andcommitted
BAEL-1202: java keystore (eugenp#4011)
1 parent 86cebe5 commit 263009f

2 files changed

Lines changed: 297 additions & 0 deletions

File tree

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package com.baeldung.keystore;
2+
3+
import java.io.FileInputStream;
4+
import java.io.FileOutputStream;
5+
import java.io.IOException;
6+
import java.nio.file.Files;
7+
import java.nio.file.Paths;
8+
import java.security.KeyStore;
9+
import java.security.KeyStoreException;
10+
import java.security.NoSuchAlgorithmException;
11+
import java.security.PrivateKey;
12+
import java.security.UnrecoverableEntryException;
13+
import java.security.cert.Certificate;
14+
import java.security.cert.CertificateException;
15+
import java.util.Enumeration;
16+
17+
/**
18+
* Created by adi on 3/7/18.
19+
*/
20+
public class JavaKeyStore {
21+
22+
private KeyStore keyStore;
23+
24+
private String keyStoreName;
25+
private String keyStoreType;
26+
private String keyStorePassword;
27+
28+
JavaKeyStore(String keyStoreType, String keyStorePassword, String keyStoreName) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException {
29+
this.keyStoreName = keyStoreName;
30+
this.keyStoreType = keyStoreType;
31+
this.keyStorePassword = keyStorePassword;
32+
}
33+
34+
void createEmptyKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
35+
if(keyStoreType ==null || keyStoreType.isEmpty()){
36+
keyStoreType = KeyStore.getDefaultType();
37+
}
38+
keyStore = KeyStore.getInstance(keyStoreType);
39+
//load
40+
char[] pwdArray = keyStorePassword.toCharArray();
41+
keyStore.load(null, pwdArray);
42+
43+
// Save the keyStore
44+
FileOutputStream fos = new FileOutputStream(keyStoreName);
45+
keyStore.store(fos, pwdArray);
46+
fos.close();
47+
}
48+
49+
void loadKeyStore() throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {
50+
char[] pwdArray = keyStorePassword.toCharArray();
51+
keyStore.load(new FileInputStream(keyStoreName), pwdArray);
52+
}
53+
54+
void setEntry(String alias, KeyStore.SecretKeyEntry secretKeyEntry, KeyStore.ProtectionParameter protectionParameter) throws KeyStoreException {
55+
keyStore.setEntry(alias, secretKeyEntry, protectionParameter);
56+
}
57+
58+
KeyStore.Entry getEntry(String alias) throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException {
59+
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(keyStorePassword.toCharArray());
60+
return keyStore.getEntry(alias, protParam);
61+
}
62+
63+
void setKeyEntry(String alias, PrivateKey privateKey, String keyPassword, Certificate[] certificateChain) throws KeyStoreException {
64+
keyStore.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), certificateChain);
65+
}
66+
67+
void setCertificateEntry(String alias, Certificate certificate) throws KeyStoreException {
68+
keyStore.setCertificateEntry(alias, certificate);
69+
}
70+
71+
Certificate getCertificate(String alias) throws KeyStoreException {
72+
return keyStore.getCertificate(alias);
73+
}
74+
75+
void deleteEntry(String alias) throws KeyStoreException {
76+
keyStore.deleteEntry(alias);
77+
}
78+
79+
void deleteKeyStore() throws KeyStoreException, IOException {
80+
Enumeration<String> aliases = keyStore.aliases();
81+
while (aliases.hasMoreElements()) {
82+
String alias = aliases.nextElement();
83+
keyStore.deleteEntry(alias);
84+
}
85+
keyStore = null;
86+
Files.delete(Paths.get(keyStoreName));
87+
}
88+
89+
KeyStore getKeyStore() {
90+
return this.keyStore;
91+
}
92+
}
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
package com.baeldung.keystore;
2+
3+
import org.junit.After;
4+
import org.junit.Assert;
5+
import org.junit.Before;
6+
import org.junit.Test;
7+
import sun.security.x509.AlgorithmId;
8+
import sun.security.x509.CertificateAlgorithmId;
9+
import sun.security.x509.CertificateSerialNumber;
10+
import sun.security.x509.CertificateValidity;
11+
import sun.security.x509.CertificateVersion;
12+
import sun.security.x509.CertificateX509Key;
13+
import sun.security.x509.X500Name;
14+
import sun.security.x509.X509CertImpl;
15+
import sun.security.x509.X509CertInfo;
16+
17+
import javax.crypto.KeyGenerator;
18+
import javax.crypto.SecretKey;
19+
import java.io.IOException;
20+
import java.math.BigInteger;
21+
import java.security.InvalidKeyException;
22+
import java.security.KeyPair;
23+
import java.security.KeyPairGenerator;
24+
import java.security.KeyStore;
25+
import java.security.NoSuchAlgorithmException;
26+
import java.security.NoSuchProviderException;
27+
import java.security.SecureRandom;
28+
import java.security.SignatureException;
29+
import java.security.cert.CertificateException;
30+
import java.security.cert.X509Certificate;
31+
import java.util.Date;
32+
33+
/**
34+
* Created by adi on 4/14/18.
35+
*/
36+
public class JavaKeyStoreTest {
37+
38+
private JavaKeyStore keyStore;
39+
40+
private static final String KEYSTORE_PWD = "abc123";
41+
private static final String KEYSTORE_NAME = "myKeyStore";
42+
private static final String KEY_STORE_TYPE = "JCEKS";
43+
44+
private static final String MY_SECRET_ENTRY = "mySecretEntry";
45+
private static final String DN_NAME = "CN=test, OU=test, O=test, L=test, ST=test, C=CY";
46+
private static final String SHA1WITHRSA = "SHA1withRSA";
47+
private static final String MY_PRIVATE_KEY = "myPrivateKey";
48+
private static final String MY_CERTIFICATE = "myCertificate";
49+
50+
@Before
51+
public void setUp() throws Exception {
52+
//using java cryptography extension keyStore instead of Keystore.getDefaultType
53+
keyStore = new JavaKeyStore(KEY_STORE_TYPE, KEYSTORE_PWD, KEYSTORE_NAME);
54+
}
55+
56+
@After
57+
public void tearDown() throws Exception {
58+
if (keyStore.getKeyStore() != null) {
59+
keyStore.deleteKeyStore();
60+
}
61+
}
62+
63+
@Test
64+
public void givenNoKeyStore_whenCreateEmptyKeyStore_thenGetKeyStoreNotNull() throws Exception {
65+
keyStore.createEmptyKeyStore();
66+
KeyStore result = keyStore.getKeyStore();
67+
Assert.assertNotNull(result);
68+
}
69+
70+
@Test
71+
public void givenEmptyKeystore_whenLoadKeyStore_thenKeyStoreLoadedAndSizeZero() throws Exception {
72+
keyStore.createEmptyKeyStore();
73+
keyStore.loadKeyStore();
74+
KeyStore result = keyStore.getKeyStore();
75+
Assert.assertNotNull(result);
76+
Assert.assertTrue(result.size() == 0);
77+
}
78+
79+
@Test
80+
public void givenLoadedKeyStore_whenSetEntry_thenSizeIsOneAndGetKeyNotNull() throws Exception {
81+
keyStore.createEmptyKeyStore();
82+
keyStore.loadKeyStore();
83+
84+
KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256");
85+
SecretKey secretKey = keygen.generateKey();
86+
//ideally, password should be different for every key
87+
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray());
88+
KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
89+
keyStore.setEntry(MY_SECRET_ENTRY, secretKeyEntry, protParam);
90+
91+
KeyStore result = keyStore.getKeyStore();
92+
Assert.assertTrue(result.size() == 1);
93+
KeyStore.Entry entry = keyStore.getEntry(MY_SECRET_ENTRY);
94+
Assert.assertTrue(entry != null);
95+
}
96+
97+
@Test
98+
public void givenLoadedKeyStore_whenSetKeyEntry_thenSizeIsOneAndGetEntryNotNull() throws Exception {
99+
keyStore.createEmptyKeyStore();
100+
keyStore.loadKeyStore();
101+
102+
// Generate the key pair
103+
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
104+
keyPairGenerator.initialize(1024);
105+
KeyPair keyPair = keyPairGenerator.generateKeyPair();
106+
107+
// Generate a self signed certificate
108+
X509Certificate certificate = generateSelfSignedCertificate(keyPair);
109+
110+
X509Certificate[] certificateChain = new X509Certificate[1];
111+
certificateChain[0] = certificate;
112+
keyStore.setKeyEntry(MY_PRIVATE_KEY, keyPair.getPrivate(), KEYSTORE_PWD, certificateChain);
113+
114+
KeyStore result = keyStore.getKeyStore();
115+
Assert.assertTrue(result.size() == 1);
116+
KeyStore.Entry entry = keyStore.getEntry(MY_PRIVATE_KEY);
117+
Assert.assertTrue(entry != null);
118+
}
119+
120+
@Test
121+
public void givenLoadedKeyStore_whenSetCertificateEntry_thenSizeIsOneAndGetCertificateEntryNotNull() throws Exception {
122+
keyStore.createEmptyKeyStore();
123+
keyStore.loadKeyStore();
124+
125+
// Generate the key pair
126+
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
127+
keyPairGenerator.initialize(1024);
128+
KeyPair keyPair = keyPairGenerator.generateKeyPair();
129+
130+
// Generate a self signed certificate
131+
X509Certificate certificate = generateSelfSignedCertificate(keyPair);
132+
133+
keyStore.setCertificateEntry(MY_CERTIFICATE, certificate);
134+
135+
KeyStore result = this.keyStore.getKeyStore();
136+
Assert.assertTrue(result.size() == 1);
137+
java.security.cert.Certificate resultCertificate = keyStore.getCertificate(MY_CERTIFICATE);
138+
Assert.assertNotNull(resultCertificate);
139+
}
140+
141+
@Test
142+
public void givenLoadedKeyStoreWithOneEntry_whenDeleteEntry_thenKeyStoreSizeIsZero() throws Exception {
143+
keyStore.createEmptyKeyStore();
144+
keyStore.loadKeyStore();
145+
146+
KeyGenerator keygen = KeyGenerator.getInstance("HmacSHA256");
147+
SecretKey secretKey = keygen.generateKey();
148+
//ideally, password should be different for every key
149+
KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(KEYSTORE_PWD.toCharArray());
150+
KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(secretKey);
151+
keyStore.setEntry(MY_SECRET_ENTRY, secretKeyEntry, protParam);
152+
153+
keyStore.deleteEntry(MY_SECRET_ENTRY);
154+
155+
KeyStore result = this.keyStore.getKeyStore();
156+
Assert.assertTrue(result.size() == 0);
157+
}
158+
159+
@Test
160+
public void givenLoadedKeystore_whenDeleteKeyStore_thenKeyStoreIsNull() throws Exception {
161+
keyStore.createEmptyKeyStore();
162+
keyStore.loadKeyStore();
163+
164+
keyStore.deleteKeyStore();
165+
166+
KeyStore result = this.keyStore.getKeyStore();
167+
Assert.assertTrue(result == null);
168+
}
169+
170+
private X509Certificate generateSelfSignedCertificate(KeyPair keyPair) throws CertificateException, IOException, NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException, SignatureException {
171+
X509CertInfo certInfo = new X509CertInfo();
172+
// Serial number and version
173+
certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(new BigInteger(64, new SecureRandom())));
174+
certInfo.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
175+
176+
// Subject & Issuer
177+
X500Name owner = new X500Name(DN_NAME);
178+
certInfo.set(X509CertInfo.SUBJECT, owner);
179+
certInfo.set(X509CertInfo.ISSUER, owner);
180+
181+
// Key and algorithm
182+
certInfo.set(X509CertInfo.KEY, new CertificateX509Key(keyPair.getPublic()));
183+
AlgorithmId algorithm = new AlgorithmId(AlgorithmId.sha1WithRSAEncryption_oid);
184+
certInfo.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algorithm));
185+
186+
// Validity
187+
Date validFrom = new Date();
188+
Date validTo = new Date(validFrom.getTime() + 50L * 365L * 24L * 60L * 60L * 1000L); //50 years
189+
CertificateValidity validity = new CertificateValidity(validFrom, validTo);
190+
certInfo.set(X509CertInfo.VALIDITY, validity);
191+
192+
// Create certificate and sign it
193+
X509CertImpl cert = new X509CertImpl(certInfo);
194+
cert.sign(keyPair.getPrivate(), SHA1WITHRSA);
195+
196+
// Since the SHA1withRSA provider may have a different algorithm ID to what we think it should be,
197+
// we need to reset the algorithm ID, and resign the certificate
198+
AlgorithmId actualAlgorithm = (AlgorithmId) cert.get(X509CertImpl.SIG_ALG);
199+
certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, actualAlgorithm);
200+
X509CertImpl newCert = new X509CertImpl(certInfo);
201+
newCert.sign(keyPair.getPrivate(), SHA1WITHRSA);
202+
203+
return newCert;
204+
}
205+
}

0 commit comments

Comments
 (0)