List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:be.fedict.trust.service.bean.TrustServiceTrustLinker.java
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData) { LOG.debug("certificate: " + childCertificate.getSubjectX500Principal()); LOG.debug("certificate Issuer: " + childCertificate.getIssuerX500Principal().toString()); LOG.debug("Issuer: " + certificate.getSubjectX500Principal()); BigInteger issuerSerialNumber = certificate.getSerialNumber(); String key = new String(); key += certificate.getSubjectX500Principal().toString() + "|" + issuerSerialNumber.toString(); String issuerName = childCertificate.getIssuerX500Principal().toString(); CertificateAuthorityEntity certificateAuthority = this.entityManager //.find(CertificateAuthorityEntity.class, issuerName); .find(CertificateAuthorityEntity.class, key); if (null == certificateAuthority) { LOG.debug("no data cache entry for CA: " + issuerName + " - Serial Number: " + issuerSerialNumber.toString()); /*/* ww w. j av a 2 s . c o m*/ * Cache Miss */ SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L); /* * Lookup Root CA's trust point via parent certificates' CA entity. */ String parentIssuerName = certificate.getIssuerX500Principal().toString(); CertificateAuthorityEntity parentCertificateAuthority = this.entityManager .find(CertificateAuthorityEntity.class, parentIssuerName); if (null == parentCertificateAuthority) { logAudit("CA not found for " + parentIssuerName); LOG.error("CA not found for " + parentIssuerName + " ?!"); return null; } // create new CA try { certificateAuthority = new CertificateAuthorityEntity(getCrlUrl(childCertificate), certificate); certificateAuthority.setTrustPoint(parentCertificateAuthority.getTrustPoint()); } catch (CertificateEncodingException e) { LOG.error("certificate encoding error: " + e.getMessage(), e); return null; } this.entityManager.persist(certificateAuthority); return null; } if (Status.ACTIVE != certificateAuthority.getStatus()) { LOG.debug("CA revocation data cache not yet active: " + issuerName); /* * Harvester is still busy processing the first CRL. */ if (null == certificateAuthority.getCrlUrl()) { certificateAuthority.setCrlUrl(getCrlUrl(childCertificate)); } if (Status.NONE != certificateAuthority.getStatus()) { // none means no CRL is available so not really a cache miss SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L); } return null; } /* * Let's use the cached revocation data */ Date thisUpdate = certificateAuthority.getThisUpdate(); if (null == thisUpdate) { LOG.warn("no thisUpdate value: " + certificateAuthority.getName()); SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L); return null; } Date nextUpdate = certificateAuthority.getNextUpdate(); if (null == nextUpdate) { LOG.warn("no nextUpdate value: " + certificateAuthority.getName()); SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L); return null; } /* * First check whether the cached revocation data is up-to-date. */ if (thisUpdate.after(validationDate)) { LOG.warn("cached CRL data too recent: " + certificateAuthority.getName()); SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L); return null; } if (validationDate.after(nextUpdate)) { LOG.warn("cached CRL data too old: " + certificateAuthority.getName()); SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L); return null; } LOG.debug("using cached CRL data"); /* * Cache Hit */ SNMPInterceptor.increment(SnmpConstants.CACHE_HITS, SnmpConstants.SNMP_SERVICE, 1L); BigInteger serialNumber = childCertificate.getSerialNumber(); RevokedCertificateEntity revokedCertificate = findRevokedCertificate(issuerName, serialNumber); if (null == revokedCertificate) { LOG.debug("certificate valid: " + childCertificate.getSubjectX500Principal()); return new TrustLinkerResult(true); } if (revokedCertificate.getRevocationDate().after(validationDate)) { LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate); return new TrustLinkerResult(true); } LOG.debug("certificate invalid: " + childCertificate.getSubjectX500Principal()); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS, "certificate revoked by cached CRL"); }
From source file:eu.eidas.auth.engine.SAMLEngineUtils.java
/** * * @param keystore//from ww w . j a v a 2s . co m * @param serialNumber * @param issuer * @return a certificate/alias pair from the keystore, having the given issuer and serialNumber * @throws KeyStoreException * @throws SAMLEngineException */ public static CertificateAliasPair getCertificatePair(KeyStore keystore, String serialNumber, String issuer) throws KeyStoreException, SAMLEngineException { String alias = null; String aliasCert; X509Certificate certificate; boolean find = false; LOG.debug("cherche dans " + keystore.toString() + " numSerie=" + serialNumber + " issuer=" + issuer); for (final Enumeration<String> e = keystore.aliases(); e.hasMoreElements() && !find;) { aliasCert = e.nextElement(); certificate = (X509Certificate) keystore.getCertificate(aliasCert); final String serialNum = certificate.getSerialNumber().toString(16); Principal p = certificate.getIssuerDN(); String name = p.getName(); X500Name issuerDN = new X500Name(name); X500Name issuerDNConf = new X500Name(issuer); if (serialNum.equalsIgnoreCase(serialNumber) && X500PrincipalUtil.principalEquals(issuerDN, issuerDNConf)) { alias = aliasCert; find = true; } else { LOG.debug("pas pareil numSerie=" + serialNum + " ou issuer=" + name); } } if (!find) { throw new SAMLEngineException( "Certificate " + issuer + "/" + serialNumber + " cannot be found in keystore "); } certificate = (X509Certificate) keystore.getCertificate(alias); return new CertificateAliasPair(certificate, alias); }
From source file:be.fedict.eid.applet.service.signer.time.TSPTimeStampService.java
public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception { // digest the message MessageDigest messageDigest = MessageDigest.getInstance(this.digestAlgo); byte[] digest = messageDigest.digest(data); // generate the TSP request BigInteger nonce = new BigInteger(128, new SecureRandom()); TimeStampRequestGenerator requestGenerator = new TimeStampRequestGenerator(); requestGenerator.setCertReq(true);//from w w w .j av a 2 s . co m if (null != this.requestPolicy) { requestGenerator.setReqPolicy(this.requestPolicy); } TimeStampRequest request = requestGenerator.generate(this.digestAlgoOid, digest, nonce); byte[] encodedRequest = request.getEncoded(); // create the HTTP client HttpClient httpClient = new HttpClient(); if (null != this.username) { Credentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpClient.getState().setCredentials(AuthScope.ANY, credentials); } if (null != this.proxyHost) { httpClient.getHostConfiguration().setProxy(this.proxyHost, this.proxyPort); } // create the HTTP POST request PostMethod postMethod = new PostMethod(this.tspServiceUrl); RequestEntity requestEntity = new ByteArrayRequestEntity(encodedRequest, "application/timestamp-query"); postMethod.addRequestHeader("User-Agent", this.userAgent); postMethod.setRequestEntity(requestEntity); // invoke TSP service int statusCode = httpClient.executeMethod(postMethod); if (HttpStatus.SC_OK != statusCode) { LOG.error("Error contacting TSP server " + this.tspServiceUrl); throw new Exception("Error contacting TSP server " + this.tspServiceUrl); } // HTTP input validation Header responseContentTypeHeader = postMethod.getResponseHeader("Content-Type"); if (null == responseContentTypeHeader) { throw new RuntimeException("missing Content-Type header"); } String contentType = responseContentTypeHeader.getValue(); if (!contentType.startsWith("application/timestamp-reply")) { LOG.debug("response content: " + postMethod.getResponseBodyAsString()); throw new RuntimeException("invalid Content-Type: " + contentType); } if (0 == postMethod.getResponseContentLength()) { throw new RuntimeException("Content-Length is zero"); } // TSP response parsing and validation InputStream inputStream = postMethod.getResponseBodyAsStream(); TimeStampResponse timeStampResponse = new TimeStampResponse(inputStream); timeStampResponse.validate(request); if (0 != timeStampResponse.getStatus()) { LOG.debug("status: " + timeStampResponse.getStatus()); LOG.debug("status string: " + timeStampResponse.getStatusString()); PKIFailureInfo failInfo = timeStampResponse.getFailInfo(); if (null != failInfo) { LOG.debug("fail info int value: " + failInfo.intValue()); if (PKIFailureInfo.unacceptedPolicy == failInfo.intValue()) { LOG.debug("unaccepted policy"); } } throw new RuntimeException("timestamp response status != 0: " + timeStampResponse.getStatus()); } TimeStampToken timeStampToken = timeStampResponse.getTimeStampToken(); SignerId signerId = timeStampToken.getSID(); BigInteger signerCertSerialNumber = signerId.getSerialNumber(); X500Principal signerCertIssuer = new X500Principal(signerId.getIssuer().getEncoded()); LOG.debug("signer cert serial number: " + signerCertSerialNumber); LOG.debug("signer cert issuer: " + signerCertIssuer); // TSP signer certificates retrieval CertStore certStore = timeStampToken.getCertificatesAndCRLs("Collection", BouncyCastleProvider.PROVIDER_NAME); Collection<? extends Certificate> certificates = certStore.getCertificates(null); X509Certificate signerCert = null; Map<String, X509Certificate> certificateMap = new HashMap<String, X509Certificate>(); for (Certificate certificate : certificates) { X509Certificate x509Certificate = (X509Certificate) certificate; if (signerCertIssuer.equals(x509Certificate.getIssuerX500Principal()) && signerCertSerialNumber.equals(x509Certificate.getSerialNumber())) { signerCert = x509Certificate; } String ski = Hex.encodeHexString(getSubjectKeyId(x509Certificate)); certificateMap.put(ski, x509Certificate); LOG.debug("embedded certificate: " + x509Certificate.getSubjectX500Principal() + "; SKI=" + ski); } // TSP signer cert path building if (null == signerCert) { throw new RuntimeException("TSP response token has no signer certificate"); } List<X509Certificate> tspCertificateChain = new LinkedList<X509Certificate>(); X509Certificate tsaIssuer = loadCertificate( "be/fedict/eid/applet/service/CA POLITICA SELLADO DE TIEMPO - COSTA RICA.crt"); X509Certificate rootCA = loadCertificate("be/fedict/eid/applet/service/CA RAIZ NACIONAL COSTA RICA.cer"); LOG.debug("adding to certificate chain: " + signerCert.getSubjectX500Principal()); tspCertificateChain.add(signerCert); LOG.debug("adding to certificate chain: " + tsaIssuer.getSubjectX500Principal()); tspCertificateChain.add(tsaIssuer); LOG.debug("adding to certificate chain: " + rootCA.getSubjectX500Principal()); tspCertificateChain.add(rootCA); // verify TSP signer signature timeStampToken.validate(tspCertificateChain.get(0), BouncyCastleProvider.PROVIDER_NAME); // verify TSP signer certificate this.validator.validate(tspCertificateChain, revocationData); LOG.debug("time-stamp token time: " + timeStampToken.getTimeStampInfo().getGenTime()); byte[] timestamp = timeStampToken.getEncoded(); return timestamp; }
From source file:org.openanzo.client.AnzoTrustManager.java
private void handleCertificateException(CertificateException ce, X509Certificate[] chain) throws CertificateException { if (trustAll) { return;// w ww. j a va 2 s .c o m } System.err.println(ce.getMessage()); System.err.println("Certificate Information: \n"); Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(chain[0].getNotBefore().getTime()); System.err.println("Creation Date: " + MONTHS[cal.get(Calendar.MONTH)] + " " + cal.get(Calendar.DAY_OF_MONTH) + ", " + cal.get(Calendar.YEAR)); //System.err.println("Entry type: " + chain[0].getType()); System.err.println("Certificate chain length: " + chain.length); // print some information about the certificate(s) that failed int i = 1; for (X509Certificate cert : chain) { System.err.println("Certificate[" + i++ + "]:"); System.err.println("Owner: " + cert.getSubjectX500Principal().toString()); System.err.println("Issuer: " + cert.getIssuerX500Principal().toString()); String serialNum = new String(Hex.encodeHex(cert.getSerialNumber().toByteArray())); System.err.println("Serial Number: " + serialNum); System.err.println( "Valid from: " + cert.getNotBefore().toString() + " until: " + cert.getNotAfter().toString()); System.err.println("Certificate fingerprints: "); try { byte[] sig = cert.getEncoded(); System.err.println("\tMD5: " + getHash(sig, "MD5")); System.err.println("\tSHA1: " + getHash(sig, "SHA1")); } catch (NoSuchAlgorithmException e) { } System.err.println("\tSignature Algorithm Name: " + cert.getSigAlgName()); System.err.println("\tVersion: " + cert.getVersion()); System.err.println("-----------------------------------------------------"); } System.err.println("Would you like to accept this certificate? (o)nce, (a)lways, (n)o"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = ""; try { line = in.readLine(); } catch (IOException e) { CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace); System.exit(1); } if (Character.toLowerCase(line.charAt(0)) == 'o') { return; } else if (Character.toLowerCase(line.charAt(0)) == 'a') { try { String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "JCEKS"); String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_PWORD); String truststorePath = System.getProperty("javax.net.ssl.trustStore"); if (truststorePath == null) { // there is no trust store location in the user's settings.trig file String userHome = System.getProperty("user.home"); if (userHome == null) throw new AnzoException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER, "User's home directory is not specified"); File truststoreFile = new File(new File(userHome, ANZO_DIR), DEFAULT_CLIENT_TRUST); truststorePath = truststoreFile.getCanonicalPath(); if (!truststoreFile.exists()) openTruststore(truststoreType, truststorePath, truststorePassword); } else { truststorePath = CommandContext.preprocessString(truststorePath); File truststoreFile = new File(truststorePath); if (!truststoreFile.exists()) { System.err.println("Could not find the specified trust store file at:"); System.err.println(truststoreFile.getCanonicalPath()); System.err.println( "The trust store file is used for permanently trusting server certificates that"); System.err.println("are not trusted by default."); System.err.println( "Would you like to create a new trust store file at the specified location?"); System.err.println("(y)es, (n)o"); try { line = in.readLine(); } catch (IOException e) { CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace); System.exit(1); } if (Character.toLowerCase(line.charAt(0)) == 'y') openTruststore(truststoreType, truststorePath, truststorePassword); else System.exit(1); } } KeystoreUtils.addTrustedCert(truststorePath, truststoreType, truststorePassword, "imported_" + System.currentTimeMillis(), chain[0]); } catch (AnzoException ae) { System.err.println("Error importing certificate into truststore: "); CommandLineInterface.DEFAULT_CONSOLE.printException(ae, showTrace); System.exit(1); } catch (IOException e) { System.err.println("Error importing certificate into truststore: "); CommandLineInterface.DEFAULT_CONSOLE.printException(e, showTrace); System.exit(1); } } else { System.exit(1); // if the user does not want to trust the certificate then exit } }
From source file:org.ejbca.core.protocol.cmp.CrmfRARequestTest.java
public void test03UseKeyID() throws Exception { GlobalConfiguration gc = globalConfigurationSession.getCachedGlobalConfiguration(admin); boolean gcEELimitations = gc.getEnableEndEntityProfileLimitations(); gc.setEnableEndEntityProfileLimitations(true); globalConfigurationSession.saveGlobalConfigurationRemote(admin, gc); updatePropertyOnServer(CmpConfiguration.CONFIG_RA_ENDENTITYPROFILE, "KeyId"); updatePropertyOnServer(CmpConfiguration.CONFIG_RA_CERTIFICATEPROFILE, "KeyId"); try {//from w w w . j av a 2 s .c o m certProfileSession.removeCertificateProfile(admin, "CMPKEYIDTESTPROFILE"); eeProfileSession.removeEndEntityProfile(admin, "CMPKEYIDTESTPROFILE"); } catch (Exception e) { } // Configure CMP for this test, we allow custom certificate serial numbers CertificateProfile profile = new CertificateProfile(); try { certProfileSession.addCertificateProfile(admin, "CMPKEYIDTESTPROFILE", profile); } catch (CertificateProfileExistsException e) { log.error("Could not create certificate profile.", e); } int cpId = certProfileSession.getCertificateProfileId(admin, "CMPKEYIDTESTPROFILE"); EndEntityProfile eep = new EndEntityProfile(); eep.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, "" + cpId); eep.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, "" + cpId); eep.setValue(EndEntityProfile.DEFAULTCA, 0, "" + caid); //CertificateProfile.ANYCA eep.setValue(EndEntityProfile.AVAILCAS, 0, "" + caid); eep.addField(DnComponents.ORGANIZATION); eep.setRequired(DnComponents.ORGANIZATION, 0, true); eep.addField(DnComponents.RFC822NAME); eep.addField(DnComponents.UPN); eep.setModifyable(DnComponents.RFC822NAME, 0, true); eep.setUse(DnComponents.RFC822NAME, 0, false); // Don't use field from "email" data try { eeProfileSession.addEndEntityProfile(admin, "CMPKEYIDTESTPROFILE", eep); } catch (EndEntityProfileExistsException e) { log.error("Could not create end entity profile.", e); } // Create a new user that does not fulfill the end entity profile String userDN = "CN=keyIDTestUser,C=SE"; final KeyPair keys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final byte[] nonce = CmpMessageHelper.createSenderNonce(); final byte[] transid = CmpMessageHelper.createSenderNonce(); final int reqId; if (userAdminSession.existsUser(admin, "keyIDTestUser")) { userAdminSession.deleteUser(admin, "keyIDTestUser"); } final PKIMessage one = genCertReq(issuerDN, userDN, keys, cacert, nonce, transid, true, null, null, null, null); final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567); reqId = req.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue(); Assert.assertNotNull(req); final ByteArrayOutputStream bao = new ByteArrayOutputStream(); final DEROutputStream out = new DEROutputStream(bao); out.writeObject(req); final byte[] ba = bao.toByteArray(); // Send request and receive response final byte[] resp = sendCmpHttp(ba, 200); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp, issuerDN, userDN, cacert, nonce, transid, false, null); checkCmpFailMessage(resp, "Subject DN field 'ORGANIZATION' must exist.", CmpPKIBodyConstants.INITIALIZATIONRESPONSE, reqId, FailInfo.BAD_REQUEST.hashCode()); // Create a new user that fulfills the end entity profile userDN = "CN=keyidtest2,O=org"; final KeyPair keys2 = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); final byte[] nonce2 = CmpMessageHelper.createSenderNonce(); final byte[] transid2 = CmpMessageHelper.createSenderNonce(); final int reqId2; final PKIMessage one2 = genCertReq(issuerDN, userDN, keys2, cacert, nonce2, transid2, true, null, null, null, null); final PKIMessage req2 = protectPKIMessage(one2, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567); reqId2 = req2.getBody().getIr().getCertReqMsg(0).getCertReq().getCertReqId().getValue().intValue(); Assert.assertNotNull(req2); final ByteArrayOutputStream bao2 = new ByteArrayOutputStream(); final DEROutputStream out2 = new DEROutputStream(bao2); out2.writeObject(req2); final byte[] ba2 = bao2.toByteArray(); // Send request and receive response final byte[] resp2 = sendCmpHttp(ba2, 200); // do not check signing if we expect a failure (sFailMessage==null) checkCmpResponseGeneral(resp2, issuerDN, userDN, cacert, nonce2, transid2, true, null); X509Certificate cert = checkCmpCertRepMessage(userDN, cacert, resp2, reqId2); BigInteger serialnumber = cert.getSerialNumber(); UserDataVO user = userAdminSession.findUser(admin, "keyidtest2"); Assert.assertEquals("Wrong certificate profile", cpId, user.getCertificateProfileId()); // Revoke the created certificate and use keyid //final String hash = "foo123"; final PKIMessage con = genRevReq(issuerDN, userDN, serialnumber, cacert, nonce2, transid2, false); Assert.assertNotNull(con); PKIMessage revmsg = protectPKIMessage(con, false, PBEPASSWORD, "CMPKEYIDTESTPROFILE", 567); final ByteArrayOutputStream baorev = new ByteArrayOutputStream(); final DEROutputStream outrev = new DEROutputStream(baorev); outrev.writeObject(revmsg); final byte[] barev = baorev.toByteArray(); // Send request and receive response final byte[] resprev = sendCmpHttp(barev, 200); checkCmpResponseGeneral(resprev, issuerDN, userDN, cacert, nonce2, transid2, true, null); int revstatus = checkRevokeStatus(issuerDN, serialnumber); Assert.assertEquals("Certificate revocation failed.", RevokedCertInfo.REVOCATION_REASON_KEYCOMPROMISE, revstatus); gc.setEnableEndEntityProfileLimitations(gcEELimitations); globalConfigurationSession.saveGlobalConfigurationRemote(admin, gc); }
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 Alias") public void testGetCertificateByAlias() throws KeystoreException, DeviceManagementException { X509Certificate x509Certificate = null; //generate and save a certificate x509Certificate = managementService.generateX509Certificate(); //initialize DeviceConfigurationManager DeviceConfigurationManager.getInstance().initConfig(); Certificate certificateByAlias = managementService .getCertificateByAlias(x509Certificate.getSerialNumber().toString()); Assert.assertNotNull(certificateByAlias); Assert.assertEquals(certificateByAlias.getType(), CertificateManagementConstants.X_509); log.info("GetCertificateByAlias Test Successful"); }
From source file:net.solarnetwork.node.setup.impl.DefaultSetupService.java
@Override public InstructionState processInstruction(Instruction instruction) { if (!INSTRUCTION_TOPIC_RENEW_CERTIFICATE.equalsIgnoreCase(instruction.getTopic())) { return null; }//from w w w . j a va 2 s. c o m PKIService pki = pkiService; if (pki == null) { return null; } String[] certParts = instruction.getAllParameterValues(INSTRUCTION_PARAM_CERTIFICATE); if (certParts == null) { log.warn("Certificate not provided with renew instruction"); return InstructionState.Declined; } String cert = org.springframework.util.StringUtils.arrayToDelimitedString(certParts, ""); log.debug("Got certificate renewal instruction with certificate data: {}", cert); try { pki.saveNodeSignedCertificate(cert); if (log.isInfoEnabled()) { X509Certificate nodeCert = pki.getNodeCertificate(); log.info("Installed node certificate {}, valid to {}", nodeCert.getSerialNumber(), nodeCert.getNotAfter()); } return InstructionState.Completed; } catch (CertificateException e) { log.error("Failed to install renewed certificate", e); } return null; }
From source file:no.digipost.signature.client.asice.signature.CreateXAdESProperties.java
public Document createPropertiesToSign(final List<ASiCEAttachable> files, final X509Certificate certificate) { byte[] certificateDigestValue; try {//from w w w.jav a 2 s. c om certificateDigestValue = sha1(certificate.getEncoded()); } catch (CertificateEncodingException e) { throw new CertificateException("Unable to get encoded from of certificate", e); } DigestAlgAndValueType certificateDigest = new DigestAlgAndValueType(sha1DigestMethod, certificateDigestValue); X509IssuerSerialType certificateIssuer = new X509IssuerSerialType(certificate.getIssuerDN().getName(), certificate.getSerialNumber()); SigningCertificate signingCertificate = new SigningCertificate( singletonList(new CertIDType(certificateDigest, certificateIssuer, null))); Date now = new Date(); 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: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 Number") public void testGetCertificateBySerial() throws KeystoreException, DeviceManagementException { X509Certificate x509Certificate = null; //generate and save a certificate x509Certificate = managementService.generateX509Certificate(); //initialize DeviceConfigurationManager DeviceConfigurationManager.getInstance().initConfig(); CertificateResponse certificateBySerial = managementService .getCertificateBySerial(x509Certificate.getSerialNumber().toString()); Assert.assertNotNull(certificateBySerial); Assert.assertEquals(certificateBySerial.getSerialNumber(), x509Certificate.getSerialNumber().toString()); log.info("GetCertificateBySerial Test Successful"); }
From source file:org.viafirma.nucleo.validacion.OcspValidatorHandler.java
/** * Genera una nueva peticin OCSP para el certificado indicado. * //from ww w.j ava2 s. c o m * @param certificadoX509 * Certificado que deseamos validar. * @param certificadoX509Emisor * Certificado emisor del certificado a validar. * @return Peticin OCSP * @throws OCSPException */ private OCSPReq generateRequest(X509Certificate certificadoX509, X509Certificate certificadoX509Emisor) throws OCSPException { // 1 -Generamos el identificador CertificateID id = new CertificateID(CertificateID.HASH_SHA1, certificadoX509Emisor, certificadoX509.getSerialNumber()); // 2- Generador de peticiones ocsp OCSPReqGenerator requestGenerator = new OCSPReqGenerator(); requestGenerator.addRequest(id); // 3- extensiones necesarias. RFC 2560 BigInteger time = BigInteger.valueOf(System.currentTimeMillis()); Vector<DERObjectIdentifier> oids = new Vector<DERObjectIdentifier>(); oids.add(OCSPObjectIdentifiers.id_pkix_ocsp_nonce); Vector<X509Extension> values = new Vector<X509Extension>(); values.add(new X509Extension(false, new DEROctetString(time.toByteArray()))); // 4. Aadimos las extensiones necesarias al generador requestGenerator.setRequestExtensions(new X509Extensions(oids, values)); // Generamos la peticin OCSP return requestGenerator.generate(); }