List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:org.apli.modelbeans.facturacion.cfdi.CFDv32.java
@Override public void sellar(PrivateKey key, X509Certificate cert) throws Exception { cert.checkValidity();/*from www. jav a 2 s.c o m*/ String signature = getSignature(key); document.setSello(signature); byte[] bytes = cert.getEncoded(); Base64 b64 = new Base64(-1); String certStr = b64.encodeToString(bytes); document.setCertificado(certStr); BigInteger bi = cert.getSerialNumber(); document.setNoCertificado(new String(bi.toByteArray())); }
From source file:org.votingsystem.web.ejb.SignatureBean.java
public CertUtils.CertValidatorResultVS verifyUserCertificate(UserVS userVS) throws Exception { CertUtils.CertValidatorResultVS validatorResult = CertUtils.verifyCertificate(getTrustAnchors(), false, Arrays.asList(userVS.getCertificate())); X509Certificate certCaResult = validatorResult.getResult().getTrustAnchor().getTrustedCert(); userVS.setCertificateCA(getTrustedCertsHashMap().get(certCaResult.getSerialNumber().longValue())); log.log(Level.FINE, "verifyCertificate - user:" + userVS.getNif() + " cert issuer: " + certCaResult.getSubjectDN() + " - CA certificateVS.id : " + userVS.getCertificateCA().getId()); return validatorResult; }
From source file:org.ejbca.extra.caservice.ExtRACAServiceWorker.java
/** * Method used to retrieve which administrator to use. * If message is signed then use the signer as admin otherwise use InternalUser * @throws SignatureException /* w w w . j a va2s .co m*/ * @throws AuthorizationDeniedException */ private Admin getAdmin(SubMessages submessages) throws SignatureException, AuthorizationDeniedException { if (submessages.isSigned()) { // Check if Signer Cert is revoked X509Certificate signerCert = submessages.getSignerCert(); Admin admin = userAdminSession.getAdmin(signerCert); // Check that user have the administrator flag set. userAdminSession.checkIfCertificateBelongToUser(admin, signerCert.getSerialNumber(), signerCert.getIssuerDN().toString()); boolean isRevoked = certificateStoreSession.isRevoked( CertTools.stringToBCDNString(signerCert.getIssuerDN().toString()), signerCert.getSerialNumber()); if (isRevoked) { throw new SignatureException("Error Signer certificate doesn't exist or is revoked."); } return admin; } return internalUser; }
From source file:org.ejbca.core.protocol.cmp.CrmfRAPbeRequestTest.java
/** * Find all certificates for a user and approve any outstanding revocation. *//*from w w w .j av a 2s . c om*/ public int approveRevocation(Admin internalAdmin, Admin approvingAdmin, String username, int reason, int approvalType, CertificateStoreSessionRemote certificateStoreSession, ApprovalSessionRemote approvalSession, ApprovalExecutionSessionRemote approvalExecutionSession, int approvalCAID) throws Exception { Collection<java.security.cert.Certificate> userCerts = certificateStoreSession .findCertificatesByUsername(internalAdmin, username); Iterator<java.security.cert.Certificate> i = userCerts.iterator(); int approvedRevocations = 0; while (i.hasNext()) { X509Certificate cert = (X509Certificate) i.next(); String issuerDN = cert.getIssuerDN().toString(); BigInteger serialNumber = cert.getSerialNumber(); boolean isRevoked = certificateStoreSession.isRevoked(issuerDN, serialNumber); if ((reason != RevokedCertInfo.NOT_REVOKED && !isRevoked) || (reason == RevokedCertInfo.NOT_REVOKED && isRevoked)) { int approvalID; if (approvalType == ApprovalDataVO.APPROVALTYPE_REVOKECERTIFICATE) { approvalID = RevocationApprovalRequest.generateApprovalId(approvalType, username, reason, serialNumber, issuerDN); } else { approvalID = RevocationApprovalRequest.generateApprovalId(approvalType, username, reason, null, null); } Query q = new Query(Query.TYPE_APPROVALQUERY); q.add(ApprovalMatch.MATCH_WITH_APPROVALID, BasicMatch.MATCH_TYPE_EQUALS, Integer.toString(approvalID)); ApprovalDataVO approvalData = (ApprovalDataVO) (approvalSession.query(internalAdmin, q, 0, 1, "cAId=" + approvalCAID, "(endEntityProfileId=" + SecConst.EMPTY_ENDENTITYPROFILE + ")") .get(0)); Approval approval = new Approval("Approved during testing."); approvalExecutionSession.approve(approvingAdmin, approvalID, approval, raAdminSession.getCachedGlobalConfiguration(new Admin(Admin.INTERNALCAID))); approvalData = (ApprovalDataVO) approvalSession.findApprovalDataVO(internalAdmin, approvalID) .iterator().next(); assertEquals(approvalData.getStatus(), ApprovalDataVO.STATUS_EXECUTED); CertificateStatus status = certificateStoreSession.getStatus(issuerDN, serialNumber); assertEquals(status.revocationReason, reason); approvalSession.removeApprovalRequest(internalAdmin, approvalData.getId()); approvedRevocations++; } } return approvedRevocations; }
From source file:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java
@Test public void testSign() throws Exception { // setup//from w ww . java2s .c om KeyPair caKeyPair = generateKeyPair(); KeyPair entityKeyPair = generateKeyPair(); X500Principal subject = new X500Principal("CN=Test"); PublicKey pubKey = entityKeyPair.getPublic(); X500Principal issuer = new X500Principal("CN=CA"); PublicKey caPubKey = caKeyPair.getPublic(); PrivateKey caKey = caKeyPair.getPrivate(); Date begin = new Date(); Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30); BigInteger serialNo = BigInteger.valueOf(1234); JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils(); // operate X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends, serialNo, null); // verify assertNotNull(resultCert); LOG.debug("result certificate: " + resultCert); resultCert.verify(caPubKey); assertEquals(subject, resultCert.getSubjectX500Principal()); assertEquals(issuer, resultCert.getIssuerX500Principal()); assertEquals(serialNo, resultCert.getSerialNumber()); assertEquals(pubKey, resultCert.getPublicKey()); LOG.debug("expected begin: " + begin.getTime()); LOG.debug("actual begin: " + resultCert.getNotBefore().getTime()); /* * BouncyCastle drops the milliseconds. */ assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000); assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000); byte[] subjectKeyIdentifierExtValue = resultCert .getExtensionValue(X509Extension.subjectKeyIdentifier.getId()); assertNotNull(subjectKeyIdentifierExtValue); ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils .parseExtensionValue(subjectKeyIdentifierExtValue); ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive(); assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded()); byte[] authorityKeyIdentifierExtValue = resultCert .getExtensionValue(X509Extension.authorityKeyIdentifier.getId()); ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils .parseExtensionValue(authorityKeyIdentifierExtValue); ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive(); assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded()); assertEquals(-1, resultCert.getBasicConstraints()); byte[] netscapeCertTypeExtValue = resultCert .getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId()); assertNotNull(netscapeCertTypeExtValue); DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil .fromExtensionValue(netscapeCertTypeExtValue); NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt); assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient); assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer); assertTrue(resultCert.getKeyUsage()[0]); assertTrue(resultCert.getKeyUsage()[2]); byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId()); assertNotNull(extendedKeyUsageExtValue); ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage .getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue)); assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth)); assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth)); }
From source file:mitm.common.security.crl.GenerateTestCRLs.java
@Test public void testGenerateCACRLThisUpdateInFarFuture() throws Exception { X509CRLBuilder crlGenerator = createX509CRLBuilder(); Date thisDate = TestUtils.parseDate("30-Nov-2030 11:38:35 GMT"); Date nextDate = TestUtils.parseDate("30-Nov-2040 11:38:35 GMT"); crlGenerator.setThisUpdate(thisDate); crlGenerator.setNextUpdate(nextDate); crlGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption"); X509Certificate certificate = TestUtils .loadCertificate("test/resources/testdata/certificates/" + "valid_certificate_mitm_test_ca.cer"); assertNotNull(certificate);//from www . j a va2s . c om Date revocationDate = TestUtils.parseDate("30-Nov-2006 11:38:35 GMT"); crlGenerator.addCRLEntry(certificate.getSerialNumber(), revocationDate, CRLReason.keyCompromise); X509CRL crl = crlGenerator.generateCRL(new KeyAndCertificateImpl(caPrivateKey, caCertificate)); assertEquals("EMAILADDRESS=ca@example.com, CN=MITM Test CA, L=Amsterdam, ST=NH, C=NL", crl.getIssuerX500Principal().toString()); assertEquals(thisDate, crl.getThisUpdate()); assertEquals(nextDate, crl.getNextUpdate()); assertEquals(1, crl.getRevokedCertificates().size()); assertTrue(crl.isRevoked(certificate)); File crlFile = new File("test/tmp/testgeneratecacrlthisupdateinfarfuture.crl"); FileOutputStream fos = new FileOutputStream(crlFile); IOUtils.write(crl.getEncoded(), fos); fos.close(); }
From source file:com.example.bbbbbb.http.sample.util.SecureSocketFactory.java
/** * Instantiate a new secured factory pertaining to the passed store. Be sure to initialize the * store with the password using {@link KeyStore#load(InputStream, * char[])} method./*from ww w. ja v a 2s .co m*/ * * @param store The key store holding the certificate details * @param alias The alias of the certificate to use */ public SecureSocketFactory(KeyStore store, String alias) throws CertificateException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException { super(store); // Loading the CA certificate from store. final Certificate rootca = store.getCertificate(alias); // Turn it to X509 format. InputStream is = new ByteArrayInputStream(rootca.getEncoded()); X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is); AsyncHttpClient.silentCloseInputStream(is); if (null == x509ca) { throw new CertificateException("Embedded SSL certificate has expired."); } // Check the CA's validity. x509ca.checkValidity(); // Accepted CA is only the one installed in the store. acceptedIssuers = new X509Certificate[] { x509ca }; sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { Exception error = null; if (null == chain || 0 == chain.length) { error = new CertificateException("Certificate chain is invalid."); } else if (null == authType || 0 == authType.length()) { error = new CertificateException("Authentication type is invalid."); } else { Log.i(LOG_TAG, "Chain includes " + chain.length + " certificates."); try { for (X509Certificate cert : chain) { Log.i(LOG_TAG, "Server Certificate Details:"); Log.i(LOG_TAG, "---------------------------"); Log.i(LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString()); Log.i(LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString()); Log.i(LOG_TAG, "Serial Number: " + cert.getSerialNumber()); Log.i(LOG_TAG, "Version: " + cert.getVersion()); Log.i(LOG_TAG, "Not before: " + cert.getNotBefore().toString()); Log.i(LOG_TAG, "Not after: " + cert.getNotAfter().toString()); Log.i(LOG_TAG, "---------------------------"); // Make sure that it hasn't expired. cert.checkValidity(); // Verify the certificate's public key chain. cert.verify(rootca.getPublicKey()); } } catch (InvalidKeyException e) { error = e; } catch (NoSuchAlgorithmException e) { error = e; } catch (NoSuchProviderException e) { error = e; } catch (SignatureException e) { error = e; } } if (null != error) { Log.e(LOG_TAG, "Certificate error", error); throw new CertificateException(error); } } @Override public X509Certificate[] getAcceptedIssuers() { return acceptedIssuers; } } }, null); setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); }
From source file:com.netscape.cms.publish.publishers.FileBasedPublisher.java
/** * Unpublishes a object to the ldap directory. * * @param conn the Ldap connection/*from w ww. j a va 2 s .c om*/ * (null if LDAP publishing is not enabled) * @param dn dn of the ldap entry to unpublish cert * (null if LDAP publishing is not enabled) * @param object object to unpublish * (java.security.cert.X509Certificate) */ public void unpublish(LDAPConnection conn, String dn, Object object) throws ELdapException { CMS.debug("FileBasedPublisher: unpublish"); String name = mDir + File.separator; String fileName; if (object instanceof X509Certificate) { X509Certificate cert = (X509Certificate) object; BigInteger sno = cert.getSerialNumber(); name += "cert-" + sno.toString(); } else if (object instanceof X509CRL) { X509CRL crl = (X509CRL) object; String[] namePrefix = getCrlNamePrefix(crl, mTimeStamp.equals("GMT")); name += namePrefix[0]; fileName = name + ".zip"; File f = new File(fileName); f.delete(); } fileName = name + ".der"; File f = new File(fileName); f.delete(); fileName = name + ".b64"; f = new File(fileName); f.delete(); }
From source file:org.ejbca.core.protocol.ocsp.OCSPUnidExtension.java
boolean checkAuthorization(HttpServletRequest request) { X509Certificate[] certs = (X509Certificate[]) request.getAttribute("javax.servlet.request.X509Certificate"); if (certs == null) { String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", request.getRemoteAddr(), request.getRemoteHost()); m_log.error(errMsg);/*from w ww.j a va2s .c o m*/ return false; } // The certificate of the entity is nr 0 X509Certificate cert = certs[0]; if (cert == null) { String errMsg = intres.getLocalizedMessage("ocsp.errornoclientauth", request.getRemoteAddr(), request.getRemoteHost()); m_log.error(errMsg); return false; } // Check if the certificate is authorised to access the Fnr if (this.trustedCerts.contains(cert.getSerialNumber())) { // If we found in the hashmap the same key with issuer and serialnumber, we know we got it. // Just verify it as well to be damn sure try { cert.verify(this.cacert.getPublicKey()); } catch (Exception e) { String errMsg = intres.getLocalizedMessage("ocsp.errorverifycert"); m_log.error(errMsg, e); return false; } // If verify was successful we know if was good! return true; } String errMsg = intres.getLocalizedMessage("ocsp.erroruntrustedclientauth", request.getRemoteAddr(), request.getRemoteHost()); m_log.error(errMsg); return false; }
From source file:org.apache.ws.security.validate.SignatureTrustValidator.java
/** * Evaluate whether a given certificate should be trusted. * // www.j ava 2 s.co m * Policy used in this implementation: * 1. Search the keystore for the transmitted certificate * 2. Search the keystore for a connection to the transmitted certificate * (that is, search for certificate(s) of the issuer of the transmitted certificate * 3. Verify the trust path for those certificates found because the search for the issuer * might be fooled by a phony DN (String!) * * @param cert the certificate that should be validated against the keystore * @param crypto A crypto instance to use for trust validation * @param data A RequestData instance * @param enableRevocation Whether revocation is enabled or not * @return true if the certificate is trusted, false if not * @throws WSSecurityException */ protected boolean verifyTrustInCert(X509Certificate cert, Crypto crypto, RequestData data, boolean enableRevocation) throws WSSecurityException { String subjectString = cert.getSubjectX500Principal().getName(); String issuerString = cert.getIssuerX500Principal().getName(); BigInteger issuerSerial = cert.getSerialNumber(); if (LOG.isDebugEnabled()) { LOG.debug("Transmitted certificate has subject " + subjectString); LOG.debug("Transmitted certificate has issuer " + issuerString + " (serial " + issuerSerial + ")"); } // // FIRST step - Search the keystore for the transmitted certificate // if (!enableRevocation && isCertificateInKeyStore(crypto, cert)) { return true; } // // SECOND step - Search for the issuer cert (chain) of the transmitted certificate in the // keystore or the truststore // CryptoType cryptoType = new CryptoType(CryptoType.TYPE.SUBJECT_DN); cryptoType.setSubjectDN(issuerString); X509Certificate[] foundCerts = crypto.getX509Certificates(cryptoType); // If the certs have not been found, the issuer is not in the keystore/truststore // As a direct result, do not trust the transmitted certificate if (foundCerts == null || foundCerts.length < 1) { if (LOG.isDebugEnabled()) { LOG.debug("No certs found in keystore for issuer " + issuerString + " of certificate for " + subjectString); } return false; } // // THIRD step // Check the certificate trust path for the issuer cert chain // if (LOG.isDebugEnabled()) { LOG.debug("Preparing to validate certificate path for issuer " + issuerString); } // // Form a certificate chain from the transmitted certificate // and the certificate(s) of the issuer from the keystore/truststore // X509Certificate[] x509certs = new X509Certificate[foundCerts.length + 1]; x509certs[0] = cert; for (int j = 0; j < foundCerts.length; j++) { x509certs[j + 1] = (X509Certificate) foundCerts[j]; } // // Use the validation method from the crypto to check whether the subjects' // certificate was really signed by the issuer stated in the certificate // if (crypto.verifyTrust(x509certs, enableRevocation)) { if (LOG.isDebugEnabled()) { LOG.debug("Certificate path has been verified for certificate with subject " + subjectString); } Collection<Pattern> subjectCertConstraints = data.getSubjectCertConstraints(); if (matches(cert, subjectCertConstraints)) { return true; } } if (LOG.isDebugEnabled()) { LOG.debug("Certificate path could not be verified for certificate with subject " + subjectString); } return false; }