List of usage examples for java.security.cert Certificate getPublicKey
public abstract PublicKey getPublicKey();
From source file:org.cesecore.util.PKIXCertRevocationStatusChecker.java
private boolean isIssuerCA(final Certificate cert, final Certificate cacert) { if (!StringUtils.equals(CertTools.getIssuerDN(cert), CertTools.getSubjectDN(cacert))) { return false; }//from w w w . ja v a2 s . c om try { cert.verify(cacert.getPublicKey()); return true; } catch (InvalidKeyException | CertificateException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException e) { return false; } }
From source file:org.ejbca.core.protocol.cmp.authentication.EndEntityCertificateAuthenticationModule.java
private boolean isExtraCertIssuedByCA(CAInfo cainfo) { //Check that the extraCert is given by the right CA // Verify the signature of the client certificate as well, that it is really issued by this CA Certificate cacert = cainfo.getCertificateChain().iterator().next(); try {/*w w w .jav a2s . c o m*/ extraCert.verify(cacert.getPublicKey(), "BC"); } catch (Exception e) { if (log.isDebugEnabled()) { String errmsg = "The End Entity certificate attached to the PKIMessage is not issued by the CA '" + cainfo.getName() + "'"; log.debug(errmsg + " - " + e.getLocalizedMessage()); } this.errorMessage = "The End Entity certificate attached to the PKIMessage is issued by the wrong CA"; return false; } return true; }
From source file:org.nuxeo.ecm.core.storage.sql.S3BinaryManager.java
@Override protected void setupCloudClient() throws IOException { // Get settings from the configuration bucketName = getProperty(BUCKET_NAME_PROPERTY); bucketNamePrefix = MoreObjects.firstNonNull(getProperty(BUCKET_PREFIX_PROPERTY), StringUtils.EMPTY); String bucketRegion = getProperty(BUCKET_REGION_PROPERTY); if (isBlank(bucketRegion)) { bucketRegion = DEFAULT_BUCKET_REGION; }/* w w w. j a v a 2s.c om*/ String awsID = getProperty(AWS_ID_PROPERTY); String awsSecret = getProperty(AWS_SECRET_PROPERTY); String proxyHost = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_HOST); String proxyPort = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PORT); String proxyLogin = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_LOGIN); String proxyPassword = Framework.getProperty(Environment.NUXEO_HTTP_PROXY_PASSWORD); int maxConnections = getIntProperty(CONNECTION_MAX_PROPERTY); int maxErrorRetry = getIntProperty(CONNECTION_RETRY_PROPERTY); int connectionTimeout = getIntProperty(CONNECTION_TIMEOUT_PROPERTY); int socketTimeout = getIntProperty(SOCKET_TIMEOUT_PROPERTY); String keystoreFile = getProperty(KEYSTORE_FILE_PROPERTY); String keystorePass = getProperty(KEYSTORE_PASS_PROPERTY); String privkeyAlias = getProperty(PRIVKEY_ALIAS_PROPERTY); String privkeyPass = getProperty(PRIVKEY_PASS_PROPERTY); String endpoint = getProperty(ENDPOINT_PROPERTY); String sseprop = getProperty(SERVERSIDE_ENCRYPTION_PROPERTY); if (isNotBlank(sseprop)) { userServerSideEncryption = Boolean.parseBoolean(sseprop); } // Fallback on default env keys for ID and secret if (isBlank(awsID)) { awsID = System.getenv(AWS_ID_ENV); } if (isBlank(awsSecret)) { awsSecret = System.getenv(AWS_SECRET_ENV); } if (isBlank(bucketName)) { throw new RuntimeException("Missing conf: " + BUCKET_NAME_PROPERTY); } if (!isBlank(bucketNamePrefix) && !bucketNamePrefix.endsWith("/")) { log.warn(String.format("%s %s S3 bucket prefix should end by '/' " + ": added automatically.", BUCKET_PREFIX_PROPERTY, bucketNamePrefix)); bucketNamePrefix += "/"; } // set up credentials if (isBlank(awsID) || isBlank(awsSecret)) { awsCredentialsProvider = new InstanceProfileCredentialsProvider(); try { awsCredentialsProvider.getCredentials(); } catch (AmazonClientException e) { throw new RuntimeException("Missing AWS credentials and no instance role found"); } } else { awsCredentialsProvider = new BasicAWSCredentialsProvider(awsID, awsSecret); } // set up client configuration clientConfiguration = new ClientConfiguration(); if (isNotBlank(proxyHost)) { clientConfiguration.setProxyHost(proxyHost); } if (isNotBlank(proxyPort)) { clientConfiguration.setProxyPort(Integer.parseInt(proxyPort)); } if (isNotBlank(proxyLogin)) { clientConfiguration.setProxyUsername(proxyLogin); } if (proxyPassword != null) { // could be blank clientConfiguration.setProxyPassword(proxyPassword); } if (maxConnections > 0) { clientConfiguration.setMaxConnections(maxConnections); } if (maxErrorRetry >= 0) { // 0 is allowed clientConfiguration.setMaxErrorRetry(maxErrorRetry); } if (connectionTimeout >= 0) { // 0 is allowed clientConfiguration.setConnectionTimeout(connectionTimeout); } if (socketTimeout >= 0) { // 0 is allowed clientConfiguration.setSocketTimeout(socketTimeout); } // set up encryption encryptionMaterials = null; if (isNotBlank(keystoreFile)) { boolean confok = true; if (keystorePass == null) { // could be blank log.error("Keystore password missing"); confok = false; } if (isBlank(privkeyAlias)) { log.error("Key alias missing"); confok = false; } if (privkeyPass == null) { // could be blank log.error("Key password missing"); confok = false; } if (!confok) { throw new RuntimeException("S3 Crypto configuration incomplete"); } try { // Open keystore File ksFile = new File(keystoreFile); FileInputStream ksStream = new FileInputStream(ksFile); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(ksStream, keystorePass.toCharArray()); ksStream.close(); // Get keypair for alias if (!keystore.isKeyEntry(privkeyAlias)) { throw new RuntimeException("Alias " + privkeyAlias + " is missing or not a key alias"); } PrivateKey privKey = (PrivateKey) keystore.getKey(privkeyAlias, privkeyPass.toCharArray()); Certificate cert = keystore.getCertificate(privkeyAlias); PublicKey pubKey = cert.getPublicKey(); KeyPair keypair = new KeyPair(pubKey, privKey); // Get encryptionMaterials from keypair encryptionMaterials = new EncryptionMaterials(keypair); cryptoConfiguration = new CryptoConfiguration(); } catch (IOException | GeneralSecurityException e) { throw new RuntimeException("Could not read keystore: " + keystoreFile + ", alias: " + privkeyAlias, e); } } isEncrypted = encryptionMaterials != null; // Try to create bucket if it doesn't exist if (!isEncrypted) { amazonS3 = new AmazonS3Client(awsCredentialsProvider, clientConfiguration); } else { amazonS3 = new AmazonS3EncryptionClient(awsCredentialsProvider, new StaticEncryptionMaterialsProvider(encryptionMaterials), clientConfiguration, cryptoConfiguration); } if (isNotBlank(endpoint)) { amazonS3.setEndpoint(endpoint); } // Set region explicitely for regions that reguire Version 4 signature ArrayList<String> V4_ONLY_REGIONS = new ArrayList<String>(); V4_ONLY_REGIONS.add("eu-central-1"); V4_ONLY_REGIONS.add("ap-northeast-2"); if (V4_ONLY_REGIONS.contains(bucketRegion)) { amazonS3.setRegion(Region.getRegion(Regions.fromName(bucketRegion))); } try { if (!amazonS3.doesBucketExist(bucketName)) { amazonS3.createBucket(bucketName, bucketRegion); amazonS3.setBucketAcl(bucketName, CannedAccessControlList.Private); } } catch (AmazonClientException e) { throw new IOException(e); } // compat for NXP-17895, using "downloadfroms3", to be removed // these two fields have already been initialized by the base class initialize() // using standard property "directdownload" String dd = getProperty(DIRECTDOWNLOAD_PROPERTY_COMPAT); if (dd != null) { directDownload = Boolean.parseBoolean(dd); } int dde = getIntProperty(DIRECTDOWNLOAD_EXPIRE_PROPERTY_COMPAT); if (dde >= 0) { directDownloadExpire = dde; } transferManager = new TransferManager(amazonS3); abortOldUploads(); }
From source file:org.cesecore.keys.key.management.CertificateKeyAssociationSessionBean.java
@Override public void bindCertificateToKey(final AuthenticationToken adminUserForAudit, final CryptoToken cryptoToken, final Certificate certificate, final List<String> tags, final String keyLabel) throws CertificateKeyAssociationException { if (log.isTraceEnabled()) { log.trace(String.format(">bindCertificateToKey cert: %s, key:%s, tags:", CertTools.getSubjectDN(certificate), keyLabel, StringUtils.join(tags, ","))); }//from ww w .j ava 2 s .c o m Map<String, Object> details = new LinkedHashMap<String, Object>(); details.put("fingerprint", CertTools.getFingerprintAsString(certificate)); details.put("keylabel", keyLabel); try { final PrivateKey privateKey = cryptoToken.getPrivateKey(keyLabel); final PublicKey certificatePublicKey = certificate.getPublicKey(); KeyTools.testKey(privateKey, certificatePublicKey, cryptoToken.getSignProviderName()); } catch (final CryptoTokenOfflineException e) { securityLogger.log(EventTypes.CERTIFICATE_KEY_BIND, EventStatus.FAILURE, ModuleTypes.KEY_MANAGEMENT, ServiceTypes.CORE, adminUserForAudit.toString(), null, null, null, details); throw new CertificateKeyAssociationException(e.getMessage(), e); } catch (final InvalidKeyException e) { securityLogger.log(EventTypes.CERTIFICATE_KEY_BIND, EventStatus.FAILURE, ModuleTypes.KEY_MANAGEMENT, ServiceTypes.CORE, adminUserForAudit.toString(), null, null, null, details); throw new CertificateKeyAssociationException(e.getMessage(), e); } catch (final NoSuchProviderException e) { securityLogger.log(EventTypes.CERTIFICATE_KEY_BIND, EventStatus.FAILURE, ModuleTypes.KEY_MANAGEMENT, ServiceTypes.CORE, adminUserForAudit.toString(), null, null, null, details); throw new CertificateKeyAssociationException(e.getMessage(), e); } final CertificateKeyAssociationData cka = new CertificateKeyAssociationData(certificate, tags, keyLabel); em.persist(cka); securityLogger.log(EventTypes.CERTIFICATE_KEY_BIND, EventStatus.SUCCESS, ModuleTypes.KEY_MANAGEMENT, ServiceTypes.CORE, adminUserForAudit.toString(), null, null, null, details); if (log.isTraceEnabled()) { log.trace("<bindCertificateToKey"); } }
From source file:org.cesecore.keys.token.BaseCryptoToken.java
/** * Reads the public key object, does so from the certificate retrieved from the alias from the KeyStore. * * @param alias alias the key alias to retrieve from the token * @param warn if we should log a warning if the key does not exist * @return the public key for the certificate represented by the given alias. * @throws KeyStoreException if the keystore has not been initialized. * @throws CryptoTokenOfflineException if Crypto Token is not available or connected. *///from w ww . ja va2 s . c o m protected PublicKey readPublicKey(String alias, boolean warn) throws KeyStoreException, CryptoTokenOfflineException { try { Certificate cert = getKeyStore().getCertificate(alias); PublicKey pubk = null; if (cert != null) { pubk = cert.getPublicKey(); } else if (warn) { log.warn(intres.getLocalizedMessage("token.nopublic", alias)); if (log.isDebugEnabled()) { Enumeration<String> en = getKeyStore().aliases(); while (en.hasMoreElements()) { log.debug("Existing alias: " + en.nextElement()); } } } return pubk; } catch (ProviderException e) { throw new CryptoTokenOfflineException(e); } }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoToken.java
@Override public PublicKey getPublicKey(int purpose) throws CryptoTokenOfflineException { final Certificate cert = getKeyEntry(purpose).getCertificate(); return cert.getPublicKey(); }
From source file:org.wso2.carbon.identity.openidconnect.RequestObjectValidatorImpl.java
/** * Validate the signedJWT signature with given certificate * * @param signedJWT// ww w . j av a 2s .com * @param x509Certificate * @return */ protected boolean isSignatureVerified(SignedJWT signedJWT, Certificate x509Certificate) { JWSVerifier verifier; JWSHeader header = signedJWT.getHeader(); if (x509Certificate == null) { return logAndReturnFalse("Unable to locate certificate for JWT " + header.toString()); } String alg = signedJWT.getHeader().getAlgorithm().getName(); if (log.isDebugEnabled()) { log.debug("Signature Algorithm found in the JWT Header: " + alg); } if (alg.indexOf(RS) == 0) { // At this point 'x509Certificate' will never be null. PublicKey publicKey = x509Certificate.getPublicKey(); if (publicKey instanceof RSAPublicKey) { verifier = new RSASSAVerifier((RSAPublicKey) publicKey); } else { return logAndReturnFalse("Public key is not an RSA public key."); } } else { return logAndReturnFalse("Signature Algorithm not supported yet : " + alg); } // At this point 'verifier' will never be null; try { return signedJWT.verify(verifier); } catch (JOSEException e) { return logAndReturnFalse( "Unable to verify the signature of the request object: " + signedJWT.serialize()); } }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java
private List<Map<String, Object>> getKeyStoreInfo(KeyStore store) { List<Map<String, Object>> storeEntries = new ArrayList<>(); try {//from w w w .jav a 2s . c om Enumeration<String> aliases = store.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Map<String, Object> aliasMap = new HashMap<>(); Certificate certificate = store.getCertificate(alias); boolean isKey = store.isKeyEntry(alias); aliasMap.put("alias", alias); aliasMap.put("isKey", isKey); aliasMap.put("type", certificate.getType()); aliasMap.put("format", certificate.getPublicKey().getFormat()); aliasMap.put("algorithm", certificate.getPublicKey().getAlgorithm()); storeEntries.add(aliasMap); } } catch (KeyStoreException e) { LOGGER.error("Unable to read entries from keystore.", e); } return storeEntries; }
From source file:com.google.appengine.tck.appidentity.AppIdentityServiceTest.java
private boolean verifySignatureWithAllCertsForApp(byte[] blob, byte[] signedBlob, Collection<PublicCertificate> certsForApp) { if (certsForApp.isEmpty()) { throw new IllegalStateException("No certificates to validate. Must have at least 1."); }// w ww . ja v a 2 s .c om int currentCertNum = 0; int totalValid = 0; int totalInvalid = 0; List<Exception> allExceptions = new ArrayList<>(); for (PublicCertificate publicCert : certsForApp) { Signature signature; Certificate cert = null; currentCertNum++; log.info("Processing certNum:" + currentCertNum); try { byte[] certBytes = publicCert.getX509CertificateInPemFormat().getBytes("UTF-8"); InputStream stream = new ByteArrayInputStream(certBytes); signature = Signature.getInstance("SHA256withRSA"); // Make this configurable? CertificateFactory cf = CertificateFactory.getInstance("X.509"); cert = cf.generateCertificate(stream); log.info(cert.toString()); PublicKey pk = cert.getPublicKey(); signature.initVerify(pk); signature.update(blob); boolean isValidSignature = signature.verify(signedBlob); if (isValidSignature) { totalValid++; } else { totalInvalid++; } log.info("certNum:" + currentCertNum + ": is valid:" + isValidSignature); // These can be thrown: // UnsupportedEncodingException, NoSuchAlgorithmException, CertificateException, // SignatureException, InvalidKeyException } catch (Exception e) { Exception logException = createExceptionForLog(e, currentCertNum, cert); allExceptions.add(logException); log.info(e.toString()); } } String summary = "totalCerts:" + certsForApp.size() + ": totalValid:" + totalValid + " totalInvalid:" + totalInvalid + " totalExceptions:" + allExceptions.size(); log.info(summary); // At least one certificate caused an exception so make test Error. if (allExceptions.size() > 0) { throw new IllegalStateException(summary + "\n\n" + exceptionListToString(allExceptions)); } // At least one signature was valid and no exceptions thrown. return (totalValid > 0); }
From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java
/** * Returns a JsonValue map representing a certificate * //from www. j a v a 2 s. co m * @param alias the certificate alias * @param cert The certificate * @return a JsonValue map representing the certificate * @throws Exception */ protected JsonValue returnCertificate(String alias, Certificate cert) throws Exception { JsonValue content = new JsonValue(new LinkedHashMap<String, Object>()); content.put(ResourceResponse.FIELD_CONTENT_ID, alias); content.put("type", cert.getType()); content.put("cert", getCertString(cert)); content.put("publicKey", getKeyMap(cert.getPublicKey())); if (cert instanceof X509Certificate) { Map<String, Object> issuer = new HashMap<>(); X500Name name = X500Name.getInstance(PrincipalUtil.getIssuerX509Principal((X509Certificate) cert)); addAttributeToIssuer(issuer, name, "C", BCStyle.C); addAttributeToIssuer(issuer, name, "ST", BCStyle.ST); addAttributeToIssuer(issuer, name, "L", BCStyle.L); addAttributeToIssuer(issuer, name, "OU", BCStyle.OU); addAttributeToIssuer(issuer, name, "O", BCStyle.O); addAttributeToIssuer(issuer, name, "CN", BCStyle.CN); content.put("issuer", issuer); content.put("notBefore", ((X509Certificate) cert).getNotBefore()); content.put("notAfter", ((X509Certificate) cert).getNotAfter()); } return content; }