/* * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions.
*/
/** * * @author Sean Mullan * @author Steve Hanna *
*/
/** * Get a PEM-encoded PKCS8 private key from a string. * * @param keyAlgo the key algorithm * @param keyStr string containing the PEM-encoded PKCS8 private key * @return the private key * @throws NoSuchAlgorithmException if no Provider supports a KeyFactorySpi * implementation for the specified algorithm * @throws InvalidKeySpecException if the given key specification is * inappropriate for this key factory to produce a private key.
*/ publicstatic PrivateKey getKeyFromString(String keyAlgo, String keyStr) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeyFactory keyFactory = KeyFactory.getInstance(keyAlgo);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(
Base64.getMimeDecoder().decode(keyStr));
PrivateKey key = keyFactory.generatePrivate(keySpec); return key;
}
/** * Get a PEM-encoded PKCS8 private key from a file. * * @param keyAlgo the key algorithm * @param keyPath path to file containing the PEM-encoded PKCS8 private key * @return the private key * @throws NoSuchAlgorithmException if no Provider supports a KeyFactorySpi * implementation for the specified algorithm * @throws InvalidKeySpecException if the given key specification is * inappropriate for this key factory to produce a private key.
*/ publicstatic PrivateKey getKeyFromFile(String keyAlgo, String keyPath) throws NoSuchAlgorithmException, InvalidKeySpecException { return getKeyFromString(
keyAlgo,
// Filter the below lines if any // -----BEGIN PRIVATE KEY----- // -----END PRIVATE KEY-----
readFile(keyPath, line -> !line.startsWith("-----")));
}
/** * Get an X.509 certificate from an input stream. * * @param input an input stream with the certificate data. * @return the X509Certificate * @throws CertificateException on parsing errors. * @throws IOException on input stream errors.
*/ publicstatic X509Certificate getCertFromStream(InputStream input) throws CertificateException, IOException { try {
CertificateFactory certFactory
= CertificateFactory.getInstance("X.509"); return (X509Certificate) certFactory.generateCertificate(input);
} finally { if (input != null) {
input.close();
}
}
}
/** * Get a PEM-encoded X.509 certificate from a string. * * @param cert string containing the PEM-encoded certificate * @return the X509Certificate * @throws CertificateException if the certificate type is not supported * or cannot be parsed * @throws IOException
*/ publicstatic X509Certificate getCertFromString(String certStr) throws CertificateException, IOException { return getCertFromStream(new ByteArrayInputStream(certStr.getBytes()));
}
/** * Get a X.509 certificate from a file. * * @param certFilePath path to file containing certificate * @return the X509Certificate * @throws CertificateException if the certificate type is not supported * or cannot be parsed * @throws IOException if the file cannot be opened
*/ publicstatic X509Certificate getCertFromFile(String certFilePath) throws CertificateException, IOException { return getCertFromStream(
Files.newInputStream(Paths.get(TEST_SRC, certFilePath)));
}
/** * Get a DER-encoded X.509 CRL from a file. * * @param crlFilePath path to file containing DER-encoded CRL * @return the X509CRL * @throws CertificateException if the crl type is not supported * @throws CRLException if the crl cannot be parsed * @throws IOException if the file cannot be opened
*/ publicstatic X509CRL getCRLFromFile(String crlFilePath) throws CertificateException, CRLException, IOException {
File crlFile = new File(TEST_SRC, crlFilePath); try (FileInputStream fis = new FileInputStream(crlFile)) { return (X509CRL)
CertificateFactory.getInstance("X.509").generateCRL(fis);
}
}
/** * Get a PEM-encoded X.509 crl from a string. * * @param crl string containing the PEM-encoded crl * @return the X509CRL * @throws CertificateException if the crl type is not supported * @throws CRLException if the crl cannot be parsed
*/ publicstatic X509CRL getCRLFromString(String crl) throws CertificateException, CRLException { byte[] crlBytes = crl.getBytes();
ByteArrayInputStream bais = new ByteArrayInputStream(crlBytes); return (X509CRL)
CertificateFactory.getInstance("X.509").generateCRL(bais);
}
/** * Read a bunch of certs from files and create a CertPath from them. * * @param fileNames an array of <code>String</code>s that are file names * @throws Exception on error
*/ publicstatic CertPath buildPath(String [] fileNames) throws Exception { return buildPath("", fileNames);
}
/** * Read a bunch of certs from files and create a CertPath from them. * * @param relPath relative path containing certs (must end in * file.separator) * @param fileNames an array of <code>String</code>s that are file names * @throws Exception on error
*/ publicstatic CertPath buildPath(String relPath, String [] fileNames) throws Exception {
List<X509Certificate> list = new ArrayList<X509Certificate>(); for (int i = 0; i < fileNames.length; i++) {
list.add(0, getCertFromFile(relPath + fileNames[i]));
}
CertificateFactory cf = CertificateFactory.getInstance("X509"); return(cf.generateCertPath(list));
}
/** * Read a bunch of certs from files and create a CertStore from them. * * @param fileNames an array of <code>String</code>s that are file names * @return the <code>CertStore</code> created * @throws Exception on error
*/ publicstatic CertStore createStore(String [] fileNames) throws Exception { return createStore("", fileNames);
}
/** * Read a bunch of certs from files and create a CertStore from them. * * @param relPath relative path containing certs (must end in * file.separator) * @param fileNames an array of <code>String</code>s that are file names * @return the <code>CertStore</code> created * @throws Exception on error
*/ publicstatic CertStore createStore(String relPath, String [] fileNames) throws Exception {
Set<X509Certificate> certs = new HashSet<X509Certificate>(); for (int i = 0; i < fileNames.length; i++) {
certs.add(getCertFromFile(relPath + fileNames[i]));
} return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs));
}
/** * Read a bunch of CRLs from files and create a CertStore from them. * * @param fileNames an array of <code>String</code>s that are file names * @return the <code>CertStore</code> created * @throws Exception on error
*/ publicstatic CertStore createCRLStore(String [] fileNames) throws Exception { return createCRLStore("", fileNames);
}
/** * Read a bunch of CRLs from files and create a CertStore from them. * * @param relPath relative path containing CRLs (must end in file.separator) * @param fileNames an array of <code>String</code>s that are file names * @return the <code>CertStore</code> created * @throws Exception on error
*/ publicstatic CertStore createCRLStore(String relPath, String [] fileNames) throws Exception {
Set<X509CRL> crls = new HashSet<X509CRL>(); for (int i = 0; i < fileNames.length; i++) {
crls.add(getCRLFromFile(relPath + fileNames[i]));
} return CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls));
}
/** * Perform a PKIX path build. On failure, throw an exception. * * @param params PKIXBuilderParameters to use in validation * @throws Exception on error
*/ publicstatic PKIXCertPathBuilderResult build(PKIXBuilderParameters params) throws Exception {
CertPathBuilder builder =
CertPathBuilder.getInstance("PKIX"); return (PKIXCertPathBuilderResult) builder.build(params);
}
/** * Perform a PKIX validation. On failure, throw an exception. * * @param path CertPath to validate * @param params PKIXParameters to use in validation * @throws Exception on error
*/ publicstatic PKIXCertPathValidatorResult validate
(CertPath path, PKIXParameters params) throws Exception {
CertPathValidator validator =
CertPathValidator.getInstance("PKIX"); return (PKIXCertPathValidatorResult) validator.validate(path, params);
}
/** * Get the content of a file with given filter condition. * * @param relativeFilePath path to file that relative to test.src directory. * @param predicate The condition for filtering file content * @return the file content
*/ privatestatic String readFile(String relativeFilePath,
Predicate<String> predicate) {
Path filePath = Paths.get(TEST_SRC, relativeFilePath); try (Stream<String> lines = Files.lines(filePath)) {
Stream<String> interStream = null; if (predicate != null) {
interStream = lines.filter(predicate);
} return interStream != null
? interStream.collect(Collectors.joining("\n"))
: lines.collect(Collectors.joining("\n"));
} catch (IOException e) { thrownew RuntimeException("Cannot read file", e);
}
}
/** * This class is useful for overriding one or more methods of an * X509Certificate for testing purposes.
*/ publicstaticclass ForwardingX509Certificate extends X509Certificate { privatefinal X509Certificate cert; public ForwardingX509Certificate(X509Certificate cert) { this.cert = cert;
} public Set<String> getCriticalExtensionOIDs() { return cert.getCriticalExtensionOIDs();
} publicbyte[] getExtensionValue(String oid) { return cert.getExtensionValue(oid);
} public Set<String> getNonCriticalExtensionOIDs() { return cert.getNonCriticalExtensionOIDs();
} publicboolean hasUnsupportedCriticalExtension() { return cert.hasUnsupportedCriticalExtension();
} publicvoid checkValidity() throws CertificateExpiredException,
CertificateNotYetValidException { /* always pass */ } publicvoid checkValidity(Date date) throws CertificateExpiredException,
CertificateNotYetValidException { /* always pass */ } publicint getVersion() { return cert.getVersion(); } public BigInteger getSerialNumber() { return cert.getSerialNumber(); } public Principal getIssuerDN() { return cert.getIssuerDN(); } public Principal getSubjectDN() { return cert.getSubjectDN(); } public Date getNotBefore() { return cert.getNotBefore(); } public Date getNotAfter() { return cert.getNotAfter(); } publicbyte[] getTBSCertificate() throws CertificateEncodingException { return cert.getTBSCertificate();
} publicbyte[] getSignature() { return cert.getSignature(); } public String getSigAlgName() { return cert.getSigAlgName(); } public String getSigAlgOID() { return cert.getSigAlgOID(); } publicbyte[] getSigAlgParams() { return cert.getSigAlgParams(); } publicboolean[] getIssuerUniqueID() { return cert.getIssuerUniqueID();
} publicboolean[] getSubjectUniqueID() { return cert.getSubjectUniqueID();
} publicboolean[] getKeyUsage() { return cert.getKeyUsage(); } publicint getBasicConstraints() { return cert.getBasicConstraints(); } publicbyte[] getEncoded() throws CertificateEncodingException { return cert.getEncoded();
} publicvoid verify(PublicKey key) throws CertificateException,
InvalidKeyException, NoSuchAlgorithmException,
NoSuchProviderException, SignatureException {
cert.verify(key);
} publicvoid verify(PublicKey key, String sigProvider) throws
CertificateException, InvalidKeyException, NoSuchAlgorithmException,
NoSuchProviderException, SignatureException {
cert.verify(key, sigProvider);
} public PublicKey getPublicKey() { return cert.getPublicKey(); } public String toString() { return cert.toString(); }
}
}
Messung V0.5
¤ Dauer der Verarbeitung: 0.21 Sekunden
(vorverarbeitet)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.