List of usage examples for java.security.cert X509Certificate getSerialNumber
public abstract BigInteger getSerialNumber();
From source file:be.fedict.eid.applet.service.signer.facets.XAdESSignatureFacet.java
/** * Gives back the JAXB CertID data structure. * //from www . ja v a 2 s. c o m * @param certificate * @param xadesObjectFactory * @param xmldsigObjectFactory * @param digestAlgorithm * @return */ public static CertIDType getCertID(X509Certificate certificate, ObjectFactory xadesObjectFactory, be.fedict.eid.applet.service.signer.jaxb.xmldsig.ObjectFactory xmldsigObjectFactory, DigestAlgo digestAlgorithm, boolean issuerNameNoReverseOrder) { CertIDType certId = xadesObjectFactory.createCertIDType(); X509IssuerSerialType issuerSerial = xmldsigObjectFactory.createX509IssuerSerialType(); certId.setIssuerSerial(issuerSerial); String issuerName; if (issuerNameNoReverseOrder) { try { /* * Make sure the DN is encoded using the same order as present * within the certificate. This is an Office2010 work-around. * Should be reverted back. * * XXX: not correct according to RFC 4514. */ issuerName = PrincipalUtil.getIssuerX509Principal(certificate).getName().replace(",", ", "); } catch (CertificateEncodingException e) { throw new RuntimeException("cert encoding error: " + e.getMessage(), e); } } else { issuerName = certificate.getIssuerX500Principal().toString(); } issuerSerial.setX509IssuerName(issuerName); issuerSerial.setX509SerialNumber(certificate.getSerialNumber()); byte[] encodedCertificate; try { encodedCertificate = certificate.getEncoded(); } catch (CertificateEncodingException e) { throw new RuntimeException("certificate encoding error: " + e.getMessage(), e); } DigestAlgAndValueType certDigest = getDigestAlgAndValue(encodedCertificate, xadesObjectFactory, xmldsigObjectFactory, digestAlgorithm); certId.setCertDigest(certDigest); return certId; }
From source file:com.zotoh.crypto.CryptoUte.java
private static SMIMESignedGenerator makeSignerGentor(PrivateKey key, Certificate[] certs, SigningAlgo algo) throws CertStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, GeneralSecurityException, CertificateEncodingException { SMIMESignedGenerator gen = new SMIMESignedGenerator("base64"); List<Certificate> lst = asList(true, certs); ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); caps.addCapability(SMIMECapability.dES_CBC); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); X509Certificate x0 = (X509Certificate) certs[0]; X509Certificate issuer = x0;/* w ww .j a va2s . c o m*/ X500Principal issuerDN; if (certs.length > 1) { issuer = (X509Certificate) certs[1]; } issuerDN = issuer.getSubjectX500Principal(); x0 = (X509Certificate) certs[0]; // // add an encryption key preference for encrypted responses - // normally this would be different from the signing certificate... // IssuerAndSerialNumber issAndSer = new IssuerAndSerialNumber(X500Name.getInstance(issuerDN.getEncoded()), x0.getSerialNumber()); Provider prov = Crypto.getInstance().getProvider(); signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(issAndSer)); try { JcaSignerInfoGeneratorBuilder bdr = new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider(prov).build()); bdr.setDirectSignature(true); ContentSigner cs = new JcaContentSignerBuilder(algo.toString()).setProvider(prov).build(key); bdr.setSignedAttributeGenerator( new DefaultSignedAttributeTableGenerator(new AttributeTable(signedAttrs))); gen.addSignerInfoGenerator(bdr.build(cs, x0)); gen.addCertificates(new JcaCertStore(lst)); return gen; } catch (OperatorCreationException e) { throw new GeneralSecurityException(e); } }
From source file:org.apigw.authserver.web.controller.ApplicationManagementController.java
private Certificate createCertificate(MultipartFile certificate, BindingResult result) { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Certificate cert = new Certificate(); if (certificate != null && certificate.getSize() > 0) { try {//from w ww .j a va 2 s . c o m PEMReader r = new PEMReader( new InputStreamReader(new ByteArrayInputStream(certificate.getBytes()))); Object certObj = r.readObject(); long reference = System.currentTimeMillis(); // validate certificate if (certObj instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) certObj; BigInteger serialNumber = x509cert.getSerialNumber(); String issuerDn = x509cert.getIssuerDN().getName(); String subjectDn = x509cert.getSubjectDN().getName(); cert.setCertificate(certificate.getBytes()); cert.setSerialNumber(serialNumber.toString()); cert.setIssuer(issuerDn); cert.setSubject(subjectDn); cert.setSubjectCommonName(extractFromDn(subjectDn, "CN")); cert.setSubjectOrganization(extractFromDn(subjectDn, "O")); cert.setSubjectOrganizationUnit(extractFromDn(subjectDn, "OU")); cert.setSubjectLocation(extractFromDn(subjectDn, "L")); cert.setSubjectCountry(extractFromDn(subjectDn, "C")); cert.setNotAfter(x509cert.getNotAfter()); cert.setNotBefore(x509cert.getNotBefore()); } else { String line; StringBuilder certString = new StringBuilder(); while ((line = r.readLine()) != null) { certString.append(line + "\n"); } log.warn( "Bad certificate [{}]: Provided certificate was of the wrong type: {}. Certificate: \n{}", new Object[] { reference, certObj, certString.toString() }); result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt (Reference: " + reference + ")"); } r.close(); } catch (IOException e) { log.warn("Bad certificate"); result.rejectValue("certificates", "invalid.certificate", "Certifikatet r ej giltigt "); } } return cert; }
From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspHttpStandaloneTest.java
/** * Tests ocsp message/*from www . j a v a 2s .c o m*/ * * @throws Exception * error */ @Test public void test02OcspGood() throws Exception { @SuppressWarnings("unused") String subjectDnCA = CertTools.getSubjectDN(unknowncacert); // And an OCSP request OCSPReqBuilder gen = new OCSPReqBuilder(); final X509Certificate ocspTestCert = getActiveTestCert(); gen.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), getCaCert(ocspTestCert), ocspTestCert.getSerialNumber())); OCSPReq req = gen.build(); helper.reloadKeys(); // Send the request and receive a singleResponse SingleResp[] singleResps = helper.sendOCSPPost(req.getEncoded(), null, 0, 200); assertEquals("No of SingResps should be 1.", 1, singleResps.length); SingleResp singleResp = singleResps[0]; CertificateID certId = singleResp.getCertID(); assertEquals("Serno in response does not match serno in request.", certId.getSerialNumber(), ocspTestCert.getSerialNumber()); Object status = singleResp.getCertStatus(); assertEquals("Status is not null (good)", null, status); }
From source file:org.wso2.carbon.identity.authenticator.pki.cert.validation.ocsp.OCSPVerifier.java
/** * Gets the revocation status (Good, Revoked or Unknown) of the given peer * certificate.//from w w w .ja v a 2s .c om * * @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 * */ 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 (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:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java
@Test public void handleRenewCertificateInstruction() throws Exception { SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, "localhost", 80, false, TEST_PW_VALUE); expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce(); replayAll();/*from w ww.j a v a 2s . c o m*/ keystoreService.saveCACertificate(CA_CERT); keystoreService.generateNodeSelfSignedCertificate(TEST_DN); String csr = keystoreService.generateNodePKCS10CertificateRequestString(); X509Certificate originalCert; PemReader pemReader = new PemReader(new StringReader(csr)); try { PemObject pem = pemReader.readPemObject(); PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent()); originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate()); String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert }); keystoreService.saveNodeSignedCertificate(signedPem); log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem); assertThat("Generated CSR", csr, notNullValue()); } finally { pemReader.close(); } // now let's renew! KeyStore keyStore = loadKeyStore(); PrivateKey nodeKey = (PrivateKey) keyStore.getKey("node", TEST_PW_VALUE.toCharArray()); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA256WithRSA"); ContentSigner signer = signerBuilder.build(nodeKey); PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder( JcaX500NameUtil.getSubject(originalCert), SubjectPublicKeyInfo.getInstance(originalCert.getPublicKey().getEncoded())); X509Certificate renewedCert = PKITestUtils.sign(builder.build(signer), CA_CERT, CA_KEY_PAIR.getPrivate()); String renewedSignedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { renewedCert }); BasicInstruction instr = new BasicInstruction(DefaultSetupService.INSTRUCTION_TOPIC_RENEW_CERTIFICATE, new Date(), "123", "456", new BasicInstructionStatus(456L, InstructionState.Received, new Date())); for (int i = 0; i < renewedSignedPem.length(); i += 256) { int end = i + (i + 256 < renewedSignedPem.length() ? 256 : renewedSignedPem.length() - i); instr.addParameter(DefaultSetupService.INSTRUCTION_PARAM_CERTIFICATE, renewedSignedPem.substring(i, end)); } InstructionState state = service.processInstruction(instr); assertThat("Instruction state", state, equalTo(InstructionState.Completed)); X509Certificate nodeCert = keystoreService.getNodeCertificate(); assertThat("Node cert is now renewed cert", nodeCert, equalTo(renewedCert)); }
From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java
public X509Certificate extractCertificateFromSignature(String headerSignature) throws KeystoreException { if (headerSignature == null || headerSignature.isEmpty()) { return null; }// w w w . j a v a 2s . c o m try { KeyStoreReader keyStoreReader = new KeyStoreReader(); CMSSignedData signedData = new CMSSignedData(Base64.decodeBase64(headerSignature.getBytes())); Store reqStore = signedData.getCertificates(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null); if (reqCerts != null && reqCerts.size() > 0) { CertificateFactory certificateFactory = CertificateFactory .getInstance(CertificateManagementConstants.X_509); X509CertificateHolder holder = reqCerts.iterator().next(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(holder.getEncoded()); X509Certificate reqCert = (X509Certificate) certificateFactory .generateCertificate(byteArrayInputStream); if (reqCert != null && reqCert.getSerialNumber() != null) { Certificate lookUpCertificate = keyStoreReader .getCertificateByAlias(reqCert.getSerialNumber().toString()); if (lookUpCertificate instanceof X509Certificate) { return (X509Certificate) lookUpCertificate; } } } } catch (CMSException e) { String errorMsg = "CMSException when decoding certificate signature"; throw new KeystoreException(errorMsg, e); } catch (IOException e) { String errorMsg = "IOException when decoding certificate signature"; throw new KeystoreException(errorMsg, e); } catch (CertificateException e) { String errorMsg = "CertificateException when decoding certificate signature"; throw new KeystoreException(errorMsg, e); } return null; }
From source file:org.votingsystem.web.ejb.SignatureBean.java
private CertificateVS checkAuthorityCertDB(X509Certificate x509AuthorityCert) throws CertificateException, NoSuchAlgorithmException, NoSuchProviderException, ExceptionVS { log.info(x509AuthorityCert.getSubjectDN().toString()); Query query = dao.getEM().createNamedQuery("findCertBySerialNumberAndType") .setParameter("type", CertificateVS.Type.CERTIFICATE_AUTHORITY) .setParameter("serialNumber", x509AuthorityCert.getSerialNumber().longValue()); CertificateVS certificateVS = dao.getSingleResult(CertificateVS.class, query); if (certificateVS == null) { certificateVS = dao.persist(CertificateVS.AUTHORITY(x509AuthorityCert, null)); log.info("ADDED NEW FILE SYSTEM CA CERT - certificateVS.id:" + certificateVS.getId()); } else if (CertificateVS.State.OK != certificateVS.getState()) { throw new ExceptionVS("File system athority cert: " + x509AuthorityCert.getSubjectDN() + " }' " + " - certificateVS.id: " + certificateVS.getId() + " - state:" + certificateVS.getState()); } else if (certificateVS.getType() != CertificateVS.Type.CERTIFICATE_AUTHORITY) { String msg = "Updated from type " + certificateVS.getType() + " to type 'CERTIFICATE_AUTHORITY'"; certificateVS.setDescription(certificateVS.getDescription() + "###" + msg); certificateVS.setType(CertificateVS.Type.CERTIFICATE_AUTHORITY); dao.merge(certificateVS);/*from www .ja v a 2 s .c om*/ } return certificateVS; }
From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java
@Test public void renewNetworkCertificate() throws Exception { SetupIdentityInfo info = new SetupIdentityInfo(1L, TEST_CONF_VALUE, TEST_SOLARIN_HOST, getHttpServerPort(), false, TEST_PW_VALUE);/*from w ww .j a va 2 s . c o m*/ expect(setupIdentityDao.getSetupIdentityInfo()).andReturn(info).atLeastOnce(); replayAll(); keystoreService.saveCACertificate(CA_CERT); keystoreService.generateNodeSelfSignedCertificate(TEST_DN); String csr = keystoreService.generateNodePKCS10CertificateRequestString(); X509Certificate originalCert; PemReader pemReader = new PemReader(new StringReader(csr)); try { PemObject pem = pemReader.readPemObject(); PKCS10CertificationRequest req = new PKCS10CertificationRequest(pem.getContent()); originalCert = PKITestUtils.sign(req, CA_CERT, CA_KEY_PAIR.getPrivate()); String signedPem = PKITestUtils.getPKCS7Encoding(new X509Certificate[] { originalCert }); keystoreService.saveNodeSignedCertificate(signedPem); log.debug("Saved signed node certificate {}:\n{}", originalCert.getSerialNumber(), signedPem); assertThat("Generated CSR", csr, notNullValue()); } finally { pemReader.close(); } // now let's renew! AbstractTestHandler handler = new AbstractTestHandler() { @Override protected boolean handleInternal(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws Exception { assertEquals("POST", request.getMethod()); assertEquals("/solarin/api/v1/sec/cert/renew", target); String password = request.getParameter("password"); assertEquals("foobar", password); String keystoreData = request.getParameter("keystore"); assertNotNull(keystoreData); byte[] data = Base64.decodeBase64(keystoreData); KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(new ByteArrayInputStream(data), password.toCharArray()); Certificate cert = keyStore.getCertificate("node"); assertNotNull(cert); assertTrue(cert instanceof X509Certificate); X509Certificate nodeCert = (X509Certificate) cert; assertEquals(new X500Principal(TEST_DN), nodeCert.getSubjectX500Principal()); assertEquals(CA_CERT.getSubjectX500Principal(), nodeCert.getIssuerX500Principal()); response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.write("{\"success\":true}"); out.flush(); response.flushBuffer(); return true; } }; httpServer.addHandler(handler); service.renewNetworkCertificate("foobar"); }
From source file:com.otterca.persistence.dao.X509CertificateDaoDatastore.java
/** * @see com.otterca.persistence.dao.X509CertificateDao#put(java.security.cert * .X509Certificate)/* w w w. ja v a 2s . co m*/ */ public void put(X509Certificate cert) throws IOException, CertificateEncodingException { // TODO: we want cert's issuer to be its parent. For now certs don't // have parents. Key key = generateKey(cert); Entity e = new Entity(key); // also set parent... e.setProperty(CERTIFICATE, new Blob(cert.getEncoded())); // up to 20 octets - 40 characters e.setProperty(SERIAL_NUMBER, cert.getSerialNumber().toString(16)); // up to 500 unicode characters e.setProperty(SUBJECT_DN, cert.getSubjectDN().getName()); // up to 500 unicode characters e.setProperty(ISSUER_DN, cert.getIssuerDN().getName()); e.setProperty(NOT_BEFORE, cert.getNotBefore()); e.setProperty(NOT_AFTER, cert.getNotAfter()); // RFC search criteria e.setProperty(COMMON_NAME, x509CertUtil.getName(cert)); e.setProperty(FINGERPRINT, x509CertUtil.getFingerprint(cert)); e.setProperty(CERT_HASH, x509CertUtil.getCertificateHash(cert)); e.setProperty(ISSUER_HASH, x509CertUtil.getIHash(cert)); e.setProperty(SUBJECT_HASH, x509CertUtil.getSHash(cert)); // e.setProperty(AKID_HASH, x509CertUtil.getAkidHash(cert)); e.setProperty(SKID_HASH, x509CertUtil.getSkidHash(cert)); // e.setProperty(IANDS_HASH, x509CertUtil.getIandSHash(cert)); // e.setProperty(EMAIL) ?... e.setUnindexedProperty(TRUSTED, false); e.setUnindexedProperty(STATUS, UNKNOWN); datastore.put(e); }