下面列出了java.security.cert.CertificateExpiredException#java.security.KeyStore 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static String writeKeyStore(KeyStore keyStore, OutputStreamFactory outputStreamFactory, File file, String password, boolean generatedPassword) throws IOException, GeneralSecurityException {
try (OutputStream fileOutputStream = outputStreamFactory.create(file)) {
keyStore.store(fileOutputStream, password.toCharArray());
} catch (IOException e) {
if (e.getMessage().toLowerCase().contains(ILLEGAL_KEY_SIZE) && !isUnlimitedStrengthCryptographyEnabled()) {
if (generatedPassword) {
file.delete();
String truncatedPassword = password.substring(0, 7);
try (OutputStream fileOutputStream = outputStreamFactory.create(file)) {
keyStore.store(fileOutputStream, truncatedPassword.toCharArray());
}
logTruncationWarning(file);
return truncatedPassword;
} else {
throw new GeneralSecurityException("Specified password for " + file + " too long to work without unlimited JCE policy installed."
+ System.lineSeparator() + "Please see " + JCE_URL);
}
} else {
throw e;
}
}
return password;
}
public static KeyStore getKeystore()
{
KeyStore keystore1 = KeyStore.getInstance(KeyStore.getDefaultType());
KeyStore keystore = keystore1;
keystore.load(null, null);
return keystore;
Throwable throwable;
throwable;
Throwable throwable1;
keystore = null;
throwable1 = throwable;
_L2:
throwable1.printStackTrace();
return keystore;
throwable1;
if (true) goto _L2; else goto _L1
_L1:
}
private static Server createServer(Handler handler, int port, KeyStore keyStore, String keyPassword) throws Exception {
Server server = new Server();
SslContextFactory sslContextFactory = new SslContextFactory();
sslContextFactory.setIncludeProtocols(CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
sslContextFactory.setKeyStore(keyStore);
sslContextFactory.setKeyManagerPassword(keyPassword);
// Need to set SslContextFactory's endpointIdentificationAlgorithm to null; this is a server,
// not a client. Server does not need to perform hostname verification on the client.
// Previous to Jetty 9.4.15.v20190215, this defaulted to null, and now defaults to "HTTPS".
sslContextFactory.setEndpointIdentificationAlgorithm(null);
HttpConfiguration httpsConfig = new HttpConfiguration();
httpsConfig.addCustomizer(new SecureRequestCustomizer());
ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig));
sslConnector.setPort(port);
server.addConnector(sslConnector);
server.setHandler(handler);
return server;
}
@Before
public void setUp() throws Exception {
callbackHandler = new MockCallbackHandler("Alias: ", "Certificate: ");
HashMap<String,String> sharedState = new HashMap<>();
HashMap<String,String> options = new HashMap<>();
options.put("rolesProperties", "roles.properties");
options.put("principalClass", "datawave.security.authorization.DatawavePrincipal");
options.put("verifier", MockDatawaveCertVerifier.class.getName());
loginModule = new DatawaveCertRolesLoginModule();
loginModule.initialize(new Subject(), callbackHandler, sharedState, options);
KeyStore truststore = KeyStore.getInstance("PKCS12");
truststore.load(getClass().getResourceAsStream("/ca.pkcs12"), "secret".toCharArray());
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(getClass().getResourceAsStream("/testUser.pkcs12"), "secret".toCharArray());
testUserCert = (X509Certificate) keystore.getCertificate("testuser");
}
/**
* Extracts the {@link KeyStore.TrustedCertificateEntry}s from the specified KeyStore. All other entry
* types, including private keys, will be ignored.
*
* @param trustStore keystore containing trusted certificate entries
* @return the trusted certificate entries in the specified keystore
*/
public static List<X509Certificate> extractTrustedCertificateEntries(KeyStore trustStore) {
try {
Enumeration<String> aliases = trustStore.aliases();
List<String> keyStoreAliases = Collections.list(aliases);
List<X509Certificate> trustedCertificates = new ArrayList<>(keyStoreAliases.size());
for (String alias : keyStoreAliases) {
if (trustStore.entryInstanceOf(alias, KeyStore.TrustedCertificateEntry.class)) {
Certificate certificate = trustStore.getCertificate(alias);
if (!(certificate instanceof X509Certificate)) {
log.debug("Skipping non-X509Certificate in KeyStore. Certificate type: {}", certificate.getType());
continue;
}
trustedCertificates.add((X509Certificate) certificate);
}
}
return trustedCertificates;
} catch (KeyStoreException e) {
throw new KeyStoreAccessException("Error occurred while retrieving trusted CAs from KeyStore", e);
}
}
private static KeyStore loadKeyStore(final File keystoreFile, final String password, final String keyStoreType)
throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
if (null == keystoreFile) {
throw new IllegalArgumentException("Keystore url may not be null");
}
URI keystoreUri = keystoreFile.toURI();
URL keystoreUrl = keystoreUri.toURL();
KeyStore keystore = KeyStore.getInstance(keyStoreType);
InputStream is = null;
try {
is = keystoreUrl.openStream();
keystore.load(is, null == password ? null : password.toCharArray());
} finally {
if (null != is) {
is.close();
}
}
return keystore;
}
static X509Certificate[] getCertificateChain(KeyStore keyStore) {
ArrayList<X509Certificate> certs = new ArrayList<>();
try {
Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
if (keyStore.isKeyEntry(alias)) {
Certificate[] certificateChain = keyStore.getCertificateChain(alias);
if (certificateChain != null) {
for (Certificate certificate : certificateChain) {
certs.add((X509Certificate) certificate);
}
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return certs.toArray(new X509Certificate[0]);
}
/**
* 获得KeyStore
*
* @param keyStorePath
* 密钥库路径
* @param password
* 密码
*
* @return KeyStore 密钥库
*
* @throws Exception
*/
static KeyStore getKeyStore(String keyStorePath, String password) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException {
// 实例化密钥库
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
// 获得密钥库文件流
FileInputStream is = new FileInputStream(keyStorePath);
// 加载密钥库
ks.load(is, password.toCharArray());
// 关闭密钥库文件流
is.close();
return ks;
}
public static HttpClient get() {
HttpParams httpParams = new BasicHttpParams();
ConnManagerParams.setTimeout(httpParams, 3000);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(30));
ConnManagerParams.setMaxTotalConnections(httpParams, 30);
HttpClientParams.setRedirecting(httpParams, true);
HttpProtocolParams.setUseExpectContinue(httpParams, true);
HttpConnectionParams.setStaleCheckingEnabled(httpParams, false);
HttpConnectionParams.setSoTimeout(httpParams, 2000);
HttpConnectionParams.setConnectionTimeout(httpParams, 2000);
HttpConnectionParams.setTcpNoDelay(httpParams, true);
HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTP_TAG, PlainSocketFactory.getSocketFactory(), 80));
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
schemeRegistry.register(new Scheme(IDataSource.SCHEME_HTTPS_TAG, sf, 443));
} catch (Exception ex) {
ex.printStackTrace();
}
return new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, schemeRegistry), httpParams);
}
private static KeyManagerFactory createKeyManagerFactory(
final String clientCertificateFileName, final String clientKeyFileName, final String clientKeyPassword)
throws InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException
{
// Creates a key manager factory
// Load and create the client certificate
final X509Certificate clientCertificate = createX509CertificateFromFile(clientCertificateFileName);
// Load the private client key
final PrivateKey privateKey = createPrivateKeyFromPemFile(clientKeyFileName);
// Client key and certificate are sent to server
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
keyStore.setCertificateEntry("certificate", clientCertificate);
keyStore.setKeyEntry("private-key", privateKey,
clientKeyPassword.toCharArray(),
new Certificate[] { clientCertificate });
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, clientKeyPassword.toCharArray());
return keyManagerFactory;
}
@Test
public void testTokenExpiredHasExpired()
throws InvalidKeySpecException, NoSuchAlgorithmException, Exception {
OpenIDConnectAuthenticator oidcAuth = new OpenIDConnectAuthenticator();
Map<String, Object> config = new HashMap<String, Object>();
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(new FileInputStream(OIDC_KS_PATH), OIDC_KS_PASSWORD);
String jwt =
TestUtils.generateJWT(
"someuser",
"https://some.domain.nowhere",
(PrivateKey) ks.getKey("oidc-sig", OIDC_KS_PASSWORD),
TestUtils.DateOptions.Past);
config.put(OpenIDConnectAuthenticator.OIDC_ID_TOKEN, jwt);
assertTrue(oidcAuth.isExpired(config));
}
public KeyPair getKeyPair(String alias, char[] password) {
try {
synchronized (lock) {
if (store == null) {
synchronized (lock) {
store = KeyStore.getInstance("jks");
store.load(resource.getInputStream(), this.password);
}
}
}
RSAPrivateCrtKey key = (RSAPrivateCrtKey) store.getKey(alias, password);
RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
return new KeyPair(publicKey, key);
}
catch (Exception e) {
throw new IllegalStateException("Cannot load keys from store: " + resource, e);
}
}
/**
* Checks if SSL certification is know and accepted by Java JRE.
*
* @param dayFromNow
* Checks expiration
* @return true Certification accepted, false No valid certification
* @throws Exception
*/
private static boolean checkServerCertValidity(final int daysFromNow) {
KeyStore keyStore;
try {
keyStore = KeyStore.getInstance(getTrustStoreType());
keyStore.load(new FileInputStream(getTrustStoreLocation()), (getTrustStorePwd() != null) ? getTrustStorePwd().toCharArray() : null);
final Enumeration<String> aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
final String alias = aliases.nextElement();
final Certificate cert = keyStore.getCertificate(alias);
if (cert instanceof X509Certificate) {
return isCertificateValid((X509Certificate) cert, daysFromNow);
}
}
} catch (final Exception e) {
return false;
}
return false;
}
@Test
public void testJWTx5tEncoding() throws Exception {
//Read public certificat
InputStream inputStream = new FileInputStream("src/test/resources/wso2carbon.jks");
KeyStore keystore = KeyStore.getInstance("JKS");
char[] pwd = "wso2carbon".toCharArray();
keystore.load(inputStream, pwd);
Certificate cert = keystore.getCertificate("wso2carbon");
//Generate JWT header using the above certificate
String header = APIUtil.generateHeader(cert, "SHA256withRSA");
//Get the public certificate's thumbprint and base64url encode it
byte[] der = cert.getEncoded();
MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
digestValue.update(der);
byte[] digestInBytes = digestValue.digest();
String publicCertThumbprint = hexify(digestInBytes);
String encodedThumbprint = java.util.Base64.getUrlEncoder()
.encodeToString(publicCertThumbprint.getBytes("UTF-8"));
//Check if the encoded thumbprint get matched with JWT header's x5t
Assert.assertTrue(header.contains(encodedThumbprint));
}
public static void main(String[] args) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream(
new File(System.getProperty("test.src"),
"../tools/jarsigner/JarSigning.keystore"));
ks.load(fis, "bbbbbb".toCharArray());
PrivateKey pk = (PrivateKey) ks.getKey("c", "bbbbbb".toCharArray());
Certificate cert = ks.getCertificate("c");
ks = KeyStore.getInstance("Windows-MY");
ks.load(null, null);
ks.setKeyEntry("8143913", pk, null, new Certificate[]{cert});
ks.deleteEntry("8143913");
}
/**
* Determines if the keystore {@code Entry} for the specified
* {@code alias} is an instance or subclass of the specified
* {@code entryClass}.
*
* @param alias the alias name
* @param entryClass the entry class
*
* @return true if the keystore {@code Entry} for the specified
* {@code alias} is an instance or subclass of the
* specified {@code entryClass}, false otherwise
*
* @since 1.5
*/
@Override
public boolean
engineEntryInstanceOf(String alias,
Class<? extends KeyStore.Entry> entryClass)
{
if (entryClass == KeyStore.TrustedCertificateEntry.class) {
return engineIsCertificateEntry(alias);
}
Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
if (entryClass == KeyStore.PrivateKeyEntry.class) {
return (entry != null && entry instanceof PrivateKeyEntry);
}
if (entryClass == KeyStore.SecretKeyEntry.class) {
return (entry != null && entry instanceof SecretKeyEntry);
}
return false;
}
@Test
public void testSignAndVerifyValid() throws Exception {
Protos.PaymentRequest.Builder paymentRequest = minimalPaymentRequest().toBuilder();
// Sign
KeyStore keyStore = X509Utils
.loadKeyStore("JKS", "password", getClass().getResourceAsStream("test-valid-cert"));
PrivateKey privateKey = (PrivateKey) keyStore.getKey("test-valid", "password".toCharArray());
X509Certificate clientCert = (X509Certificate) keyStore.getCertificate("test-valid");
PaymentProtocol.signPaymentRequest(paymentRequest, new X509Certificate[]{clientCert}, privateKey);
// Verify
PkiVerificationData verificationData = PaymentProtocol.verifyPaymentRequestPki(paymentRequest.build(), caStore);
assertNotNull(verificationData);
assertEquals(caCert, verificationData.rootAuthority.getTrustedCert());
}
/**
*
* @param pinNumber pin
* @param keyStoreType PKSC12 or JKS
* @return keystore
*/
private KeyStore getKeyStoreWithType(String pinNumber, String keyStoreType) {
KeyStore result = null;
try {
result = KeyStore.getInstance(keyStoreType);
char[] pwd = pinNumber == null ? null : pinNumber.toCharArray();
InputStream is = new FileInputStream(this.fileKeyStore);
result.load(is, pwd);
} catch (Throwable error) {
throw new KeyStoreLoaderException(coreMessagesBundle.getString("error.keystore.from.file"), error);
}
return result;
}
private SSLSocketFactory createSSLSocketFactory(final InputStream is, final String passphrase) throws Exception
{
final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(is, passphrase.toCharArray());
is.close();
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
final SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { defaultTrustManager}, null);
return context.getSocketFactory();
}
/**
* Creates the key managers required to initiate the {@link SSLContext}.
* @return {@link KeyManager} array that will be used to initiate the {@link SSLContext}.
* @throws Exception Key managers creation exception
*/
protected KeyManager[] createKeyManagers() throws Exception {
KeyStore keyStore = getProvider() == null ? KeyStore.getInstance(getKeyType()) : KeyStore.getInstance(getKeyType(), getProvider());
InputStream keyStoreIS = new FileInputStream(getKeystoreFilePath().toFile());
try {
keyStore.load(keyStoreIS, getKeystorePassword().toCharArray());
} finally {
if (keyStoreIS != null) {
keyStoreIS.close();
}
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, getKeyPassword().toCharArray());
return kmf.getKeyManagers();
}
public static KeyStore loadKeystore(final byte[] ksData, final String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
Preconditions.checkNotNull(ksData, "Keystore data cannot be null");
final KeyStore ks = KeyStore.getInstance("JKS");
try (final ByteArrayInputStream is = new ByteArrayInputStream(ksData)) {
ks.load(is, storePassword != null ? storePassword.toCharArray() : null);
}
return ks;
}
private static KeyStore readTestKeyStore() throws Exception {
File file = new File(System.getProperty("test.src", "."), "keystore");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(in, "passphrase".toCharArray());
in.close();
return ks;
}
public static KeyStore.Entry getKeyEntry(String keystorePath, String storePass, String keyName, String keyPass)
throws Exception {
char[] keyPw = null;
KeyStore.PasswordProtection passwordProtection = null;
try {
KeyStore ks = loadKeyStore(keystorePath, storePass);
keyPw = PasswordObfuscator.getInstance().decodeAliasPassword(keystorePath, keyName, keyPass);
passwordProtection = new KeyStore.PasswordProtection(keyPw);
return ks.getEntry(keyName, passwordProtection);
} finally {
if (keyPw != null) PasswordObfuscator.flush(keyPw);
if (passwordProtection != null) passwordProtection.destroy();
}
}
private void setFtpsUserKeyManagerOrTrustManager(
KeyStore keystore,
String fileConfigName,
String keyStorePassword,
boolean isKeyStore, // or truststore
List<Stage.ConfigIssue> issues,
ConfigIssueContext context,
Label group
) {
try {
if (isKeyStore) {
FtpsFileSystemConfigBuilder.getInstance().setKeyManager(
options,
KeyManagerUtils.createClientKeyManager(keystore, null, keyStorePassword)
);
} else {
FtpsFileSystemConfigBuilder.getInstance().setTrustManager(
options,
TrustManagerUtils.getDefaultTrustManager(keystore)
);
}
} catch (GeneralSecurityException e) {
issues.add(context.createConfigIssue(group.getLabel(),
fileConfigName,
Errors.REMOTE_15,
isKeyStore ? "key" : "trust",
e.getMessage(),
e
));
}
}
public int loadPKCS12Certificate(String filename, String ksPassword)
throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {
// Open the file
InputStream is = new FileInputStream(filename);
if (is == null)
throw new FileNotFoundException(filename + " could not be found");
// create the keystore
KeyStore ks = KeyStore.getInstance("PKCS12");
ks.load(is, ksPassword == null ? null : ksPassword.toCharArray());
return addKeyStore(ks, filename);
}
public static KeyStore getKeyStore() {
KeyStore ks = null;
try {
ks = KeyStore.getInstance("JKS");
ks.load(new ByteArrayInputStream(JKS_CERT_BYTES), getKeyStorePassword());
} catch (Exception ex) {
throw new RuntimeException("Failed to load SSL key store.", ex);
}
return ks;
}
public static KeyStore getComponentKeyStore(String componentName, String keyStoreName) throws IOException, GeneralSecurityException, GenericConfigException {
ComponentConfig.KeystoreInfo ks = ComponentConfig.getKeystoreInfo(componentName, keyStoreName);
// SCIPIO: Prevent confusing NPE
if (ks == null) {
throw new IOException("Could not get keystore info for given keystore; not found");
}
return getStore(ks.createResourceHandler().getURL(), ks.getPassword(), ks.getType());
}
public DataUnsealer initUnsealing() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, IntegrationModuleException {
Security.addProvider(new BouncyCastleProvider());
KeyStore caCertificatesKeystore = KeyManager.getKeyStore(this.getCaCertificateKeystoreIs(), this.propertyHandler.getProperty("LOCAL_CA_CERTIFICATES_STORE_TYPE"), this.propertyHandler.getProperty("CAKEYSTORE_PASSWORD").toCharArray());
Map<String, PrivateKey> clientDecryptionKeys = KeyManager.getDecryptionKeys(this.getKeyStore(), DEFAULT_PASSWORD);
Iterator var4 = clientDecryptionKeys.keySet().iterator();
while(var4.hasNext()) {
String key = (String)var4.next();
LOG.debug("Key Available for decryption : " + key);
}
DataUnsealer dataUnsealer = DataUnsealerBuilder.newBuilder().addOCSPPolicy(OCSPPolicy.NONE).addSigningPolicy(caCertificatesKeystore, SigningPolicy.EHEALTH_CERT, SigningPolicy.EID).addPublicKeyPolicy(EncryptionPolicy.KNOWN_RECIPIENT, EncryptionCredentials.from(clientDecryptionKeys)).build();
return dataUnsealer;
}
public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
{
TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
var4.init((KeyStore) null);
defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
this.localTrustManager = localTrustManager;
}
public static void main (String[] args) throws Exception {
SecretKey key = new SecretKeySpec(new byte[8], "DES");
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, passwd);
try {
// store the SecretKey
ks.setKeyEntry("test_encrypt_key", key, passwd, null);
throw new Exception("Should throw KeyStoreException when " +
"storing SecretKey into JKS keystores");
} catch (KeyStoreException kse) {
// expected exception thrown; swallow
}
}