Skip to content

Commit

Permalink
new example class that generate keystore and truststore files with java
Browse files Browse the repository at this point in the history
  • Loading branch information
astrapisixtynine committed Jul 10, 2024
1 parent 3e637ce commit 239ed49
Show file tree
Hide file tree
Showing 10 changed files with 352 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
Expand Down Expand Up @@ -261,11 +262,59 @@ public static PrivateKey getPrivateKey(final KeyStore keyStore, String alias, ch
public static void store(final KeyStore keyStore, final File keystoreFile,
final String password)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException
{
store(keyStore, keystoreFile, password.toCharArray());
}

/**
* Stores the given {@link KeyStore} object into the given keystore file
*
* @param keyStore
* the keystore
* @param keystoreFile
* the keystore file
* @param password
* the password as char array
* @throws KeyStoreException
* is thrown if there is an error accessing the key store
* @throws NoSuchAlgorithmException
* is thrown if instantiation of the SecretKeyFactory object fails
* @throws CertificateException
* is thrown if there is an error with an certificate
* @throws FileNotFoundException
* is thrown if the keystore file not found
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void store(final KeyStore keyStore, final File keystoreFile,
final char[] password)
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException
{
try (FileOutputStream fos = new FileOutputStream(keystoreFile))
{
keyStore.store(fos, password.toCharArray());
keyStore.store(fos, password);
}
}

/**
* Assigns the given key to the given alias, protecting it with the given password
*
* @param alias
* the alias name
* @param key
* the key to be associated with the alias
* @param password
* the password as char array
* @param chain
* the certificate chain for the corresponding public key
*
* @throws KeyStoreException
* is thrown if there is an error accessing the key store
*/
public static void setKeyEntry(final KeyStore keyStore, final String alias, final Key key,
final char[] password, Certificate[] chain) throws KeyStoreException
{
keyStore.setKeyEntry(alias, key, password, chain);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -108,25 +108,21 @@ public static KeyManager[] resolveKeyManagers(final String keystoreType, final S
* is thrown if instantiation of the SecretKeyFactory object fails
* @throws CertificateException
* is thrown if there is an error with an certificate
* @throws FileNotFoundException
* is thrown if the keystore file not found
* @throws IOException
* Signals that an I/O exception has occurred.
* Signals that an I/O exception has occurred
* @throws KeyStoreException
* is thrown if there is an error accessing the key store
*/
public static TrustManager[] resolveTrustManagers(final String keystoreType,
final String password, final File keystoreFile, final String trustManagerAlgorithm)
throws NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException,
KeyStoreException
throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException
{
final KeyStore keyStore = KeyStoreFactory.loadKeyStore(keystoreFile, keystoreType,
password);
final TrustManagerFactory trustFactory = TrustManagerFactory
.getInstance(trustManagerAlgorithm);
trustFactory.init(keyStore);
final TrustManager[] trustManagers = trustFactory.getTrustManagers();
return trustManagers;
return trustFactory.getTrustManagers();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.astrapi69.mystic.crypt.ssl;

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

public class KeystoreChecker
{

public static boolean isKeystoreFile(String filePath, String password)
{
try (FileInputStream fis = new FileInputStream(filePath))
{
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(fis, password.toCharArray());
return true; // No exception, valid keystore
}
catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException e)
{
return false; // Not a valid keystore
}
}

public static boolean isKeystoreFile(String filePath, String password, String[] types)
{
for (String type : types)
{
if (isKeystoreFile(filePath, type))
return true;// Valid keystore of type 'type'
}
return false; // No types matched
}

public static boolean isKeystoreFile(File file, String password)
{
return isKeystoreFile(file.getAbsolutePath(), password);
}

public static boolean isKeystoreFile(File file, String password, String[] types)
{
return isKeystoreFile(file.getAbsolutePath(), password, types);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.astrapi69.mystic.crypt.key.agreement;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.util.Date;

import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import io.github.astrapi69.crypt.api.algorithm.key.KeyPairGeneratorAlgorithm;
import io.github.astrapi69.crypt.data.factory.CertFactory;
import io.github.astrapi69.crypt.data.factory.KeyPairFactory;
import io.github.astrapi69.crypt.data.factory.KeyStoreFactory;
import io.github.astrapi69.file.create.FileFactory;
import io.github.astrapi69.file.search.PathFinder;
import io.github.astrapi69.mystic.crypt.ssl.KeyStoreExtensions;

public class KeyToolExample
{
public static void main(String[] args) throws Exception
{
Security.addProvider(new BouncyCastleProvider());
KeyPair keyPair;
org.bouncycastle.asn1.x500.X500Name issuer;
BigInteger serial;
Date notBefore;
Date notAfter;
X500Name subject;
String signatureAlgorithm;
X509Certificate cert;
String dn;

dn = "CN=Tyler Durden,OU=light,O=heaven,L=Katerini,ST=macedonia,C=gr";
serial = BigInteger.ONE;
notBefore = Date.from(
LocalDate.of(2024, Month.JANUARY, 1).atStartOfDay(ZoneId.systemDefault()).toInstant());
notAfter = Date.from(
LocalDate.of(2034, Month.JANUARY, 1).atStartOfDay(ZoneId.systemDefault()).toInstant());
subject = new X500Name(dn);
signatureAlgorithm = "SHA256withRSA";
// Generate a key pair
keyPair = KeyPairFactory.newKeyPair(KeyPairGeneratorAlgorithm.RSA, 2048);
issuer = new X500Name(dn);

// Create a self-signed certificate
cert = CertFactory.newX509CertificateV3(keyPair, issuer, serial, notBefore, notAfter,
subject, signatureAlgorithm);

File keystoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
"new-keystore.jks");

// Initialize a KeyStore and store the key pair and certificate
KeyStore keyStore = KeyStoreFactory.newKeyStore(keystoreFile, "JKS", "password");
KeyStoreExtensions.setKeyEntry(keyStore, "serverKey", keyPair.getPrivate(),
"password".toCharArray(), new Certificate[] { cert });
// Save the KeyStore to a file
KeyStoreExtensions.store(keyStore, keystoreFile, "password");

File trustStoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
"new-truststore.jks");

// Initialize a KeyStore for the truststore and store the key pair and certificate
KeyStore trustStore = KeyStoreFactory.newKeyStore(trustStoreFile, "JKS", "password");
KeyStoreExtensions.setKeyEntry(trustStore, "serverKey", keyPair.getPrivate(),
"password".toCharArray(), new Certificate[] { cert });
// Save the KeyStore to a file
KeyStoreExtensions.store(trustStore, trustStoreFile, "password");


}

}
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
/**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.astrapi69.mystic.crypt.key.agreement;

import java.io.File;
Expand Down Expand Up @@ -39,10 +63,14 @@ public class SecureClient
public static void main(String[] args) throws Exception
{

// File keystoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
// "keystore.jks");
// File trustStoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
// "truststore.jks");
File keystoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
"keystore.jks");
"new-keystore.jks");
File trustStoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
"truststore.jks");
"new-truststore.jks");
// Step 2: Load KeyStore and TrustStore
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(keystoreFile), "password".toCharArray());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
/**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.astrapi69.mystic.crypt.key.agreement;

import java.io.File;
Expand Down Expand Up @@ -37,10 +61,15 @@ public class SecureServer
{
public static void main(String[] args) throws Exception
{

// File keystoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
// "keystore.jks");
// File trustStoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
// "truststore.jks");
File keystoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
"keystore.jks");
"new-keystore.jks");
File trustStoreFile = FileFactory.newFile(PathFinder.getSrcTestResourcesDir(),
"truststore.jks");
"new-truststore.jks");
// Step 2: Load KeyStore and TrustStore
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(keystoreFile), "password".toCharArray());
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
/**
* The MIT License
*
* Copyright (C) 2015 Asterios Raptis
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.github.astrapi69.mystic.crypt.key.agreement;

import java.security.InvalidAlgorithmParameterException;
Expand Down
Loading

0 comments on commit 239ed49

Please sign in to comment.