List of usage examples for java.security.cert X509Certificate getSignature
public abstract byte[] getSignature();
From source file:MainClass.java
public static void main(String args[]) throws Exception { CertificateFactory cf = CertificateFactory.getInstance("X.509"); FileInputStream in = new FileInputStream(args[0]); java.security.cert.Certificate c = cf.generateCertificate(in); in.close();/* w ww .j a v a 2s .co m*/ X509Certificate t = (X509Certificate) c; System.out.println(t.getVersion()); System.out.println(t.getSerialNumber().toString(16)); System.out.println(t.getSubjectDN()); System.out.println(t.getIssuerDN()); System.out.println(t.getNotBefore()); System.out.println(t.getNotAfter()); System.out.println(t.getSigAlgName()); byte[] sig = t.getSignature(); System.out.println(new BigInteger(sig).toString(16)); PublicKey pk = t.getPublicKey(); byte[] pkenc = pk.getEncoded(); for (int i = 0; i < pkenc.length; i++) { System.out.print(pkenc[i] + ","); } }
From source file:org.brekka.pegasus.core.services.impl.CertificateAuthenticationServiceImpl.java
@Override @Transactional()/*w w w. j a v a2 s .com*/ public DigitalCertificate authenticate(X509Certificate certificate) throws BadCredentialsException, DisabledException { byte[] signature = certificate.getSignature(); String subjectDN = certificate.getSubjectDN().getName(); String commonName = null; Matcher matcher = matchAllowedSubjectDN(subjectDN, allowedSubjectDistinguishedNamePatterns); if (matcher.groupCount() > 0) { commonName = matcher.group(1); } byte[] subjectDNBytes = subjectDN.getBytes(Charset.forName("UTF-8")); SystemDerivedKeySpecType spec = config.getSubjectDerivedKeySpec(); DerivedKey derivedKey = derivedKeyCryptoService.apply(subjectDNBytes, spec.getSalt(), null, CryptoProfile.Static.of(spec.getCryptoProfile())); byte[] distinguishedNameDigest = derivedKey.getDerivedKey(); CertificateSubject certificateSubject = certificateSubjectDAO .retrieveByDistinguishedNameDigest(distinguishedNameDigest); if (certificateSubject == null) { // Create it certificateSubject = new CertificateSubject(); certificateSubject.setDistinguishedNameDigest(distinguishedNameDigest); certificateSubjectDAO.create(certificateSubject); } DigitalCertificate digitalCertificate = digitalCertificateDAO .retrieveBySubjectAndSignature(certificateSubject, signature); if (digitalCertificate == null) { digitalCertificate = new DigitalCertificate(); digitalCertificate.setActive(Boolean.TRUE); digitalCertificate.setCertificateSubject(certificateSubject); digitalCertificate.setCreated(certificate.getNotBefore()); digitalCertificate.setExpires(certificate.getNotAfter()); digitalCertificate.setSignature(signature); digitalCertificateDAO.create(digitalCertificate); } // Perform some checks if (BooleanUtils.isNotTrue(digitalCertificate.getActive())) { throw new DisabledException( String.format("The certficate with id '%s' has been disabled", digitalCertificate.getId())); } if (digitalCertificate.getExpires().before(new Date())) { throw new CredentialsExpiredException(String.format("The certficate with id '%s' expired %tF", digitalCertificate.getId(), digitalCertificate.getExpires())); } // Both of these are transient certificateSubject.setCommonName(commonName); certificateSubject.setDistinguishedName(subjectDN); return digitalCertificate; }
From source file:com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java
public String getFingerprint() { X509Certificate cert = getCertificateList().get(0); return new String(cert.getSignature()); }
From source file:eu.europa.esig.dss.x509.CertificatePool.java
/** * This method returns the instance of a {@link CertificateToken} corresponding to the given {@link X509Certificate}. * If the given certificate is not yet present in the pool it will added. If the {@link CertificateToken} exists * already in the pool but has no {@link ServiceInfo} this reference will be added. * * @param certificateToAdd//from w w w . j ava2 s .co m * @param sources * @param services * @return */ public CertificateToken getInstance(final CertificateToken certificateToAdd, final Set<CertificateSourceType> sources, final Set<ServiceInfo> services) { if (certificateToAdd == null) { throw new NullPointerException("The certificate must be filled"); } if (CollectionUtils.isEmpty(sources)) { throw new IllegalStateException("The certificate source type must be set."); } if (LOG.isTraceEnabled()) { LOG.trace("Certificate to add: " + certificateToAdd.getIssuerX500Principal() + "|" + certificateToAdd.getSerialNumber()); } final TokenIdentifier id = certificateToAdd.getDSSId(); synchronized (certById) { CertificateToken certToken = certById.get(id); if (certToken == null) { LOG.debug("Certificate " + id + " is not in the pool"); certToken = certificateToAdd; certById.put(id, certToken); final String subjectName = certificateToAdd.getSubjectX500Principal() .getName(X500Principal.CANONICAL); List<CertificateToken> list = certBySubject.get(subjectName); if (list == null) { list = new ArrayList<CertificateToken>(); certBySubject.put(subjectName, list); } list.add(certToken); } else { LOG.debug("Certificate " + id + " is already in the pool"); final X509Certificate foundCertificate = certToken.getCertificate(); final byte[] foundCertificateSignature = foundCertificate.getSignature(); final byte[] certificateToAddSignature = certificateToAdd.getSignature(); if (!Arrays.equals(foundCertificateSignature, certificateToAddSignature)) { LOG.warn(" Found certificate: " + certToken.getIssuerX500Principal().toString() + "|" + certToken.getSerialNumber()); LOG.warn( "More than one certificate for the same issuer subject name and serial number! The standard is not met by the certificate issuer!"); } } for (final CertificateSourceType sourceType : sources) { certToken.addSourceType(sourceType); } if (services != null) { for (final ServiceInfo serviceInfo : services) { certToken.addServiceInfo(serviceInfo); } } return certToken; } }
From source file:com.archivas.clienttools.arcutils.utils.net.SSLCertChain.java
public String getSignatureString() { X509Certificate cert = getCertificateList().get(0); return byteArrayToColonSeparatedHexString(cert.getSignature(), ":"); }
From source file:com.xwiki.authentication.sts.STSTokenValidator.java
/** * validateToken(SignableSAMLObject samlToken) * Validates Token from SAMLlObject - returns boolen * Validates Token - exitracting sertificate from samlToken. * And validates it. Returning true or false according on validation results. * @param samlToken SignableSAMLObject/*w w w .java 2 s . co m*/ * @return boolean valid => true, not valid => false */ private static boolean validateToken(SignableSAMLObject samlToken) throws SecurityException, ValidationException, ConfigurationException, UnmarshallingException, CertificateException, KeyException { // Validate XML structure samlToken.validate(true); Signature signature = samlToken.getSignature(); X509Certificate certificate = certFromToken(samlToken); // Certificate data log.debug("certificate issuerDN: " + certificate.getIssuerDN()); log.debug("certificate issuerUniqueID: " + certificate.getIssuerUniqueID()); log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal()); log.debug("certificate notBefore: " + certificate.getNotBefore()); log.debug("certificate notAfter: " + certificate.getNotAfter()); log.debug("certificate serialNumber: " + certificate.getSerialNumber()); log.debug("certificate sigAlgName: " + certificate.getSigAlgName()); log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID()); log.debug("certificate signature: " + new String(certificate.getSignature())); log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal().toString()); log.debug("certificate publicKey: " + certificate.getPublicKey()); log.debug("certificate subjectDN: " + certificate.getSubjectDN()); log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID()); log.debug("certificate version: " + certificate.getVersion()); BasicX509Credential cred = new BasicX509Credential(); cred.setEntityCertificate(certificate); // Credential data cred.setEntityId(entityId); log.debug("cred entityId: " + cred.getEntityId()); log.debug("cred usageType: " + cred.getUsageType()); log.debug("cred credentalContextSet: " + cred.getCredentalContextSet()); log.debug("cred hashCode: " + cred.hashCode()); log.debug("cred privateKey: " + cred.getPrivateKey()); log.debug("cred publicKey: " + cred.getPublicKey()); log.debug("cred secretKey: " + cred.getSecretKey()); log.debug("cred entityCertificateChain: " + cred.getEntityCertificateChain()); ArrayList<Credential> trustedCredentials = new ArrayList<Credential>(); trustedCredentials.add(cred); CollectionCredentialResolver credResolver = new CollectionCredentialResolver(trustedCredentials); KeyInfoCredentialResolver kiResolver = SecurityTestHelper.buildBasicInlineKeyInfoResolver(); ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver); CriteriaSet criteriaSet = new CriteriaSet(); criteriaSet.add(new EntityIDCriteria(entityId)); Base64 decoder = new Base64(); // In trace mode write certificate in the file if (log.isTraceEnabled()) { String certEncoded = new String(decoder.encode(certificate.getEncoded())); try { FileUtils.writeStringToFile(new File("/tmp/Certificate.cer"), "-----BEGIN CERTIFICATE-----\n" + certEncoded + "\n-----END CERTIFICATE-----"); log.trace("Certificate file was saved in: /tmp/Certificate.cer"); } catch (IOException e1) { log.error(e1); } } return engine.validate(signature, criteriaSet); }
From source file:com.vmware.bdd.cli.http.DefaultTrustManager.java
@Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { String errorMsg = ""; InputStream in = null;// w w w. j av a 2 s .com OutputStream out = null; // load key store file try { char[] pwd = cliProperties.readKeyStorePwd(); File file = new File(KEY_STORE_FILE); if (file.exists() && file.isFile()) { keyStore.load(new FileInputStream(file), pwd); } else { //init an empty keystore keyStore.load(null, pwd); } // show certificate informations MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); String md5Fingerprint = ""; String sha1Fingerprint = ""; SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy/MM/dd"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; sha1.update(cert.getEncoded()); md5.update(cert.getEncoded()); md5Fingerprint = ByteArrayUtils.byteArrayToHexString(md5.digest()); sha1Fingerprint = ByteArrayUtils.byteArrayToHexString(sha1.digest()); if (keyStore.getCertificate(md5Fingerprint) != null) { if (i == chain.length - 1) { return; } else { continue; } } System.out.println(); System.out.println("Server Certificate"); System.out.println("================================================================"); System.out.println("Subject: " + cert.getSubjectDN()); System.out.println("Issuer: " + cert.getIssuerDN()); System.out.println("SHA Fingerprint: " + sha1Fingerprint); System.out.println("MD5 Fingerprint: " + md5Fingerprint); System.out.println("Issued on: " + dateFormate.format(cert.getNotBefore())); System.out.println("Expires on: " + dateFormate.format(cert.getNotAfter())); System.out.println("Signature: " + cert.getSignature()); System.out.println(); if (checkExpired(cert.getNotBefore(), cert.getNotAfter())) { throw new CertificateException("The security certificate has expired."); } ConsoleReader reader = new ConsoleReader(); // Set prompt message reader.setPrompt(Constants.PARAM_PROMPT_ADD_CERTIFICATE_MESSAGE); // Read user input String readMsg; if (RunWayConfig.getRunType().equals(RunWayConfig.RunType.MANUAL)) { readMsg = reader.readLine().trim(); } else { readMsg = "yes"; } if ("yes".equalsIgnoreCase(readMsg) || "y".equalsIgnoreCase(readMsg)) { { // add new certificate into key store file. keyStore.setCertificateEntry(md5Fingerprint, cert); out = new FileOutputStream(KEY_STORE_FILE); keyStore.store(out, pwd); CommonUtil.setOwnerOnlyReadWrite(KEY_STORE_FILE); // save keystore password cliProperties.saveKeyStorePwd(pwd); } } else { if (i == chain.length - 1) { throw new CertificateException("Could not find a valid certificate in the keystore."); } else { continue; } } } } catch (FileNotFoundException e) { errorMsg = "Cannot find the keystore file: " + e.getMessage(); } catch (NoSuchAlgorithmException e) { errorMsg = "SSL Algorithm not supported: " + e.getMessage(); } catch (IOException e) { e.printStackTrace(); errorMsg = "IO error: " + e.getMessage(); } catch (KeyStoreException e) { errorMsg = "Keystore error: " + e.getMessage(); } catch (ConfigurationException e) { errorMsg = "cli.properties access error: " + e.getMessage(); } finally { if (!CommandsUtils.isBlank(errorMsg)) { System.out.println(errorMsg); logger.error(errorMsg); } if (in != null) { try { in.close(); } catch (IOException e) { logger.warn("Input stream of serengeti.keystore close failed."); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.warn("Output stream of serengeti.keystore close failed."); } } } }
From source file:org.syncany.plugins.webdav.WebdavTransferManager.java
private ConnectionSocketFactory initSsl() throws Exception { TrustStrategy trustStrategy = new TrustStrategy() { @Override/*from w ww . j a v a 2s .c o m*/ public boolean isTrusted(X509Certificate[] certificateChain, String authType) throws CertificateException { logger.log(Level.INFO, "WebDAV: isTrusted(" + certificateChain.toString() + ", " + authType + ")"); try { // First check if already in trust store, if so; okay! X509Certificate serverCertificate = certificateChain[0]; for (int i = 0; i < certificateChain.length; i++) { X509Certificate certificate = certificateChain[i]; logger.log(Level.FINE, "WebDAV: Checking certificate validity: " + certificate.getSubjectDN().toString()); logger.log(Level.FINEST, "WebDAV: Full certificate: " + certificate); // Check validity try { certificate.checkValidity(); } catch (CertificateException e) { logger.log(Level.FINE, "WebDAV: Certificate is NOT valid.", e); return false; } logger.log(Level.FINE, "WebDAV: Checking is VALID."); // Certificate found; we trust this, okay! if (inTrustStore(certificate)) { logger.log(Level.FINE, "WebDAV: Certificate found in trust store."); return true; } // Certificate is new; continue ... else { logger.log(Level.FINE, "WebDAV: Certificate NOT found in trust store."); } } // We we reach this code, none of the CAs are known in the trust store // So we ask the user if he/she wants to add the server certificate to the trust store UserInteractionListener userInteractionListener = getSettings().getUserInteractionListener(); if (userInteractionListener == null) { throw new RuntimeException("pluginListener cannot be null!"); } boolean userTrustsCertificate = userInteractionListener.onUserConfirm( "Unknown SSL/TLS certificate", formatCertificate(serverCertificate), "Do you want to trust this certificate?"); if (!userTrustsCertificate) { logger.log(Level.INFO, "WebDAV: User does not trust certificate. ABORTING."); throw new RuntimeException("User does not trust certificate. ABORTING."); } logger.log(Level.INFO, "WebDAV: User trusts certificate. Adding to trust store."); addToTrustStore(serverCertificate); return true; } catch (KeyStoreException e) { logger.log(Level.SEVERE, "WebDAV: Key store exception.", e); return false; } } private boolean inTrustStore(X509Certificate certificate) throws KeyStoreException { String certAlias = getCertificateAlias(certificate); return UserConfig.getUserTrustStore().containsAlias(certAlias); } private void addToTrustStore(X509Certificate certificate) throws KeyStoreException { String certAlias = getCertificateAlias(certificate); UserConfig.getUserTrustStore().setCertificateEntry(certAlias, certificate); hasNewCertificates = true; } private String getCertificateAlias(X509Certificate certificate) { return StringUtil.toHex(certificate.getSignature()); } }; SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustStrategy).useTLS().build(); return new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier()); }
From source file:org.apache.directory.studio.connection.ui.widgets.CertificateInfoComposite.java
private void populateCertificateTree() { certificateTree.removeAll();// w w w.j a v a 2s . c om valueText.setText(StringUtils.EMPTY); IStructuredSelection selection = (IStructuredSelection) hierarchyTreeViewer.getSelection(); if (selection.size() != 1) { return; } CertificateChainItem certificateItem = (CertificateChainItem) selection.getFirstElement(); X509Certificate certificate = certificateItem.certificate; TreeItem rootItem = new TreeItem(certificateTree, SWT.NONE); Map<String, String> attributeMap = getAttributeMap(certificate.getSubjectX500Principal()); rootItem.setText(attributeMap.get("CN")); //$NON-NLS-1$ TreeItem certItem = createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Certificate"), //$NON-NLS-1$ StringUtils.EMPTY); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Version"), //$NON-NLS-1$ String.valueOf(certificate.getVersion())); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.SerialNumber"), //$NON-NLS-1$ certificate.getSerialNumber().toString(16)); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$ certificate.getSigAlgName()); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Issuer"), //$NON-NLS-1$ certificate.getIssuerX500Principal().getName()); TreeItem validityItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Validity"), //$NON-NLS-1$ StringUtils.EMPTY); createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotBefore"), //$NON-NLS-1$ certificate.getNotBefore().toString()); createTreeItem(validityItem, Messages.getString("CertificateInfoComposite.NotAfter"), //$NON-NLS-1$ certificate.getNotAfter().toString()); createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Subject"), //$NON-NLS-1$ certificate.getSubjectX500Principal().getName()); TreeItem pkiItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.SubjectPublicKeyInfo"), StringUtils.EMPTY); //$NON-NLS-1$ createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKeyAlgorithm"), //$NON-NLS-1$ certificate.getPublicKey().getAlgorithm()); createTreeItem(pkiItem, Messages.getString("CertificateInfoComposite.SubjectPublicKey"), //$NON-NLS-1$ new String(Hex.encodeHex(certificate.getPublicKey().getEncoded()))); TreeItem extItem = createTreeItem(certItem, Messages.getString("CertificateInfoComposite.Extensions"), //$NON-NLS-1$ StringUtils.EMPTY); populateExtensions(extItem, certificate, true); populateExtensions(extItem, certificate, false); createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.SignatureAlgorithm"), //$NON-NLS-1$ certificate.getSigAlgName()); createTreeItem(rootItem, Messages.getString("CertificateInfoComposite.Signature"), //$NON-NLS-1$ new String(Hex.encodeHex(certificate.getSignature()))); rootItem.setExpanded(true); certItem.setExpanded(true); validityItem.setExpanded(true); pkiItem.setExpanded(true); extItem.setExpanded(true); }
From source file:org.apache.hadoop.yarn.server.resourcemanager.security.MockX509SecurityHandler.java
private void verifyContentOfAppTrustStore(byte[] appTrustStore, char[] password, String appUser, ApplicationId appId) throws GeneralSecurityException, IOException { File trustStoreFile = Paths.get(systemTMP, appUser + "-" + appId.toString() + "_tstore.jks").toFile(); boolean certificateMissing = false; try {/*from ww w . ja v a 2s . c om*/ KeyStore systemTrustStore = loadSystemTrustStore(getConfig()); FileUtils.writeByteArrayToFile(trustStoreFile, appTrustStore, false); KeyStore ts = KeyStore.getInstance("JKS"); try (FileInputStream fis = new FileInputStream(trustStoreFile)) { ts.load(fis, password); } Enumeration<String> sysAliases = systemTrustStore.aliases(); while (sysAliases.hasMoreElements()) { String alias = sysAliases.nextElement(); X509Certificate appCert = (X509Certificate) ts.getCertificate(alias); if (appCert == null) { certificateMissing = true; break; } X509Certificate sysCert = (X509Certificate) systemTrustStore.getCertificate(alias); if (!Arrays.equals(sysCert.getSignature(), appCert.getSignature())) { certificateMissing = true; break; } } } finally { FileUtils.deleteQuietly(trustStoreFile); assertFalse(certificateMissing); } }