Resource fix

Resource fix
LOG4J2 PatternLayout
debug change
This commit is contained in:
shimingxy 2020-04-11 16:36:51 +08:00
parent c80205883f
commit 166b8362d3
8 changed files with 869 additions and 878 deletions

View File

@ -1,3 +1,4 @@
package org.maxkey.crypto.jose.keystore;
/******************************************************************************* /*******************************************************************************
* Copyright 2014 The MITRE Corporation * Copyright 2014 The MITRE Corporation
* and the MIT Kerberos and Internet Trust Consortium * and the MIT Kerberos and Internet Trust Consortium
@ -14,29 +15,26 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
******************************************************************************/ ******************************************************************************/
/**
*
*/
package org.maxkey.crypto.jose.keystore;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.List;
import org.springframework.core.io.Resource;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.io.CharStreams; import com.google.common.io.CharStreams;
import com.nimbusds.jose.jwk.JWK; import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet; import com.nimbusds.jose.jwk.JWKSet;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
/** /**
* .
* @author jricher * @author jricher
* *
*/ */
public class JWKSetKeyStore { public class JWKSetKeyStore {
private static final Logger _logger = LoggerFactory.getLogger(JWKSetKeyStore.class);
private JWKSet jwkSet; private JWKSet jwkSet;
private Resource location; private Resource location;
@ -58,22 +56,26 @@ public class JWKSetKeyStore {
if (location.exists() && location.isReadable()) { if (location.exists() && location.isReadable()) {
try { try {
_logger.debug("JWK location " + location.getURL());
// read in the file from disk // read in the file from disk
String s = CharStreams.toString(new InputStreamReader(location.getInputStream(), Charsets.UTF_8)); String s = CharStreams
.toString(new InputStreamReader(location.getInputStream(), Charsets.UTF_8));
// parse it into a jwkSet object // parse it into a jwkSet object
jwkSet = JWKSet.parse(s); jwkSet = JWKSet.parse(s);
} catch (IOException e) { } catch (IOException e) {
throw new IllegalArgumentException("Key Set resource could not be read: " + location); throw new IllegalArgumentException("Key Set resource could not be read: " + location);
} catch (ParseException e) { } catch (ParseException e) {
throw new IllegalArgumentException("Key Set resource could not be parsed: " + location); } throw new IllegalArgumentException("Key Set resource could not be parsed: " + location);
}
} else { } else {
throw new IllegalArgumentException("Key Set resource could not be read: " + location); throw new IllegalArgumentException("Key Set resource could not be read: " + location);
} }
} else { } else {
throw new IllegalArgumentException("Key store must be initialized with at least one of a jwkSet or a location."); throw new IllegalArgumentException(
"Key store must be initialized with at least one of a jwkSet or a location.");
} }
} }
} }
@ -105,11 +107,13 @@ public class JWKSetKeyStore {
*/ */
public void setLocation(Resource location) { public void setLocation(Resource location) {
this.location = location; this.location = location;
initializeJwkSet(); initializeJwkSet();
} }
/** /**
* Get the list of keys in this keystore. This is a passthrough to the underlying JWK Set * Get the list of keys in this keystore. This is a passthrough to the
* underlying JWK Set
*/ */
public List<JWK> getKeys() { public List<JWK> getKeys() {
if (jwkSet == null) { if (jwkSet == null) {
@ -118,6 +122,4 @@ public class JWKSetKeyStore {
return jwkSet.getKeys(); return jwkSet.getKeys();
} }
} }

View File

@ -1,33 +1,34 @@
/** /**
* *
*/ */
package org.maxkey.crypto.keystore; package org.maxkey.crypto.keystore;
import java.security.KeyStore; import java.security.KeyStore;
import java.util.Enumeration; import java.util.Enumeration;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils; import org.springframework.util.ResourceUtils;
/** /**
* .
* @author Crystal.Sea * @author Crystal.Sea
* *
*/ */
public class KeyStoreLoader implements InitializingBean{ public class KeyStoreLoader implements InitializingBean {
private final static Logger _logger = LoggerFactory.getLogger(KeyStoreLoader.class); private static final Logger _logger = LoggerFactory.getLogger(KeyStoreLoader.class);
private KeyStore keyStore; private KeyStore keyStore;
private String entityName; private String entityName;
private String keystoreFile; private Resource keystoreFile;
private String keystorePassword; private String keystorePassword;
private String keystoreType = "JKS"; private String keystoreType = "JKS";
/** /**
* *
*/ */
@ -44,12 +45,10 @@ public class KeyStoreLoader implements InitializingBean{
/** /**
* @param keystoreFile the keystoreFile to set * @param keystoreFile the keystoreFile to set
*/ */
public void setKeystoreFile(String keystoreFile) { public void setKeystoreFile(Resource keystoreFile) {
this.keystoreFile = keystoreFile; this.keystoreFile = keystoreFile;
} }
/** /**
* @param keystorePassword the keystorePassword to set * @param keystorePassword the keystorePassword to set
*/ */
@ -59,6 +58,7 @@ public class KeyStoreLoader implements InitializingBean{
/** /**
* <EFBFBD><EFBFBD>ȡKeyStore<EFBFBD><EFBFBD><EFBFBD><EFBFBD> * <EFBFBD><EFBFBD>ȡKeyStore<EFBFBD><EFBFBD><EFBFBD><EFBFBD>
*
* @return * @return
*/ */
public String getKeystorePassword() { public String getKeystorePassword() {
@ -67,20 +67,21 @@ public class KeyStoreLoader implements InitializingBean{
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
_logger.debug("Load KeyStore from file "+ResourceUtils.getFile(keystoreFile).getPath()); _logger.debug("Load KeyStore from file " + keystoreFile.getURL());
keyStore =KeyStoreUtil.loadKeyStore(ResourceUtils.getFile(keystoreFile), keystorePassword.toCharArray(), KeyStoreType.JKS); keyStore = KeyStoreUtil.loadKeyStore(
keystoreFile, keystorePassword.toCharArray(),
KeyStoreType.JKS);
_logger.debug("Load KeyStore success . "); _logger.debug("Load KeyStore success . ");
Enumeration<String> temp = keyStore.aliases(); Enumeration<String> temp = keyStore.aliases();
int i=0; int i = 0;
while(temp.hasMoreElements()){ while (temp.hasMoreElements()) {
_logger.debug("KeyStore alias name "+(i++)+" : "+temp.nextElement()); _logger.debug("KeyStore alias name " + (i++) + " : " + temp.nextElement());
} }
} }
/** /**
* .
* @return the entityName * @return the entityName
*/ */
public String getEntityName() { public String getEntityName() {
@ -101,5 +102,4 @@ public class KeyStoreLoader implements InitializingBean{
return keystoreType; return keystoreType;
} }
} }

View File

@ -4,7 +4,6 @@
package org.maxkey.crypto.keystore; package org.maxkey.crypto.keystore;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.File;
@ -12,6 +11,7 @@ import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.security.Key; import java.security.Key;
import java.security.KeyPair; import java.security.KeyPair;
@ -39,25 +39,24 @@ import org.maxkey.crypto.Base64Utils;
import org.maxkey.crypto.cert.CryptoException; import org.maxkey.crypto.cert.CryptoException;
import org.maxkey.crypto.cert.X509CertUtils; import org.maxkey.crypto.cert.X509CertUtils;
import org.maxkey.crypto.cert.X509V3CertGen; import org.maxkey.crypto.cert.X509V3CertGen;
import org.springframework.core.io.Resource;
/** /**
* Provides utility methods for loading/saving keystores. The Bouncy Castle provider must be registered before * Provides utility methods for loading/saving keystores. The Bouncy Castle
* using this class to create or load BKS or UBER type keystores. * provider must be registered before using this class to create or load BKS or
* UBER type keystores.
*/ */
public final class KeyStoreUtil{ public final class KeyStoreUtil {
public static final String X509 = "X.509"; public static final String X509 = "X.509";
/** Map of available keystore types */ /** Map of available keystore types */
private static final HashMap<KeyStoreType, Boolean> AVAILABLE_TYPES =new HashMap<KeyStoreType, Boolean>(); private static final HashMap<KeyStoreType, Boolean> AVAILABLE_TYPES = new HashMap<KeyStoreType, Boolean>();
/** /**
* Private to prevent construction. * Private to prevent construction.
*/ */
private KeyStoreUtil() private KeyStoreUtil() {
{
// Nothing to do // Nothing to do
} }
@ -68,33 +67,27 @@ public final class KeyStoreUtil{
* @return The keystore * @return The keystore
* @throws KeyStoreException No implementation found * @throws KeyStoreException No implementation found
*/ */
private static KeyStore getKeyStoreImpl(KeyStoreType keyStoreType)throws KeyStoreException private static KeyStore getKeyStoreImpl(KeyStoreType keyStoreType) throws KeyStoreException {
{
KeyStore keyStore = null; KeyStore keyStore = null;
if (keyStoreType == KeyStoreType.PKCS12) if (keyStoreType == KeyStoreType.PKCS12) {
{ // Prefer BC for PKCS #12 for now; the BC and SunJSSE 1.5+ implementations are
// Prefer BC for PKCS #12 for now; the BC and SunJSSE 1.5+ implementations are incompatible in how // incompatible in how
// they handle empty/missing passwords; BC works consistently with char[0] on load and store (does // they handle empty/missing passwords; BC works consistently with char[0] on
// not accept nulls), SunJSSE throws division by zero with char[0] on load and store, works with // load and store (does
// not accept nulls), SunJSSE throws division by zero with char[0] on load and
// store, works with
// null on load, does not work with null on store. // null on load, does not work with null on store.
// Checked with BC 1.{29,40}, SunJSSE 1.5.0_0{3,4,14}, 1.6.0 (OpenJDK) // Checked with BC 1.{29,40}, SunJSSE 1.5.0_0{3,4,14}, 1.6.0 (OpenJDK)
try try {
{
keyStore = KeyStore.getInstance(keyStoreType.name(), "BC"); keyStore = KeyStore.getInstance(keyStoreType.name(), "BC");
} } catch (NoSuchProviderException ex) {
catch (NoSuchProviderException ex)
{
ex.printStackTrace(); ex.printStackTrace();
} }
} }
if (keyStore == null) if (keyStore == null) {
{ try {
try
{
keyStore = KeyStore.getInstance(keyStoreType.name()); keyStore = KeyStore.getInstance(keyStoreType.name());
} } catch (KeyStoreException e) {
catch (KeyStoreException e)
{
AVAILABLE_TYPES.put(keyStoreType, Boolean.FALSE); AVAILABLE_TYPES.put(keyStoreType, Boolean.FALSE);
throw e; throw e;
} }
@ -111,105 +104,82 @@ public final class KeyStoreUtil{
* @throws CryptoException Problem encountered creating the keystore * @throws CryptoException Problem encountered creating the keystore
* @throws IOException An I/O error occurred * @throws IOException An I/O error occurred
*/ */
public static KeyStore createKeyStore(KeyStoreType keyStoreType) public static KeyStore createKeyStore(KeyStoreType keyStoreType) throws CryptoException, IOException {
throws CryptoException, IOException
{
KeyStore keyStore = null; KeyStore keyStore = null;
try try {
{
keyStore = getKeyStoreImpl(keyStoreType); keyStore = getKeyStoreImpl(keyStoreType);
keyStore.load(null, null); keyStore.load(null, null);
} } catch (GeneralSecurityException ex) {
catch (GeneralSecurityException ex) throw new CryptoException("Could not create " + keyStoreType + " keystore.", ex);
{
throw new CryptoException(
"Could not create "+ keyStoreType+" keystore.", ex);
} }
return keyStore; return keyStore;
} }
/** /**
* Load keystore entries from PEM reader into a new PKCS #12 keystore. The reader is not closed. * Load keystore entries from PEM reader into a new PKCS #12 keystore. The
* reader is not closed.
* *
* @param reader reader to read entries from * @param reader reader to read entries from
* @return new PKCS #12 keystore containing read entries, possibly empty * @return new PKCS #12 keystore containing read entries, possibly empty
* @throws CryptoException Problem encountered creating the keystore * @throws CryptoException Problem encountered creating the keystore
* @throws IOException An I/O error occurred * @throws IOException An I/O error occurred
*/ */
public static KeyStore loadEntries(PEMParser reader,String password)throws CryptoException, IOException public static KeyStore loadEntries(PEMParser reader, String password) throws CryptoException, IOException {
{
LinkedHashSet<KeyPair> keyPairs = new LinkedHashSet<KeyPair>(); LinkedHashSet<KeyPair> keyPairs = new LinkedHashSet<KeyPair>();
LinkedHashSet<Certificate> certs = new LinkedHashSet<Certificate>(); LinkedHashSet<Certificate> certs = new LinkedHashSet<Certificate>();
KeyStore keyStore = createKeyStore(KeyStoreType.PKCS12); KeyStore keyStore = createKeyStore(KeyStoreType.PKCS12);
Object obj; Object obj;
while ((obj = reader.readObject()) != null) while ((obj = reader.readObject()) != null) {
{ if (obj instanceof KeyPair) {
if (obj instanceof KeyPair)
{
keyPairs.add((KeyPair) obj); keyPairs.add((KeyPair) obj);
} } else if (obj instanceof Certificate) {
else if (obj instanceof Certificate)
{
certs.add((Certificate) obj); certs.add((Certificate) obj);
} }
} }
// Add key pairs // Add key pairs
for (KeyPair keyPair : keyPairs) for (KeyPair keyPair : keyPairs) {
{
Certificate keyPairCert = null; Certificate keyPairCert = null;
for (Iterator<Certificate> it = certs.iterator(); it.hasNext();) for (Iterator<Certificate> it = certs.iterator(); it.hasNext();) {
{
Certificate cert = it.next(); Certificate cert = it.next();
if (cert.getPublicKey().equals(keyPair.getPublic())) if (cert.getPublicKey().equals(keyPair.getPublic())) {
{
keyPairCert = cert; keyPairCert = cert;
it.remove(); it.remove();
break; break;
} }
} }
if (keyPairCert != null) if (keyPairCert != null) {
{
String alias = "keypair"; String alias = "keypair";
if (keyPairCert instanceof X509Certificate) if (keyPairCert instanceof X509Certificate) {
{
alias = X509CertUtils.getCertificateAlias((X509Certificate) keyPairCert); alias = X509CertUtils.getCertificateAlias((X509Certificate) keyPairCert);
} }
KeyStore.PrivateKeyEntry entry = KeyStore.PrivateKeyEntry entry = new KeyStore.PrivateKeyEntry(keyPair.getPrivate(),
new KeyStore.PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] { keyPairCert }); new Certificate[] { keyPairCert });
KeyStore.PasswordProtection prot = new KeyStore.PasswordProtection(password.toCharArray()); KeyStore.PasswordProtection prot = new KeyStore.PasswordProtection(password.toCharArray());
try try {
{
alias = findUnusedAlias(keyStore, alias); alias = findUnusedAlias(keyStore, alias);
keyStore.setEntry(alias, entry, prot); keyStore.setEntry(alias, entry, prot);
} } catch (KeyStoreException e) {
catch (KeyStoreException e)
{
throw new CryptoException(e); throw new CryptoException(e);
} }
} }
} }
// Add remaining certificates as trusted certificate entries // Add remaining certificates as trusted certificate entries
for (Certificate cert : certs) for (Certificate cert : certs) {
{
String alias = "certificate"; String alias = "certificate";
if (cert instanceof X509Certificate) if (cert instanceof X509Certificate) {
{
alias = X509CertUtils.getCertificateAlias((X509Certificate) cert); alias = X509CertUtils.getCertificateAlias((X509Certificate) cert);
} }
KeyStore.TrustedCertificateEntry entry = new KeyStore.TrustedCertificateEntry(cert); KeyStore.TrustedCertificateEntry entry = new KeyStore.TrustedCertificateEntry(cert);
try try {
{
keyStore.setEntry(alias, entry, null); keyStore.setEntry(alias, entry, null);
} } catch (KeyStoreException e) {
catch (KeyStoreException e)
{
throw new CryptoException(e); throw new CryptoException(e);
} }
} }
@ -223,20 +193,15 @@ public final class KeyStoreUtil{
* @param keyStoreType the keystore type * @param keyStoreType the keystore type
* @return true if the keystore type is available, false otherwise * @return true if the keystore type is available, false otherwise
*/ */
public static boolean isAvailable(KeyStoreType keyStoreType) public static boolean isAvailable(KeyStoreType keyStoreType) {
{
Boolean available; Boolean available;
if ((available = AVAILABLE_TYPES.get(keyStoreType)) != null) if ((available = AVAILABLE_TYPES.get(keyStoreType)) != null) {
{
return available; return available;
} }
try try {
{
// Populate AVAILABLE_TYPES // Populate AVAILABLE_TYPES
getKeyStoreImpl(keyStoreType); getKeyStoreImpl(keyStoreType);
} } catch (KeyStoreException e) {
catch (KeyStoreException e)
{
// Ignore // Ignore
e.printStackTrace(); e.printStackTrace();
} }
@ -248,15 +213,12 @@ public final class KeyStoreUtil{
* *
* @return available keystore types * @return available keystore types
*/ */
public static KeyStoreType[] getAvailableTypes() public static KeyStoreType[] getAvailableTypes() {
{
// TODO: populate only once // TODO: populate only once
KeyStoreType[] known = KeyStoreType.values(); KeyStoreType[] known = KeyStoreType.values();
ArrayList<KeyStoreType> available = new ArrayList<KeyStoreType>(); ArrayList<KeyStoreType> available = new ArrayList<KeyStoreType>();
for (KeyStoreType type : known) for (KeyStoreType type : known) {
{ if (isAvailable(type)) {
if (isAvailable(type))
{
available.add(type); available.add(type);
} }
} }
@ -271,47 +233,33 @@ public final class KeyStoreUtil{
* @param cKeyStorePassword Password of the keystore * @param cKeyStorePassword Password of the keystore
* @return The keystore * @return The keystore
* @throws CryptoException Problem encountered loading the keystore * @throws CryptoException Problem encountered loading the keystore
* @throws FileNotFoundException If the keystore file does not exist, is a directory rather than a regular * @throws FileNotFoundException If the keystore file does not exist, is a
* file, or for some other reason cannot be opened for reading * directory rather than a regular file, or for
* some other reason cannot be opened for reading
*/ */
public static KeyStore loadKeyStore(File fKeyStore, char[] cKeyStorePassword, KeyStoreType keyStoreType) public static KeyStore loadKeyStore(
throws CryptoException, FileNotFoundException File fKeyStore, char[] cKeyStorePassword, KeyStoreType keyStoreType)
{ throws CryptoException, FileNotFoundException {
KeyStore keyStore = null; KeyStore keyStore = null;
try try {
{
keyStore = getKeyStoreImpl(keyStoreType); keyStore = getKeyStoreImpl(keyStoreType);
} } catch (KeyStoreException ex) {
catch (KeyStoreException ex) throw new CryptoException("Could not create " + keyStoreType + " keystore.", ex);
{
throw new CryptoException("Could not create "+keyStoreType+" keystore.", ex);
} }
FileInputStream fis = new FileInputStream(fKeyStore); FileInputStream fis = new FileInputStream(fKeyStore);
try try {
{
keyStore.load(fis, cKeyStorePassword); keyStore.load(fis, cKeyStorePassword);
} } catch (GeneralSecurityException ex) {
catch (GeneralSecurityException ex) throw new CryptoException("Could not load keystore as type ''" + keyStoreType + "''.", ex);
{ } catch (FileNotFoundException ex) {
throw new CryptoException("Could not load keystore as type ''"+keyStoreType+"''.", ex);
}
catch (FileNotFoundException ex)
{
throw ex; throw ex;
} } catch (IOException ex) {
catch (IOException ex) throw new CryptoException("Could not load keystore as type ''" + keyStoreType + "''.", ex);
{ } finally {
throw new CryptoException("Could not load keystore as type ''"+keyStoreType+"''." , ex); try {
}
finally
{
try
{
fis.close(); fis.close();
} } catch (IOException ex) {
catch (IOException ex)
{
// Ignore // Ignore
ex.printStackTrace(); ex.printStackTrace();
} }
@ -320,14 +268,46 @@ public final class KeyStoreUtil{
return keyStore; return keyStore;
} }
public static KeyStore loadKeyStore(String keyStoreB64Encoded, char[] cKeyStorePassword, KeyStoreType keyStoreType){ public static KeyStore loadKeyStore(
Resource keystoreFile, char[] cKeyStorePassword, KeyStoreType keyStoreType)
throws CryptoException, IOException {
KeyStore keyStore = null;
try {
keyStore = getKeyStoreImpl(keyStoreType);
} catch (KeyStoreException ex) {
throw new CryptoException("Could not create " + keyStoreType + " keystore.", ex);
}
InputStream fis = keystoreFile.getInputStream();
try {
keyStore.load(fis, cKeyStorePassword);
} catch (GeneralSecurityException ex) {
throw new CryptoException("Could not load keystore as type ''" + keyStoreType + "''.", ex);
} catch (FileNotFoundException ex) {
throw ex;
} catch (IOException ex) {
throw new CryptoException("Could not load keystore as type ''" + keyStoreType + "''.", ex);
} finally {
try {
fis.close();
} catch (IOException ex) {
// Ignore
ex.printStackTrace();
}
}
return keyStore;
}
public static KeyStore loadKeyStore(String keyStoreB64Encoded, char[] cKeyStorePassword,
KeyStoreType keyStoreType) {
KeyStore keyStore; KeyStore keyStore;
try { try {
// //
keyStore = KeyStore.getInstance(keyStoreType.name()); keyStore = KeyStore.getInstance(keyStoreType.name());
byte[] keyStoreB64=Base64.decodeBase64(keyStoreB64Encoded.getBytes()); byte[] keyStoreB64 = Base64.decodeBase64(keyStoreB64Encoded.getBytes());
ByteArrayInputStream keyStoreBAIS=new ByteArrayInputStream(keyStoreB64); ByteArrayInputStream keyStoreBAIS = new ByteArrayInputStream(keyStoreB64);
keyStore.load(keyStoreBAIS, cKeyStorePassword); keyStore.load(keyStoreBAIS, cKeyStorePassword);
@ -345,12 +325,12 @@ public final class KeyStoreUtil{
return null; return null;
} }
public static String keyStore2Base64(KeyStore keyStore, String password){ public static String keyStore2Base64(KeyStore keyStore, String password) {
ByteArrayOutputStream stream =new ByteArrayOutputStream(); ByteArrayOutputStream stream = new ByteArrayOutputStream();
try { try {
keyStore.store(stream, password.toCharArray()); keyStore.store(stream, password.toCharArray());
byte[] keyStoreByte=stream.toByteArray(); byte[] keyStoreByte = stream.toByteArray();
String keyStoreBase64= Base64Utils.encodeBase64(keyStoreByte); String keyStoreBase64 = Base64Utils.encodeBase64(keyStoreByte);
return keyStoreBase64; return keyStoreBase64;
} catch (KeyStoreException e) { } catch (KeyStoreException e) {
@ -364,9 +344,10 @@ public final class KeyStoreUtil{
} }
return null; return null;
} }
public static KeyStore base642KeyStore(String keyStoreBase64, String password){
byte[] keyStoreByte=Base64Utils.decoderBase64(keyStoreBase64); public static KeyStore base642KeyStore(String keyStoreBase64, String password) {
return bytes2KeyStore(keyStoreByte,"JKS",password); byte[] keyStoreByte = Base64Utils.decoderBase64(keyStoreBase64);
return bytes2KeyStore(keyStoreByte, "JKS", password);
} }
/** /**
@ -377,39 +358,29 @@ public final class KeyStoreUtil{
* @return The keystore * @return The keystore
* @throws CryptoException Problem encountered loading the keystore * @throws CryptoException Problem encountered loading the keystore
*/ */
public static KeyStore loadKeyStore(String sPkcs11Provider, char[] cKeyStorePassword) public static KeyStore loadKeyStore(String sPkcs11Provider, char[] cKeyStorePassword) throws CryptoException {
throws CryptoException
{
KeyStore keyStore = null; KeyStore keyStore = null;
try try {
{ if (Security.getProvider(sPkcs11Provider) == null) {
if (Security.getProvider(sPkcs11Provider) == null) throw new CryptoException("The ''" + sPkcs11Provider + "'' provider is not present.");
{
throw new CryptoException("The ''"+sPkcs11Provider+"'' provider is not present." );
} }
keyStore = KeyStore.getInstance(KeyStoreType.PKCS11.name(), sPkcs11Provider); keyStore = KeyStore.getInstance(KeyStoreType.PKCS11.name(), sPkcs11Provider);
} } catch (GeneralSecurityException ex) {
catch (GeneralSecurityException ex) throw new CryptoException("Could not create " + KeyStoreType.PKCS11 + " keystore.", ex);
{
throw new CryptoException(
"Could not create "+KeyStoreType.PKCS11+" keystore.", ex);
} }
try try {
{
keyStore.load(null, cKeyStorePassword); keyStore.load(null, cKeyStorePassword);
} } catch (Exception ex) {
catch (Exception ex) throw new CryptoException("Could not load keystore as type ''" + KeyStoreType.PKCS11 + "''.", ex);
{
throw new CryptoException("Could not load keystore as type ''"+KeyStoreType.PKCS11+"''.", ex);
} }
return keyStore; return keyStore;
} }
/** */
/** *//** /**
* <p> * <p>
* get a Certificate from keyStore * get a Certificate from keyStore
* </p> * </p>
@ -420,7 +391,7 @@ public final class KeyStoreUtil{
* @throws Exception * @throws Exception
*/ */
public static Certificate getCertificate(KeyStore keyStore, String alias) { public static Certificate getCertificate(KeyStore keyStore, String alias) {
Certificate certificate=null; Certificate certificate = null;
try { try {
certificate = keyStore.getCertificate(alias); certificate = keyStore.getCertificate(alias);
} catch (KeyStoreException e) { } catch (KeyStoreException e) {
@ -429,7 +400,8 @@ public final class KeyStoreUtil{
return certificate; return certificate;
} }
/** *//** /** */
/**
* <p> * <p>
* 根据密钥库获得私<EFBFBD>? * 根据密钥库获得私<EFBFBD>?
* </p> * </p>
@ -440,15 +412,13 @@ public final class KeyStoreUtil{
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static PrivateKey getPrivateKey(KeyStore keyStore, String alias, String password) public static PrivateKey getPrivateKey(KeyStore keyStore, String alias, String password) throws Exception {
throws Exception {
PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
return privateKey; return privateKey;
} }
/** */
/**
/** *//**
* <p> * <p>
* 根据证书获得公钥 * 根据证书获得公钥
* </p> * </p>
@ -456,12 +426,13 @@ public final class KeyStoreUtil{
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static PublicKey getPublicKey(Certificate certificate)throws Exception { public static PublicKey getPublicKey(Certificate certificate) throws Exception {
PublicKey publicKey = certificate.getPublicKey(); PublicKey publicKey = certificate.getPublicKey();
return publicKey; return publicKey;
} }
/** *//** /** */
/**
* <p> * <p>
* 获得证书 * 获得证书
* </p> * </p>
@ -470,8 +441,7 @@ public final class KeyStoreUtil{
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static Certificate loadCertificateFromFile(String certificatePath) public static Certificate loadCertificateFromFile(String certificatePath) throws Exception {
throws Exception {
CertificateFactory certificateFactory = CertificateFactory.getInstance(X509); CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);
FileInputStream in = new FileInputStream(certificatePath); FileInputStream in = new FileInputStream(certificatePath);
Certificate certificate = certificateFactory.generateCertificate(in); Certificate certificate = certificateFactory.generateCertificate(in);
@ -479,7 +449,8 @@ public final class KeyStoreUtil{
return certificate; return certificate;
} }
/** *//** /** */
/**
* <p> * <p>
* 根据密钥库获得证<EFBFBD>? * 根据密钥库获得证<EFBFBD>?
* </p> * </p>
@ -490,36 +461,37 @@ public final class KeyStoreUtil{
* @return * @return
* @throws Exception * @throws Exception
*/ */
public static Certificate getCertificate(KeyStore keyStore, String alias, String password) public static Certificate getCertificate(KeyStore keyStore, String alias, String password) throws Exception {
throws Exception {
Certificate certificate = keyStore.getCertificate(alias); Certificate certificate = keyStore.getCertificate(alias);
return certificate; return certificate;
} }
/** /**
* import X509Certificate trustCert to keyStore * import X509Certificate trustCert to keyStore
*
* @param keyStore * @param keyStore
* @param trustCert * @param trustCert
* @return KeyStore * @return KeyStore
*/ */
public static KeyStore importTrustCertificate(KeyStore keyStore, X509Certificate trustCert){ public static KeyStore importTrustCertificate(KeyStore keyStore, X509Certificate trustCert) {
String sMatchAlias; String sMatchAlias;
try { try {
sMatchAlias = X509CertUtils.matchCertificate(keyStore, trustCert); sMatchAlias = X509CertUtils.matchCertificate(keyStore, trustCert);
System.out.println("sMatchAlias : "+sMatchAlias); System.out.println("sMatchAlias : " + sMatchAlias);
if(sMatchAlias != null){ if (sMatchAlias != null) {
System.out.println("The certificate already exists in the Keystore under alias ''"+sMatchAlias+"''.\nDo you still want to import it?"); System.out.println("The certificate already exists in the Keystore under alias ''" + sMatchAlias
}else{ + "''.\nDo you still want to import it?");
} else {
KeyStore[] keyStores = { keyStore }; KeyStore[] keyStores = { keyStore };
if (X509CertUtils.establishTrust(keyStores, trustCert) == null){ if (X509CertUtils.establishTrust(keyStores, trustCert) == null) {
System.out.println("Could not establish a trust path for the certficate.\nThe certficate information will now be displayed after\nwhich you may confirm whether or not you trust the\ncertificate."); System.out.println(
"Could not establish a trust path for the certficate.\nThe certficate information will now be displayed after\nwhich you may confirm whether or not you trust the\ncertificate.");
} }
String sCertAlias = X509CertUtils.getCertificateAlias(trustCert).toLowerCase(); String sCertAlias = X509CertUtils.getCertificateAlias(trustCert).toLowerCase();
// Delete old entry first // Delete old entry first
if (keyStore.containsAlias(sCertAlias)){ if (keyStore.containsAlias(sCertAlias)) {
keyStore.deleteEntry(sCertAlias); keyStore.deleteEntry(sCertAlias);
} }
// Import the trusted certificate // Import the trusted certificate
@ -537,26 +509,29 @@ public final class KeyStoreUtil{
/** /**
* import X509Certificate trustCert to keyStore * import X509Certificate trustCert to keyStore
*
* @param keyStore * @param keyStore
* @param trustCert * @param trustCert
* @return KeyStore * @return KeyStore
*/ */
public static KeyStore importTrustCertificate(KeyStore keyStore, X509Certificate trustCert,String sCertAlias){ public static KeyStore importTrustCertificate(KeyStore keyStore, X509Certificate trustCert, String sCertAlias) {
String sMatchAlias; String sMatchAlias;
try { try {
sMatchAlias = X509CertUtils.matchCertificate(keyStore, trustCert); sMatchAlias = X509CertUtils.matchCertificate(keyStore, trustCert);
System.out.println("sMatchAlias : "+sMatchAlias); System.out.println("sMatchAlias : " + sMatchAlias);
if(sMatchAlias != null){ if (sMatchAlias != null) {
System.out.println("The certificate already exists in the Keystore under alias ''"+sMatchAlias+"''.\nDo you still want to import it?"); System.out.println("The certificate already exists in the Keystore under alias ''" + sMatchAlias
}else{ + "''.\nDo you still want to import it?");
} else {
KeyStore[] keyStores = { keyStore }; KeyStore[] keyStores = { keyStore };
if (X509CertUtils.establishTrust(keyStores, trustCert) == null){ if (X509CertUtils.establishTrust(keyStores, trustCert) == null) {
System.out.println("Could not establish a trust path for the certficate.\nThe certficate information will now be displayed after\nwhich you may confirm whether or not you trust the\ncertificate."); System.out.println(
"Could not establish a trust path for the certficate.\nThe certficate information will now be displayed after\nwhich you may confirm whether or not you trust the\ncertificate.");
} }
// Delete old entry first // Delete old entry first
if (keyStore.containsAlias(sCertAlias)){ if (keyStore.containsAlias(sCertAlias)) {
keyStore.deleteEntry(sCertAlias); keyStore.deleteEntry(sCertAlias);
} }
// Import the trusted certificate // Import the trusted certificate
@ -580,36 +555,31 @@ public final class KeyStoreUtil{
* @param cKeyStorePassword The password to protect the keystore with * @param cKeyStorePassword The password to protect the keystore with
* @return the saved keystore ready for further use * @return the saved keystore ready for further use
* @throws CryptoException Problem encountered saving the keystore * @throws CryptoException Problem encountered saving the keystore
* @throws FileNotFoundException If the keystore file exists but is a directory rather than a regular * @throws FileNotFoundException If the keystore file exists but is a directory
* file, does not exist but cannot be created, or cannot be opened for any other reason * rather than a regular file, does not exist but
* cannot be created, or cannot be opened for any
* other reason
* @throws IOException An I/O error occurred * @throws IOException An I/O error occurred
*/ */
public static KeyStore saveKeyStore(KeyStore keyStore, File fKeyStoreFile, char[] cKeyStorePassword) public static KeyStore saveKeyStore(KeyStore keyStore, File fKeyStoreFile, char[] cKeyStorePassword)
throws CryptoException, IOException throws CryptoException, IOException {
{
FileOutputStream fos = new FileOutputStream(fKeyStoreFile); FileOutputStream fos = new FileOutputStream(fKeyStoreFile);
try try {
{
keyStore.store(fos, cKeyStorePassword); keyStore.store(fos, cKeyStorePassword);
} } catch (IOException ex) {
catch (IOException ex)
{
throw new CryptoException("Could not save keystore.", ex); throw new CryptoException("Could not save keystore.", ex);
} } catch (GeneralSecurityException ex) {
catch (GeneralSecurityException ex)
{
throw new CryptoException("Could not save keystore.", ex); throw new CryptoException("Could not save keystore.", ex);
} } finally {
finally
{
fos.close(); fos.close();
} }
// As of GNU classpath 0.92, we need to reload GKR keystores after storing them, otherwise // As of GNU classpath 0.92, we need to reload GKR keystores after storing them,
// "masked envelope" IllegalStateExceptions occur when trying to access things in the stored keystore // otherwise
// "masked envelope" IllegalStateExceptions occur when trying to access things
// in the stored keystore
// again. // again.
if (KeyStoreType.valueOf(keyStore.getType()) == KeyStoreType.GKR) if (KeyStoreType.valueOf(keyStore.getType()) == KeyStoreType.GKR) {
{
keyStore = loadKeyStore(fKeyStoreFile, cKeyStorePassword, KeyStoreType.GKR); keyStore = loadKeyStore(fKeyStoreFile, cKeyStorePassword, KeyStoreType.GKR);
} }
@ -624,17 +594,12 @@ public final class KeyStoreUtil{
* @return alias that is not in use in the keystore * @return alias that is not in use in the keystore
* @throws KeyStoreException * @throws KeyStoreException
*/ */
public static String findUnusedAlias(KeyStore keyStore, String alias) public static String findUnusedAlias(KeyStore keyStore, String alias) throws KeyStoreException {
throws KeyStoreException if (keyStore.containsAlias(alias)) {
{
if (keyStore.containsAlias(alias))
{
int i = 1; int i = 1;
while (true) while (true) {
{
String nextAlias = alias + " (" + i + ")"; String nextAlias = alias + " (" + i + ")";
if (!keyStore.containsAlias(nextAlias)) if (!keyStore.containsAlias(nextAlias)) {
{
alias = nextAlias; alias = nextAlias;
break; break;
} }
@ -642,13 +607,14 @@ public final class KeyStoreUtil{
} }
return alias; return alias;
} }
public static KeyStore clone(KeyStore keyStore,String password){
public static KeyStore clone(KeyStore keyStore, String password) {
try { try {
KeyStore cloneKeyStore= KeyStore.getInstance(keyStore.getType()); KeyStore cloneKeyStore = KeyStore.getInstance(keyStore.getType());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
keyStore.store(byteArrayOutputStream, password.toCharArray()); keyStore.store(byteArrayOutputStream, password.toCharArray());
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
cloneKeyStore.load(byteArrayInputStream, password.toCharArray()); cloneKeyStore.load(byteArrayInputStream, password.toCharArray());
byteArrayInputStream.close(); byteArrayInputStream.close();
byteArrayOutputStream.close(); byteArrayOutputStream.close();
@ -665,8 +631,8 @@ public final class KeyStoreUtil{
return null; return null;
} }
public static byte[] keyStore2Bytes(KeyStore keyStore ,String password){ public static byte[] keyStore2Bytes(KeyStore keyStore, String password) {
ByteArrayOutputStream stream =new ByteArrayOutputStream(); ByteArrayOutputStream stream = new ByteArrayOutputStream();
try { try {
keyStore.store(stream, password.toCharArray()); keyStore.store(stream, password.toCharArray());
return stream.toByteArray(); return stream.toByteArray();
@ -682,10 +648,10 @@ public final class KeyStoreUtil{
return null; return null;
} }
public static KeyStore bytes2KeyStore(byte[] keyStoreByte ,String keyStoreType,String password){ public static KeyStore bytes2KeyStore(byte[] keyStoreByte, String keyStoreType, String password) {
try { try {
KeyStore keyStore= KeyStore.getInstance(keyStoreType); KeyStore keyStore = KeyStore.getInstance(keyStoreType);
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(keyStoreByte); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(keyStoreByte);
keyStore.load(byteArrayInputStream, password.toCharArray()); keyStore.load(byteArrayInputStream, password.toCharArray());
return keyStore; return keyStore;
} catch (KeyStoreException e) { } catch (KeyStoreException e) {
@ -700,31 +666,31 @@ public final class KeyStoreUtil{
return null; return null;
} }
public static KeyStore setKeyEntry(KeyStore keyStore,String keyEntry,KeyPair keyPair,Certificate certificate,String password) throws KeyStoreException{ public static KeyStore setKeyEntry(KeyStore keyStore, String keyEntry, KeyPair keyPair, Certificate certificate,
String password) throws KeyStoreException {
Certificate[] certChain = new Certificate[1]; Certificate[] certChain = new Certificate[1];
certChain[0] = certificate; certChain[0] = certificate;
keyStore.setKeyEntry(keyEntry, (Key)keyPair.getPrivate(), password.toCharArray(), certChain); keyStore.setKeyEntry(keyEntry, (Key) keyPair.getPrivate(), password.toCharArray(), certChain);
return keyStore; return keyStore;
} }
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
KeyPair keyPair =X509V3CertGen.genRSAKeyPair(); KeyPair keyPair = X509V3CertGen.genRSAKeyPair();
String issuer="CN=connsec.com,O=connsec,L=SH,ST=SH,C=CN"; String issuer = "CN=connsec.com,O=connsec,L=SH,ST=SH,C=CN";
Date startDate=DateTime.now().toDate(); Date startDate = DateTime.now().toDate();
Date endDate=DateTime.now().plusMonths(10).toDate(); Date endDate = DateTime.now().plusMonths(10).toDate();
System.out.println("Private : "+ keyPair.getPrivate().toString()); System.out.println("Private : " + keyPair.getPrivate().toString());
System.out.println("Public : "+ keyPair.getPublic().toString()); System.out.println("Public : " + keyPair.getPublic().toString());
X509Certificate cert = X509V3CertGen.genV3Certificate(issuer,issuer,startDate,endDate,keyPair); X509Certificate cert = X509V3CertGen.genV3Certificate(issuer, issuer, startDate, endDate, keyPair);
KeyStore keyStore=KeyStoreUtil.createKeyStore(KeyStoreType.JKS); KeyStore keyStore = KeyStoreUtil.createKeyStore(KeyStoreType.JKS);
keyStore=KeyStoreUtil.setKeyEntry(keyStore, "connsec.com", keyPair, cert, "password"); keyStore = KeyStoreUtil.setKeyEntry(keyStore, "connsec.com", keyPair, cert, "password");
KeyStoreUtil.saveKeyStore(keyStore, new File("c:\\mykeystore"), "password".toCharArray()); KeyStoreUtil.saveKeyStore(keyStore, new File("c:\\mykeystore"), "password".toCharArray());
keyStore=KeyStoreUtil.loadKeyStore(new File("c:\\mykeystore"), "password".toCharArray(), KeyStoreType.JKS); keyStore = KeyStoreUtil.loadKeyStore(new File("c:\\mykeystore"), "password".toCharArray(), KeyStoreType.JKS);
System.out.println(KeyStoreUtil.getPrivateKey(keyStore, "connsec.com", "password")); System.out.println(KeyStoreUtil.getPrivateKey(keyStore, "connsec.com", "password"));
Certificate certificate = KeyStoreUtil.getCertificate(keyStore, "connsec.com"); Certificate certificate = KeyStoreUtil.getCertificate(keyStore, "connsec.com");
System.out.println(KeyStoreUtil.getPublicKey(certificate)); System.out.println(KeyStoreUtil.getPublicKey(certificate));
@ -732,91 +698,103 @@ public final class KeyStoreUtil{
} }
/** /**
* @param args * @param args
*
public static void main(String[] args) { * public static void main(String[] args) {
*
// new * // new //
// ByteArrayInputStream(Base64.decodeBase64(b64EncodedKeystore.getBytes())) * ByteArrayInputStream(Base64.decodeBase64(b64EncodedKeystore.getBytes()))
*
try { * try { // load a keyStore File file = new
// load a keyStore * File("C:\\cert\\idp-keystore.jks"); String keystorePassword =
File file = new File("C:\\cert\\idp-keystore.jks"); * "secret"; KeyStore ks = KeyStoreUtil.loadKeyStore(file,
String keystorePassword = "secret"; * keystorePassword.toCharArray(), KeyStoreType.JKS);
KeyStore ks = KeyStoreUtil.loadKeyStore(file, *
keystorePassword.toCharArray(), KeyStoreType.JKS); * String b64 = KeyStoreUtil.keyStore2Base64(ks,keystorePassword);
* System.out.println(b64); Enumeration<String> temp = ks.aliases();
String b64 = KeyStoreUtil.keyStore2Base64(ks,keystorePassword); * int i = 0; while (temp.hasMoreElements()) {
System.out.println(b64); * System.out.println("KeyStore alias name " + (i++) + " : " +
Enumeration<String> temp = ks.aliases(); * temp.nextElement()); }
int i = 0; *
while (temp.hasMoreElements()) { * System.out.println("=================================="); // load
System.out.println("KeyStore alias name " + (i++) + " : " * X509Certificate
+ temp.nextElement()); *
} * // one from pem file Reader reader =new FileReader(new
* File("C:\\cert\\onelogin.pem")); X509Certificate certPem =
System.out.println("=================================="); * X509CertUtils.loadCertFromReader(reader);
// load X509Certificate *
* System.out.println("====loadCertificateFromPEMReader:"+certPem.getIssuerDN());
// one from pem file *
Reader reader =new FileReader(new File("C:\\cert\\onelogin.pem")); * // two from bin file File fileCert = new
X509Certificate certPem = X509CertUtils.loadCertFromReader(reader); * File("C:\\cert\\clientCert.cert"); InputStream isCert = new
* FileInputStream(fileCert); X509Certificate trustCert =
System.out.println("====loadCertificateFromPEMReader:"+certPem.getIssuerDN()); * X509CertUtils.loadCertFromInputStream(isCert);
*
// two from bin file * ks = KeyStoreUtil.importTrustCertificate(ks, trustCert);
File fileCert = new File("C:\\cert\\clientCert.cert"); *
InputStream isCert = new FileInputStream(fileCert); * System.out
X509Certificate trustCert = X509CertUtils.loadCertFromInputStream(isCert); * .println("generatePEMEncoded==================================");
* System.out.println(X509CertUtils.generatePEMEncoded(trustCert));
ks = KeyStoreUtil.importTrustCertificate(ks, trustCert); *
* // output keystore to file KeyStoreUtil.saveKeyStore(ks, new
System.out * File( "C:\\cert\\ClientRegistrarKeyStore12.jks"),
.println("generatePEMEncoded=================================="); * keystorePassword.toCharArray());
System.out.println(X509CertUtils.generatePEMEncoded(trustCert)); *
* String pemString ="-----BEGIN CERTIFICATE-----"+'\n'; pemString
// output keystore to file * +=
KeyStoreUtil.saveKeyStore(ks, new File( * "MIIEHjCCAwagAwIBAgIBATANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJVUzET"+'\n';
"C:\\cert\\ClientRegistrarKeyStore12.jks"), * pemString +=
keystorePassword.toCharArray()); * "MBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UEBwwMU2FudGEgTW9uaWNhMREwDwYD"+'\n';
* pemString +=
String pemString ="-----BEGIN CERTIFICATE-----"+'\n'; * "VQQKDAhPbmVMb2dpbjEZMBcGA1UEAwwQYXBwLm9uZWxvZ2luLmNvbTAeFw0xMjEx"+'\n';
pemString += "MIIEHjCCAwagAwIBAgIBATANBgkqhkiG9w0BAQUFADBnMQswCQYDVQQGEwJVUzET"+'\n'; * pemString +=
pemString += "MBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UEBwwMU2FudGEgTW9uaWNhMREwDwYD"+'\n'; * "MDEwNzUzMTJaFw0xNzExMDEwNzUzMTJaMGcxCzAJBgNVBAYTAlVTMRMwEQYDVQQI"+'\n';
pemString += "VQQKDAhPbmVMb2dpbjEZMBcGA1UEAwwQYXBwLm9uZWxvZ2luLmNvbTAeFw0xMjEx"+'\n'; * pemString +=
pemString += "MDEwNzUzMTJaFw0xNzExMDEwNzUzMTJaMGcxCzAJBgNVBAYTAlVTMRMwEQYDVQQI"+'\n'; * "DApDYWxpZm9ybmlhMRUwEwYDVQQHDAxTYW50YSBNb25pY2ExETAPBgNVBAoMCE9u"+'\n';
pemString += "DApDYWxpZm9ybmlhMRUwEwYDVQQHDAxTYW50YSBNb25pY2ExETAPBgNVBAoMCE9u"+'\n'; * pemString +=
pemString += "ZUxvZ2luMRkwFwYDVQQDDBBhcHAub25lbG9naW4uY29tMIIBIjANBgkqhkiG9w0B"+'\n'; * "ZUxvZ2luMRkwFwYDVQQDDBBhcHAub25lbG9naW4uY29tMIIBIjANBgkqhkiG9w0B"+'\n';
pemString += "AQEFAAOCAQ8AMIIBCgKCAQEAsVV3NROfDQBtSmsyZjdHKre1BMzmnjdyM5vViZV+"+'\n'; * pemString +=
pemString += "OMjLU/aVejupyeNi6i6fqgBzU8a6vz3bXBnL4I8CAZYuRKxz57O2iTMTHLs6cAIT"+'\n'; * "AQEFAAOCAQ8AMIIBCgKCAQEAsVV3NROfDQBtSmsyZjdHKre1BMzmnjdyM5vViZV+"+'\n';
pemString += "FTXSfSn/3gxgaOTNfvFXtwSD5yMaxAZckhHCTqVQgUgLLV+JApTSnW22NFadJ8aM"+'\n'; * pemString +=
pemString += "hbajNCbpgIW0CFeiSlbojHzpeZewi8cTgjPDBbxwOeR8VUC6bMWsseqEyxUuHH9E"+'\n'; * "OMjLU/aVejupyeNi6i6fqgBzU8a6vz3bXBnL4I8CAZYuRKxz57O2iTMTHLs6cAIT"+'\n';
pemString += "TmO2pd9m5EKFpqZWlxGqa9qc6e89kpEhbIRpRjPWqSIjeDrsJllAmglsfD5MpnBq"+'\n'; * pemString +=
pemString += "bHXx4BK9cziv6TWMyF0MZ+CnfBWl5JCJaWBFQCs5bG0m8QIDAQABo4HUMIHRMAwG"+'\n'; * "FTXSfSn/3gxgaOTNfvFXtwSD5yMaxAZckhHCTqVQgUgLLV+JApTSnW22NFadJ8aM"+'\n';
pemString += "A1UdEwEB/wQCMAAwHQYDVR0OBBYEFG6SGHTIayKeDRRGEkIdVBeRwjcFMIGRBgNV"+'\n'; * pemString +=
pemString += "HSMEgYkwgYaAFG6SGHTIayKeDRRGEkIdVBeRwjcFoWukaTBnMQswCQYDVQQGEwJV"+'\n'; * "hbajNCbpgIW0CFeiSlbojHzpeZewi8cTgjPDBbxwOeR8VUC6bMWsseqEyxUuHH9E"+'\n';
pemString += "UzETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UEBwwMU2FudGEgTW9uaWNhMREw"+'\n'; * pemString +=
pemString += "DwYDVQQKDAhPbmVMb2dpbjEZMBcGA1UEAwwQYXBwLm9uZWxvZ2luLmNvbYIBATAO"+'\n'; * "TmO2pd9m5EKFpqZWlxGqa9qc6e89kpEhbIRpRjPWqSIjeDrsJllAmglsfD5MpnBq"+'\n';
pemString += "BgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcNAQEFBQADggEBAGkBjaIhHusWRmY0O16+"+'\n'; * pemString +=
pemString += "WoKC7l5Re2C+bz+tyuSLlDcuHniAsyhbYG8xvEJSOnxpeFbS/a4ko80wSsd+sUXJ"+'\n'; * "bHXx4BK9cziv6TWMyF0MZ+CnfBWl5JCJaWBFQCs5bG0m8QIDAQABo4HUMIHRMAwG"+'\n';
pemString += "FR3Z40W0JNT6ELn5Tf51b+cbm3erucMxKIDiMsQBcO/nHHBQs25kTXeKBjLnR/9u"+'\n'; * pemString +=
pemString += "i3+naVemnRb1cvffenAPpm12yKqWWcKgN19mE2vdrw0y/GoirFFtO/STdkDPKuYu"+'\n'; * "A1UdEwEB/wQCMAAwHQYDVR0OBBYEFG6SGHTIayKeDRRGEkIdVBeRwjcFMIGRBgNV"+'\n';
pemString += "6wubRBeURNzqims0xe4/vPFE7iN50bjgKcuPn6LMaIDrLJVkwMC09MNsr0Dgmqgt"+'\n'; * pemString +=
pemString += "hBdnEqXkhdE8F/VneHn5xLSfExC662OaU6jqDASBvN15mrLGaQ+Ou9qOsCFi7wg6"+'\n'; * "HSMEgYkwgYaAFG6SGHTIayKeDRRGEkIdVBeRwjcFoWukaTBnMQswCQYDVQQGEwJV"+'\n';
pemString += "8QI="+'\n'; * pemString +=
pemString += "-----END CERTIFICATE-----"+'\n'; * "UzETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UEBwwMU2FudGEgTW9uaWNhMREw"+'\n';
* pemString +=
System.out.println(pemString); * "DwYDVQQKDAhPbmVMb2dpbjEZMBcGA1UEAwwQYXBwLm9uZWxvZ2luLmNvbYIBATAO"+'\n';
X509Certificate x509Certificate = * pemString +=
X509CertUtils.loadCertFromPEM(pemString); * "BgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcNAQEFBQADggEBAGkBjaIhHusWRmY0O16+"+'\n';
System.out.println(x509Certificate.getIssuerDN()); * pemString +=
} catch (IOException e) { * "WoKC7l5Re2C+bz+tyuSLlDcuHniAsyhbYG8xvEJSOnxpeFbS/a4ko80wSsd+sUXJ"+'\n';
e.printStackTrace(); * pemString +=
} catch (KeyStoreException e) { * "FR3Z40W0JNT6ELn5Tf51b+cbm3erucMxKIDiMsQBcO/nHHBQs25kTXeKBjLnR/9u"+'\n';
e.printStackTrace(); * pemString +=
} catch (Exception e) { * "i3+naVemnRb1cvffenAPpm12yKqWWcKgN19mE2vdrw0y/GoirFFtO/STdkDPKuYu"+'\n';
e.printStackTrace(); * pemString +=
} * "6wubRBeURNzqims0xe4/vPFE7iN50bjgKcuPn6LMaIDrLJVkwMC09MNsr0Dgmqgt"+'\n';
* pemString +=
}*/ * "hBdnEqXkhdE8F/VneHn5xLSfExC662OaU6jqDASBvN15mrLGaQ+Ou9qOsCFi7wg6"+'\n';
* pemString += "8QI="+'\n'; pemString += "-----END
* CERTIFICATE-----"+'\n';
*
* System.out.println(pemString); X509Certificate x509Certificate =
* X509CertUtils.loadCertFromPEM(pemString);
* System.out.println(x509Certificate.getIssuerDN()); } catch
* (IOException e) { e.printStackTrace(); } catch (KeyStoreException
* e) { e.printStackTrace(); } catch (Exception e) {
* e.printStackTrace(); }
*
* }
*/
} }

View File

@ -32,7 +32,7 @@ public class ConfigurerFreeMarker implements ApplicationContextAware {
Map<String, Object> map = this.applicationContext.getBeansWithAnnotation(FreemarkerTag.class); Map<String, Object> map = this.applicationContext.getBeansWithAnnotation(FreemarkerTag.class);
for (String key : map.keySet()) { for (String key : map.keySet()) {
configuration.setSharedVariable(key, map.get(key)); configuration.setSharedVariable(key, map.get(key));
_logger.debug("FreeMarker Template "+key); _logger.trace("FreeMarker Template "+key);
} }
} }

View File

@ -60,7 +60,8 @@ public class InitApplicationContext extends HttpServlet {
* InitApplicationContext. * InitApplicationContext.
*/ */
public InitApplicationContext() { public InitApplicationContext() {
this.applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); this.applicationContext =
WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
} }
public InitApplicationContext(ConfigurableApplicationContext applicationContext) { public InitApplicationContext(ConfigurableApplicationContext applicationContext) {
@ -71,20 +72,19 @@ public class InitApplicationContext extends HttpServlet {
* loadCaches. * loadCaches.
*/ */
public void loadCaches() { public void loadCaches() {
_logger.info( _logger.info("-----------------------------------------------------------");
"----------------------------------------------------------------------------------------------------");
_logger.info("Load Caches "); _logger.info("Load Caches ");
try { try {
if (applicationContext.containsBean("cacheFactory")) { if (applicationContext.containsBean("cacheFactory")) {
CacheFactory cacheFactory = applicationContext.getBean("cacheFactory", CacheFactory.class); CacheFactory cacheFactory =
applicationContext.getBean("cacheFactory", CacheFactory.class);
cacheFactory.start(); cacheFactory.start();
} }
} catch (BeansException e) { } catch (BeansException e) {
e.printStackTrace(); e.printStackTrace();
} }
_logger.info( _logger.info("-----------------------------------------------------------");
"----------------------------------------------------------------------------------------------------");
} }
@ -94,30 +94,42 @@ public class InitApplicationContext extends HttpServlet {
public void listDataBaseVariables() { public void listDataBaseVariables() {
if (applicationContext.containsBean("dataSource")) { if (applicationContext.containsBean("dataSource")) {
try { try {
_logger.debug( _logger.debug("-----------------------------------------------------------");
"----------------------------------------------------------------------------------------------------");
_logger.debug("List DatabaseMetaData Variables "); _logger.debug("List DatabaseMetaData Variables ");
Connection connection = ((javax.sql.DataSource) applicationContext.getBean("dataSource")) Connection connection =
((javax.sql.DataSource) applicationContext.getBean("dataSource"))
.getConnection(); .getConnection();
java.sql.DatabaseMetaData databaseMetaData = connection.getMetaData(); java.sql.DatabaseMetaData databaseMetaData = connection.getMetaData();
_logger.debug("DatabaseProductName : " + databaseMetaData.getDatabaseProductName()); _logger.debug("DatabaseProductName : "
_logger.debug("DatabaseProductVersion: " + databaseMetaData.getDatabaseProductVersion()); + databaseMetaData.getDatabaseProductName());
_logger.debug("DatabaseMajorVersion : " + databaseMetaData.getDatabaseMajorVersion()); _logger.debug("DatabaseProductVersion: "
_logger.debug("DatabaseMinorVersion : " + databaseMetaData.getDatabaseMinorVersion()); + databaseMetaData.getDatabaseProductVersion());
_logger.debug("supportsTransactions : " + databaseMetaData.supportsTransactions()); _logger.debug("DatabaseMajorVersion : "
_logger.debug("DefaultTransaction : " + databaseMetaData.getDefaultTransactionIsolation()); + databaseMetaData.getDatabaseMajorVersion());
_logger.debug("MaxConnections : " + databaseMetaData.getMaxConnections()); _logger.debug("DatabaseMinorVersion : "
+ databaseMetaData.getDatabaseMinorVersion());
_logger.debug("supportsTransactions : "
+ databaseMetaData.supportsTransactions());
_logger.debug("DefaultTransaction : "
+ databaseMetaData.getDefaultTransactionIsolation());
_logger.debug("MaxConnections : "
+ databaseMetaData.getMaxConnections());
_logger.debug(""); _logger.debug("");
_logger.debug("JDBCMajorVersion : " + databaseMetaData.getJDBCMajorVersion()); _logger.debug("JDBCMajorVersion : "
_logger.debug("JDBCMinorVersion : " + databaseMetaData.getJDBCMinorVersion()); + databaseMetaData.getJDBCMajorVersion());
_logger.debug("DriverName : " + databaseMetaData.getDriverName()); _logger.debug("JDBCMinorVersion : "
_logger.debug("DriverVersion : " + databaseMetaData.getDriverVersion()); + databaseMetaData.getJDBCMinorVersion());
_logger.debug("DriverName : "
+ databaseMetaData.getDriverName());
_logger.debug("DriverVersion : "
+ databaseMetaData.getDriverVersion());
_logger.debug(""); _logger.debug("");
_logger.debug("DBMS URL : " + databaseMetaData.getURL()); _logger.debug("DBMS URL : "
_logger.debug("UserName : " + databaseMetaData.getUserName()); + databaseMetaData.getURL());
_logger.debug( _logger.debug("UserName : "
"----------------------------------------------------------------------------------------------------"); + databaseMetaData.getUserName());
_logger.debug("-----------------------------------------------------------");
} catch (SQLException e) { } catch (SQLException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -129,13 +141,15 @@ public class InitApplicationContext extends HttpServlet {
*/ */
public void listProperties() { public void listProperties() {
if (applicationContext.containsBean("propertySourcesPlaceholderConfigurer")) { if (applicationContext.containsBean("propertySourcesPlaceholderConfigurer")) {
_logger.debug( _logger.trace("-----------------------------------------------------------");
"----------------------------------------------------------------------------------------------------"); _logger.trace("List Properties Variables ");
_logger.debug("List Properties Variables "); PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer =
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = ((PropertySourcesPlaceholderConfigurer) applicationContext ((PropertySourcesPlaceholderConfigurer) applicationContext
.getBean("propertySourcesPlaceholderConfigurer")); .getBean("propertySourcesPlaceholderConfigurer"));
properties = (Properties) propertySourcesPlaceholderConfigurer.getAppliedPropertySources() properties = (Properties) propertySourcesPlaceholderConfigurer
.get(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME).getSource(); .getAppliedPropertySources()
.get(PropertySourcesPlaceholderConfigurer.LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME)
.getSource();
Set<Object> keyValue = properties.keySet(); Set<Object> keyValue = properties.keySet();
SortedSet<String> keyValueSet = new TreeSet<String>(); SortedSet<String> keyValueSet = new TreeSet<String>();
// sort key // sort key
@ -146,10 +160,9 @@ public class InitApplicationContext extends HttpServlet {
// out // out
for (Iterator<String> it = keyValueSet.iterator(); it.hasNext();) { for (Iterator<String> it = keyValueSet.iterator(); it.hasNext();) {
String key = (String) it.next(); String key = (String) it.next();
_logger.debug(key + " = " + properties.get(key)); _logger.trace(key + " = " + properties.get(key));
} }
_logger.debug( _logger.trace("-----------------------------------------------------------");
"----------------------------------------------------------------------------------------------------");
} }
} }
@ -157,8 +170,7 @@ public class InitApplicationContext extends HttpServlet {
* listEnvVars. * listEnvVars.
*/ */
public void listEnvVars() { public void listEnvVars() {
_logger.debug( _logger.debug("-----------------------------------------------------------");
"----------------------------------------------------------------------------------------------------");
_logger.debug("List Environment Variables "); _logger.debug("List Environment Variables ");
Map<String, String> map = System.getenv(); Map<String, String> map = System.getenv();
SortedSet<String> keyValueSet = new TreeSet<String>(); SortedSet<String> keyValueSet = new TreeSet<String>();
@ -169,27 +181,25 @@ public class InitApplicationContext extends HttpServlet {
// out // out
for (Iterator<String> it = keyValueSet.iterator(); it.hasNext();) { for (Iterator<String> it = keyValueSet.iterator(); it.hasNext();) {
String key = (String) it.next(); String key = (String) it.next();
_logger.debug(key + " = " + map.get(key)); _logger.trace(key + " = " + map.get(key));
} }
_logger.debug("APP_HOME" + " = " + PathUtils.getInstance().getAppPath()); _logger.debug("APP_HOME" + " = " + PathUtils.getInstance().getAppPath());
_logger.debug( _logger.debug("-----------------------------------------------------------");
"----------------------------------------------------------------------------------------------------");
} }
/** /**
* showLicense. * showLicense.
*/ */
public void showLicense() { public void showLicense() {
_logger.info( _logger.info("-----------------------------------------------------------");
"----------------------------------------------------------------------------------------------------");
_logger.info("+ Single Sign On ( SSO ) "); _logger.info("+ Single Sign On ( SSO ) ");
_logger.info("+ MaxKey Version "+properties.getProperty("application.formatted-version")); _logger.info("+ MaxKey Version "
+ properties.getProperty("application.formatted-version"));
_logger.info(""); _logger.info("");
_logger.info("+ Apache License 2.0"); _logger.info("+ Apache License 2.0");
_logger.info("+ https://shimingxy.github.io/MaxKey/"); _logger.info("+ https://shimingxy.github.io/MaxKey/");
_logger.info("+ email:shimingxy@163.com"); _logger.info("+ email:shimingxy@163.com");
_logger.info( _logger.info("-----------------------------------------------------------");
"----------------------------------------------------------------------------------------------------");
} }
} }

View File

@ -73,6 +73,7 @@ import org.opensaml.saml2.metadata.impl.SurNameBuilder;
import org.opensaml.saml2.metadata.impl.TelephoneNumberBuilder; import org.opensaml.saml2.metadata.impl.TelephoneNumberBuilder;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import java.security.KeyStore; import java.security.KeyStore;
@ -118,7 +119,7 @@ public void samlmtest(){
try { try {
KeyStoreLoader keyStoreLoader=new KeyStoreLoader(); KeyStoreLoader keyStoreLoader=new KeyStoreLoader();
keyStoreLoader.setKeystorePassword("secret"); keyStoreLoader.setKeystorePassword("secret");
keyStoreLoader.setKeystoreFile("D:/JavaIDE/cert/idp-keystore.jks"); keyStoreLoader.setKeystoreFile(new FileSystemResource("D:/JavaIDE/cert/idp-keystore.jks"));
keyStoreLoader.afterPropertiesSet(); keyStoreLoader.afterPropertiesSet();
KeyStore trustKeyStore =keyStoreLoader.getKeyStore(); KeyStore trustKeyStore =keyStoreLoader.getKeyStore();

View File

@ -6,14 +6,14 @@
<appenders> <appenders>
<Console name="consolePrint" target="SYSTEM_OUT"> <Console name="consolePrint" target="SYSTEM_OUT">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss,SSS} [%t] %-5level %logger{36} - %msg%n" /> <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss,SSS} %-5level [%t] %logger{36}:%L - %msg%n" />
</Console> </Console>
<!-- 输出到文件按天或者超过128MB分割 --> <!-- 输出到文件按天或者超过128MB分割 -->
<RollingFile name="RollingFile" fileName="logs/maxkey_mgt.log" filePattern="logs/$${date:yyyyMMdd}/maxkey-%d{yyyy-MM-dd}-%i.log.gz"> <RollingFile name="RollingFile" fileName="logs/maxkey_mgt.log" filePattern="logs/$${date:yyyyMMdd}/maxkey-%d{yyyy-MM-dd}-%i.log.gz">
<!-- 需要记录的级别 --> <!-- 需要记录的级别 -->
<!-- <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" /> --> <!-- <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" /> -->
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n" /> <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss,SSS} %-5level [%t] (%logger{36}:%L) - %msg%n" />
<Policies> <Policies>
<OnStartupTriggeringPolicy /> <OnStartupTriggeringPolicy />
<TimeBasedTriggeringPolicy /> <TimeBasedTriggeringPolicy />

View File

@ -6,14 +6,14 @@
<appenders> <appenders>
<Console name="consolePrint" target="SYSTEM_OUT"> <Console name="consolePrint" target="SYSTEM_OUT">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss,SSS} [%t] %-5level %logger{36} - %msg%n" /> <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss,SSS} %-5level [%t] %logger{36}:%L - %msg%n" />
</Console> </Console>
<!-- 输出到文件按天或者超过128MB分割 每天进行归档yyyy-MM-dd --> <!-- 输出到文件按天或者超过128MB分割 每天进行归档yyyy-MM-dd -->
<RollingFile name="RollingFile" fileName="logs/maxkey.log" filePattern="logs/$${date:yyyyMMdd}/maxkey-%d{yyyy-MM-dd}-%i.log.gz"> <RollingFile name="RollingFile" fileName="logs/maxkey.log" filePattern="logs/$${date:yyyyMMdd}/maxkey-%d{yyyy-MM-dd}-%i.log.gz">
<!-- 需要记录的级别 --> <!-- 需要记录的级别 -->
<!-- <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" /> --> <!-- <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY" /> -->
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n" /> <PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss,SSS} %-5level [%t] %logger{36}:%L - %msg%n" />
<Policies> <Policies>
<OnStartupTriggeringPolicy /> <OnStartupTriggeringPolicy />
<TimeBasedTriggeringPolicy /> <TimeBasedTriggeringPolicy />