List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:org.apache.synapse.transport.utils.sslcert.ocsp.OCSPVerifier.java
/** * Gets the revocation status (Good, Revoked or Unknown) of the given peer certificate. * * @param peerCert The certificate we want to check if revoked. * @param issuerCert Needed to create OCSP request. * @return revocation status of the peer certificate. * @throws CertificateVerificationException * *//*from ww w . j a va 2 s . co m*/ public RevocationStatus checkRevocationStatus(X509Certificate peerCert, X509Certificate issuerCert) throws CertificateVerificationException { //check cache if (cache != null) { SingleResp resp = cache.getCacheValue(peerCert.getSerialNumber()); if (resp != null) { //If cant be casted, we have used the wrong cache. RevocationStatus status = getRevocationStatus(resp); log.debug("OCSP response taken from cache...."); return status; } } OCSPReq request = generateOCSPRequest(issuerCert, peerCert.getSerialNumber()); //This list will sometimes have non ocsp urls as well. List<String> locations = getAIALocations(peerCert); for (String serviceUrl : locations) { SingleResp[] responses; try { OCSPResp ocspResponse = getOCSPResponse(serviceUrl, request); if (OCSPRespStatus.SUCCESSFUL != ocspResponse.getStatus()) { continue; // Server didn't give the response right. } BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); responses = (basicResponse == null) ? null : basicResponse.getResponses(); //todo use the super exception } catch (Exception e) { continue; } if (responses != null && responses.length == 1) { SingleResp resp = responses[0]; RevocationStatus status = getRevocationStatus(resp); if (cache != null) cache.setCacheValue(peerCert.getSerialNumber(), resp, request, serviceUrl); return status; } } throw new CertificateVerificationException("Cant get Revocation Status from OCSP."); }
From source file:org.apache.ws.security.validate.SignatureTrustValidator.java
/** * Check to see if the certificate argument is in the keystore * @param crypto A Crypto instance to use for trust validation * @param cert The certificate to check/*from www . j a v a 2 s.c o m*/ * @return true if cert is in the keystore * @throws WSSecurityException */ protected boolean isCertificateInKeyStore(Crypto crypto, X509Certificate cert) throws WSSecurityException { String issuerString = cert.getIssuerX500Principal().getName(); BigInteger issuerSerial = cert.getSerialNumber(); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ISSUER_SERIAL); cryptoType.setIssuerSerial(issuerString, issuerSerial); X509Certificate[] foundCerts = crypto.getX509Certificates(cryptoType); // // If a certificate has been found, the certificates must be compared // to ensure against phony DNs (compare encoded form including signature) // if (foundCerts != null && foundCerts[0] != null && foundCerts[0].equals(cert)) { if (LOG.isDebugEnabled()) { LOG.debug("Direct trust for certificate with " + cert.getSubjectX500Principal().getName()); } return true; } if (LOG.isDebugEnabled()) { LOG.debug("No certificate found for subject from issuer with " + issuerString + " (serial " + issuerSerial + ")"); } return false; }
From source file:org.apache.synapse.transport.certificatevalidation.ocsp.OCSPVerifier.java
/** * Gets the revocation status (Good, Revoked or Unknown) of the given peer certificate. * * @param peerCert The certificate we want to check if revoked. * @param issuerCert Needed to create OCSP request. * @return revocation status of the peer certificate. * @throws CertificateVerificationException * */// w w w .j av a 2s . c o m public RevocationStatus checkRevocationStatus(X509Certificate peerCert, X509Certificate issuerCert) throws CertificateVerificationException { //check cache if (cache != null) { SingleResp resp = cache.getCacheValue(peerCert.getSerialNumber()); if (resp != null) { //If cant be casted, we have used the wrong cache. RevocationStatus status = getRevocationStatus(resp); log.info("OCSP response taken from cache...."); return status; } } OCSPReq request = generateOCSPRequest(issuerCert, peerCert.getSerialNumber()); //This list will sometimes have non ocsp urls as well. List<String> locations = getAIALocations(peerCert); for (String serviceUrl : locations) { SingleResp[] responses; try { OCSPResp ocspResponse = getOCSPResponce(serviceUrl, request); if (OCSPResponseStatus.SUCCESSFUL != ocspResponse.getStatus()) { continue; // Server didn't give the response right. } BasicOCSPResp basicResponse = (BasicOCSPResp) ocspResponse.getResponseObject(); responses = (basicResponse == null) ? null : basicResponse.getResponses(); //todo use the super exception } catch (Exception e) { continue; } if (responses != null && responses.length == 1) { SingleResp resp = responses[0]; RevocationStatus status = getRevocationStatus(resp); if (cache != null) cache.setCacheValue(peerCert.getSerialNumber(), resp, request, serviceUrl); return status; } } throw new CertificateVerificationException("Cant get Revocation Status from OCSP."); }
From source file:eu.europa.esig.dss.pades.signature.PAdESLevelBTest.java
@Override protected void onDocumentSigned(byte[] byteArray) { try {/*from ww w . j av a 2s. c o m*/ InputStream inputStream = new ByteArrayInputStream(byteArray); PDDocument document = PDDocument.load(inputStream); List<PDSignature> signatures = document.getSignatureDictionaries(); assertEquals(1, signatures.size()); for (PDSignature pdSignature : signatures) { byte[] contents = pdSignature.getContents(byteArray); byte[] signedContent = pdSignature.getSignedContent(byteArray); logger.info("Byte range : " + Arrays.toString(pdSignature.getByteRange())); //IOUtils.write(contents, new FileOutputStream("sig.p7s")); ASN1InputStream asn1sInput = new ASN1InputStream(contents); ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject(); logger.info("SEQ : " + asn1Seq.toString()); ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0)); assertEquals(PKCSObjectIdentifiers.signedData, oid); SignedData signedData = SignedData .getInstance(DERTaggedObject.getInstance(asn1Seq.getObjectAt(1)).getObject()); ASN1Set digestAlgorithmSet = signedData.getDigestAlgorithms(); ASN1ObjectIdentifier oidDigestAlgo = ASN1ObjectIdentifier .getInstance(ASN1Sequence.getInstance(digestAlgorithmSet.getObjectAt(0)).getObjectAt(0)); DigestAlgorithm digestAlgorithm = DigestAlgorithm.forOID(oidDigestAlgo.getId()); logger.info("DIGEST ALGO : " + digestAlgorithm); ContentInfo encapContentInfo = signedData.getEncapContentInfo(); ASN1ObjectIdentifier contentTypeOID = encapContentInfo.getContentType(); logger.info("ENCAPSULATED CONTENT INFO TYPE : " + contentTypeOID); assertEquals(PKCSObjectIdentifiers.data, contentTypeOID); ASN1Encodable content = encapContentInfo.getContent(); logger.info("ENCAPSULATED CONTENT INFO CONTENT : " + content); assertNull(content); List<X509Certificate> certificates = extractCertificates(signedData); ASN1Set signerInfosAsn1 = signedData.getSignerInfos(); logger.info("SIGNER INFO ASN1 : " + signerInfosAsn1.toString()); SignerInfo signedInfo = SignerInfo .getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0))); ASN1Set authenticatedAttributeSet = signedInfo.getAuthenticatedAttributes(); logger.info("AUTHENTICATED ATTR : " + authenticatedAttributeSet); List<ASN1ObjectIdentifier> attributeOids = new ArrayList<ASN1ObjectIdentifier>(); for (int i = 0; i < authenticatedAttributeSet.size(); i++) { Attribute attribute = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(i)); attributeOids.add(attribute.getAttrType()); } logger.info("List of OID for Auth Attrb : " + attributeOids); Attribute attributeDigest = Attribute.getInstance(authenticatedAttributeSet.getObjectAt(1)); assertEquals(PKCSObjectIdentifiers.pkcs_9_at_messageDigest, attributeDigest.getAttrType()); ASN1OctetString asn1ObjString = ASN1OctetString .getInstance(attributeDigest.getAttrValues().getObjectAt(0)); String embeddedDigest = Base64.encode(asn1ObjString.getOctets()); logger.info("MESSAGE DIGEST : " + embeddedDigest); byte[] digestSignedContent = DSSUtils.digest(digestAlgorithm, signedContent); String computedDigestSignedContentEncodeBase64 = Base64.encode(digestSignedContent); logger.info("COMPUTED DIGEST SIGNED CONTENT BASE64 : " + computedDigestSignedContentEncodeBase64); assertEquals(embeddedDigest, computedDigestSignedContentEncodeBase64); SignerIdentifier sid = signedInfo.getSID(); logger.info("SIGNER IDENTIFIER : " + sid.getId()); IssuerAndSerialNumber issuerAndSerialNumber = IssuerAndSerialNumber .getInstance(signedInfo.getSID()); ASN1Integer signerSerialNumber = issuerAndSerialNumber.getSerialNumber(); logger.info("ISSUER AND SN : " + issuerAndSerialNumber.getName() + " " + signerSerialNumber); BigInteger serial = issuerAndSerialNumber.getSerialNumber().getValue(); X509Certificate signerCertificate = null; for (X509Certificate x509Certificate : certificates) { if (serial.equals(x509Certificate.getSerialNumber())) { signerCertificate = x509Certificate; } } assertNotNull(signerCertificate); String algorithm = signerCertificate.getPublicKey().getAlgorithm(); EncryptionAlgorithm encryptionAlgorithm = EncryptionAlgorithm.forName(algorithm); ASN1OctetString encryptedInfoOctedString = signedInfo.getEncryptedDigest(); String signatureValue = Hex.toHexString(encryptedInfoOctedString.getOctets()); logger.info("SIGNATURE VALUE : " + signatureValue); Cipher cipher = Cipher.getInstance(encryptionAlgorithm.getName()); cipher.init(Cipher.DECRYPT_MODE, signerCertificate); byte[] decrypted = cipher.doFinal(encryptedInfoOctedString.getOctets()); ASN1InputStream inputDecrypted = new ASN1InputStream(decrypted); ASN1Sequence seqDecrypt = (ASN1Sequence) inputDecrypted.readObject(); logger.info("DECRYPTED : " + seqDecrypt); DigestInfo digestInfo = new DigestInfo(seqDecrypt); assertEquals(oidDigestAlgo, digestInfo.getAlgorithmId().getAlgorithm()); String decryptedDigestEncodeBase64 = Base64.encode(digestInfo.getDigest()); logger.info("DECRYPTED BASE64 : " + decryptedDigestEncodeBase64); byte[] encoded = authenticatedAttributeSet.getEncoded(); byte[] digest = DSSUtils.digest(digestAlgorithm, encoded); String computedDigestFromSignatureEncodeBase64 = Base64.encode(digest); logger.info("COMPUTED DIGEST FROM SIGNATURE BASE64 : " + computedDigestFromSignatureEncodeBase64); assertEquals(decryptedDigestEncodeBase64, computedDigestFromSignatureEncodeBase64); IOUtils.closeQuietly(inputDecrypted); IOUtils.closeQuietly(asn1sInput); } IOUtils.closeQuietly(inputStream); document.close(); } catch (Exception e) { logger.error(e.getMessage(), e); fail(e.getMessage()); } }
From source file:com.otterca.persistence.entity.X509CertificateEntity.java
/** * Cache values within certificate. They should never be set directly and * the actual values in the database should be created via triggers. * //from www . j av a 2 s . c o m * @param cert */ protected final void cacheAttributes(X509Certificate cert) throws CertificateEncodingException, IOException { serialNumber = cert.getSerialNumber(); certificate = cert.getEncoded(); subject = cert.getSubjectDN().getName(); issuer = cert.getIssuerDN().getName(); notBefore = cert.getNotBefore(); notAfter = cert.getNotAfter(); //name = x509CertUtil.getName(cert); //fingerprint = x509CertUtil.getFingerprint(cert); //certHash = x509CertUtil.getCertificateHash(cert); //iHash = x509CertUtil.getIHash(cert); //sHash = x509CertUtil.getSHash(cert); //akidHash = x509CertUtil.getAkidHash(cert); //skidHash = x509CertUtil.getSkidHash(cert); }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateManagementServiceImplTests.java
@Test(description = "This test case tests retrieval of a Certificate from the keystore from the Serial") public void testRetrieveCertificate() throws KeystoreException, CertificateManagementException { X509Certificate x509Certificate = managementService.generateX509Certificate(); CertificateResponse certificateResponse = managementService .retrieveCertificate(x509Certificate.getSerialNumber().toString()); Assert.assertNotNull(certificateResponse); Assert.assertEquals(x509Certificate.getSerialNumber(), certificateResponse.getCertificateserial()); }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateManagementServiceImplTests.java
@Test(description = "This test case tests searching for a list of certificates by the serial number") public void testSearchCertificates() throws CertificateManagementException, KeystoreException { X509Certificate x509Certificate = managementService.generateX509Certificate(); List<CertificateResponse> certificateResponses = managementService .searchCertificates(x509Certificate.getSerialNumber().toString()); Assert.assertNotNull(certificateResponses); Assert.assertEquals(1, certificateResponses.size()); Assert.assertEquals(certificateResponses.get(0).getSerialNumber(), x509Certificate.getSerialNumber().toString()); log.info("SearchCertificates Test Successful"); }
From source file:com.alfaariss.oa.engine.crypto.keystore.KeystoreSigningFactory.java
/** * Retrieve alias from the certificate store. * @see AbstractSigningFactory#getAliasForX509Cert( * java.lang.String, java.math.BigInteger) *///from w w w.jav a 2 s . c o m @Override public String getAliasForX509Cert(String issuer, BigInteger serialNumber) throws CryptoException { X500Principal issuerRDN = new X500Principal(issuer); Certificate cert = null; try { Enumeration<String> aliases = _certificatestore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate[] certs = _certificatestore.getCertificateChain(alias); if (certs == null || certs.length == 0) { // no cert chain cert = _certificatestore.getCertificate(alias); if (cert == null) { return null; } } else { cert = certs[0]; } if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; if (serialNumber == null || x509cert.getSerialNumber().compareTo(serialNumber) == 0) { X500Principal certRDN = new X500Principal(x509cert.getIssuerDN().getName()); if (certRDN.equals(issuerRDN)) { return alias; } } } } } catch (KeyStoreException e) { _logger.error("Could not read alias from trust store", e); throw new CryptoException(SystemErrors.ERROR_RESOURCE_RETRIEVE, e); } return null; }
From source file:no.difi.sdp.client.asice.signature.CreateXAdESProperties.java
public Document createPropertiesToSign(List<AsicEAttachable> files, Sertifikat sertifikat) { X509Certificate certificate = sertifikat.getX509Certificate(); byte[] certificateDigestValue = sha1(sertifikat.getEncoded()); DigestAlgAndValueType certificateDigest = new DigestAlgAndValueType(sha1DigestMethod, certificateDigestValue);// ww w. j a va2 s . co m X509IssuerSerialType certificateIssuer = new X509IssuerSerialType(certificate.getIssuerDN().getName(), certificate.getSerialNumber()); SigningCertificate signingCertificate = new SigningCertificate( singletonList(new CertIDType(certificateDigest, certificateIssuer, null))); DateTime now = DateTime.now(DateTimeZone.UTC); SignedSignatureProperties signedSignatureProperties = new SignedSignatureProperties(now, signingCertificate, null, null, null, null); SignedDataObjectProperties signedDataObjectProperties = new SignedDataObjectProperties( dataObjectFormats(files), null, null, null, null); SignedProperties signedProperties = new SignedProperties(signedSignatureProperties, signedDataObjectProperties, "SignedProperties"); QualifyingProperties qualifyingProperties = new QualifyingProperties(signedProperties, null, "#Signature", null); DOMResult domResult = new DOMResult(); marshaller.marshal(qualifyingProperties, domResult); Document document = (Document) domResult.getNode(); // Explicitly mark the SignedProperties Id as an Document ID attribute, so that it will be eligble as a reference for signature. // If not, it will not be treated as something to sign. markAsIdProperty(document, "SignedProperties", "Id"); return document; }
From source file:be.fedict.trust.service.dao.bean.TrustDomainDAOBean.java
/** * {@inheritDoc}// w w w. j ava 2 s.com */ public EndEntityConstraintEntity addEndEntityConstraint(TrustDomainEntity trustDomain, X509Certificate certificate) { String issuerName = certificate.getIssuerX500Principal().getName(); BigInteger serialNumber = certificate.getSerialNumber(); EndEntityConstraintEntity endEntityCertificateConstraint = new EndEntityConstraintEntity(trustDomain, issuerName, serialNumber); this.entityManager.persist(endEntityCertificateConstraint); TrustDomainEntity attachedTrustDomain = findTrustDomain(trustDomain.getName()); attachedTrustDomain.getCertificateConstraints().add(endEntityCertificateConstraint); return endEntityCertificateConstraint; }