List of usage examples for org.bouncycastle.asn1.x509 GeneralNames GeneralNames
private GeneralNames(ASN1Sequence seq)
From source file:org.qipki.ca.tests.http.QiPkiHttpCaTest.java
License:Open Source License
private void testCA() throws InterruptedException, IOException, JSONException, GeneralSecurityException { // Get CA list HttpGet get = new HttpGet(caApi.caListUri().get()); addAcceptJsonHeader(get);/*from w w w . ja v a2 s .c o m*/ String jsonCaList = httpClient.execute(get, strResponseHandler); LOGGER.debug("CAs List: {}", new JSONObject(jsonCaList).toString(2)); RestListValue caList = valueBuilderFactory.newValueFromJSON(RestListValue.class, jsonCaList); CAValue firstCa = (CAValue) caList.items().get().get(0); // Get first CA as Value get = new HttpGet(firstCa.uri().get()); addAcceptJsonHeader(get); String caJson = httpClient.execute(get, strResponseHandler); CAValue ca = valueBuilderFactory.newValueFromJSON(CAValue.class, caJson); LOGGER.debug("First CA JSON:\n{}", ca.toJSON()); // Get first CA CRL get = new HttpGet(ca.crlUri().get()); String crl = httpClient.execute(get, strResponseHandler); LOGGER.debug("First CA CRL:\n{}", crl); X509CRL x509CRL = cryptio.readCRLPEM(new StringReader(crl)); // Create a new CryptoStore HttpPost post = new HttpPost(caApi.cryptoStoreListUri().get()); addAcceptJsonHeader(post); CryptoStoreFactoryParamsValue csParams = paramsFactory.createCryptoStoreFactoryParams(testCryptoStoreName, KeyStoreType.JKS, "changeit".toCharArray()); post.setEntity(new StringEntity(csParams.toJSON())); String csJson = httpClient.execute(post, strResponseHandler); CryptoStoreValue cryptoStore = valueBuilderFactory.newValueFromJSON(CryptoStoreValue.class, csJson); // Create a new CA post = new HttpPost(caApi.caListUri().get()); addAcceptJsonHeader(post); KeyPairSpecValue keyPairSpec = cryptoValuesFactory.createKeySpec(AsymetricAlgorithm.RSA, 512); CAFactoryParamsValue caParams = paramsFactory.createCAFactoryParams(cryptoStore.uri().get(), testCaName, 1, "CN=" + testCaName, keyPairSpec, null); post.setEntity(new StringEntity(caParams.toJSON())); caJson = httpClient.execute(post, strResponseHandler); ca = valueBuilderFactory.newValueFromJSON(CAValue.class, caJson); // Create a new X509Profile post = new HttpPost(caApi.x509ProfileListUri().get()); addAcceptJsonHeader(post); X509ProfileFactoryParamsValue profileParams = paramsFactory.createX509ProfileFactoryParams("SSLClient", 1, "A simple SSLClient x509 profile for unit tests", x509ExtValuesFactory.buildKeyUsagesValue(true, EnumSet.of(KeyUsage.keyEncipherment, KeyUsage.digitalSignature)), x509ExtValuesFactory.buildExtendedKeyUsagesValue(false, EnumSet.of(ExtendedKeyUsage.clientAuth)), x509ExtValuesFactory.buildNetscapeCertTypesValue(false, EnumSet.of(NetscapeCertType.sslClient)), x509ExtValuesFactory.buildBasicConstraintsValue(true, false, 0), null); post.setEntity(new StringEntity(profileParams.toJSON())); String sslClientProfileJson = httpClient.execute(post, strResponseHandler); X509ProfileValue sslClientProfile = valueBuilderFactory.newValueFromJSON(X509ProfileValue.class, sslClientProfileJson); // Add profile to CA post = new HttpPost(ca.uri().get()); addAcceptJsonHeader(post); ValueBuilder<CAValue> caValueBuilder = valueBuilderFactory.newValueBuilder(CAValue.class).withPrototype(ca); // Needed as Values are immutables ca = caValueBuilder.prototype(); ca.allowedX509Profiles().get().add( paramsFactory.createX509ProfileAssignment(sslClientProfile.uri().get(), KeyEscrowPolicy.allowed)); ca = caValueBuilder.newInstance(); post.setEntity(new StringEntity(ca.toJSON())); caJson = httpClient.execute(post, strResponseHandler); ca = valueBuilderFactory.newValueFromJSON(CAValue.class, caJson); // Request certificate on X509Factory with a PKCS#10 request using the first CA KeyPair keyPair = asymGenerator .generateKeyPair(new AsymetricGeneratorParameters(AsymetricAlgorithm.RSA, 512)); PKCS10CertificationRequest pkcs10 = x509Generator.generatePKCS10(new DistinguishedName("CN=qipki"), keyPair, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "qipki@codeartisans.org"))); String pkcs10PEM = cryptio.asPEM(pkcs10).toString(); LOGGER.debug("Will request a new X509 with the following PKCS#10: " + pkcs10PEM); X509FactoryParamsValue x509FactoryParams = paramsFactory.createX509FactoryParams(ca.uri().get(), sslClientProfile.uri().get(), pkcs10PEM); post = new HttpPost(caApi.x509ListUri().get()); addAcceptJsonHeader(post); post.setEntity(new StringEntity(x509FactoryParams.toJSON())); String jsonX509 = httpClient.execute(post, strResponseHandler); X509Value newX509 = valueBuilderFactory.newValueFromJSON(X509Value.class, jsonX509); LOGGER.debug("New X509 created using /api/x509/factory after POST/302/REDIRECT: {}", newX509.toJSON()); // Get detailled info about new X509 get = new HttpGet(newX509.detailUri().get()); addAcceptJsonHeader(get); String jsonX509Detail = httpClient.execute(get, strResponseHandler); LOGGER.debug("New X509 detail: {}", new JSONObject(jsonX509Detail).toString(2)); X509DetailValue newX509Detail = valueBuilderFactory.newValueFromJSON(X509DetailValue.class, jsonX509Detail); assertTrue(newX509Detail.keysExtensions().get().extendedKeyUsages().get().extendedKeyUsages().get() .contains(ExtendedKeyUsage.clientAuth)); assertTrue(newX509Detail.keysExtensions().get().netscapeCertTypes().get().netscapeCertTypes().get() .contains(NetscapeCertType.sslClient)); // Get X509 list get = new HttpGet(caApi.x509ListUri().get()); addAcceptJsonHeader(get); String jsonX509List = httpClient.execute(get, strResponseHandler); LOGGER.debug("X509s List: {}", new JSONObject(jsonX509List).toString(2)); RestListValue x509List = valueBuilderFactory.newValueFromJSON(RestListValue.class, jsonX509List); X509Value firstX509 = (X509Value) x509List.items().get().get(0); // Get first X509 get = new HttpGet(firstX509.uri().get()); addAcceptJsonHeader(get); jsonX509 = httpClient.execute(get, strResponseHandler); LOGGER.debug("First X509: {}", new JSONObject(jsonX509).toString(2)); firstX509 = valueBuilderFactory.newValueFromJSON(X509Value.class, jsonX509); // Revoke first X509 X509RevocationParamsValue x509RevocationParams = paramsFactory .createX509RevocationParams(RevocationReason.cessationOfOperation); post = new HttpPost(firstX509.revocationUri().get()); addAcceptJsonHeader(post); post.setEntity(new StringEntity(x509RevocationParams.toJSON())); String jsonRevocation = httpClient.execute(post, strResponseHandler); LOGGER.debug(jsonRevocation); // Get KeyPair list get = new HttpGet(caApi.escrowedKeyPairListUri().get()); addAcceptJsonHeader(get); String jsonKeyPairList = httpClient.execute(get, strResponseHandler); LOGGER.debug("EscrowedKeyPair List: {}", new JSONObject(jsonKeyPairList).toString(2)); // Create KeyPair EscrowedKeyPairFactoryParamsValue escrowParams = paramsFactory .createEscrowedKeyPairFactoryParams(AsymetricAlgorithm.RSA, 512); post = new HttpPost(caApi.escrowedKeyPairListUri().get()); addAcceptJsonHeader(post); post.setEntity(new StringEntity(escrowParams.toJSON())); String jsonEscrowed = httpClient.execute(post, strResponseHandler); LOGGER.debug("EscrowedKeyPair : {}", new JSONObject(jsonEscrowed).toString(2)); EscrowedKeyPairValue ekp = valueBuilderFactory.newValueFromJSON(EscrowedKeyPairValue.class, jsonEscrowed); // Recover KeyPair get = new HttpGet(ekp.recoveryUri().get()); addAcceptJsonHeader(get); String kpPem = httpClient.execute(get, strResponseHandler); LOGGER.debug("EscrowedKeyPair PEM: {}", kpPem); KeyPair keypair = cryptio.readKeyPairPEM(new StringReader(kpPem)); // Issue X509Certificate using an escrowed keypair String dn = "CN=qipki-escrowed"; LOGGER.debug("Will request a new X509 with the following DN: " + dn); x509FactoryParams = paramsFactory.createX509FactoryParams(ca.uri().get(), sslClientProfile.uri().get(), ekp.uri().get(), dn); post = new HttpPost(caApi.x509ListUri().get()); addAcceptJsonHeader(post); post.setEntity(new StringEntity(x509FactoryParams.toJSON())); jsonX509 = httpClient.execute(post, strResponseHandler); newX509 = valueBuilderFactory.newValueFromJSON(X509Value.class, jsonX509); LOGGER.debug("New X509 created using /api/x509/factory and an escrowed keypair after POST/302/REDIRECT: {}", newX509.toJSON()); // Getting new X509 PEM get = new HttpGet(newX509.pemUri().get()); String x509pem = httpClient.execute(get, strResponseHandler); LOGGER.debug("X509 created from escrowed keypair PEM: {}", x509pem); X509Certificate x509Certificate = cryptio.readX509PEM(new StringReader(x509pem)); // Getting EscrowedKeyPair from X509Certificate get = new HttpGet(newX509.recoveryUri().get()); kpPem = httpClient.execute(get, strResponseHandler); LOGGER.debug("EscrowedKeyPair PEM: {}", kpPem); keypair = cryptio.readKeyPairPEM(new StringReader(kpPem)); // Create local PKCS#12 keystore with keypair, certificate and full certchain char[] password = "changeit".toCharArray(); KeyStore ks = KeyStore.getInstance(KeyStoreType.PKCS12.typeString(), BouncyCastleProvider.PROVIDER_NAME); ks.load(null, password); ks.setEntry("wow", new KeyStore.PrivateKeyEntry(keyPair.getPrivate(), new Certificate[] { x509Certificate }), new KeyStore.PasswordProtection(password)); String base64encodedp12 = cryptio.base64Encode(ks, password); System.out.println(base64encodedp12); // Exporting CA in a PKCS#12 keystore get = new HttpGet(ca.exportUri().get() + "?password=changeit"); byte[] responseBytes = httpClient.execute(get, bytesResponseHandler); ks = KeyStore.getInstance(KeyStoreType.PKCS12.typeString(), BouncyCastleProvider.PROVIDER_NAME); ks.load(new ByteArrayInputStream(responseBytes), password); base64encodedp12 = cryptio.base64Encode(ks, password); System.out.println(base64encodedp12); // Exporting CA in a JKS keystore get = new HttpGet(ca.exportUri().get() + "?password=changeit&kstype=jks"); responseBytes = httpClient.execute(get, bytesResponseHandler); ks = KeyStore.getInstance(KeyStoreType.JKS.typeString()); ks.load(new ByteArrayInputStream(responseBytes), password); base64encodedp12 = cryptio.base64Encode(ks, password); System.out.println(base64encodedp12); }
From source file:org.qipki.crypto.x509.X509ExtensionsBuilderImpl.java
License:Open Source License
@Override public CRLDistPoint buildCRLDistributionPoints(Map<X500Principal, Iterable<String>> crlDistPointsData) { List<DistributionPoint> distributionPoints = new ArrayList<DistributionPoint>(); for (Map.Entry<X500Principal, Iterable<String>> eachIssuerEntry : crlDistPointsData.entrySet()) { GeneralName issuerName = new GeneralName(new X509Name(eachIssuerEntry.getKey().getName())); ASN1EncodableVector issuerVector = new ASN1EncodableVector(); issuerVector.add(issuerName);/* ww w .jav a2 s.com*/ GeneralNames issuerNames = new GeneralNames(new DERSequence(issuerVector)); for (String eachEndpoint : eachIssuerEntry.getValue()) { GeneralName endpointName = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(eachEndpoint)); ASN1EncodableVector epVector = new ASN1EncodableVector(); epVector.add(endpointName); GeneralNames endpointNames = new GeneralNames(new DERSequence(epVector)); DistributionPointName dpn = new DistributionPointName(DistributionPointName.FULL_NAME, endpointNames); distributionPoints.add(new DistributionPoint(dpn, null, issuerNames)); } } return new CRLDistPoint(distributionPoints.toArray(new DistributionPoint[distributionPoints.size()])); }
From source file:org.shredzone.acme4j.util.CertificateUtils.java
License:Apache License
/** * Creates a self-signed {@link X509Certificate} that can be used for * {@link org.shredzone.acme4j.challenge.TlsSni01Challenge}. The certificate is valid * for 7 days./*from w ww. jav a 2 s .c o m*/ * * @param keypair * A domain {@link KeyPair} to be used for the challenge * @param subject * Subject to create a certificate for * @return Created certificate * @deprecated Will be removed when * {@link org.shredzone.acme4j.challenge.TlsSni01Challenge} is removed */ @Deprecated public static X509Certificate createTlsSniCertificate(KeyPair keypair, String subject) throws IOException { final long now = System.currentTimeMillis(); final long validSpanMs = 7 * 24 * 60 * 60 * 1000L; final String signatureAlg = "SHA256withRSA"; try { X500Name issuer = new X500Name("CN=acme.invalid"); BigInteger serial = BigInteger.valueOf(now); Date notBefore = new Date(now); Date notAfter = new Date(now + validSpanMs); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, keypair.getPublic()); GeneralName[] gns = new GeneralName[1]; gns[0] = new GeneralName(GeneralName.dNSName, subject); certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns)); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlg); byte[] cert = certBuilder.build(signerBuilder.build(keypair.getPrivate())).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert)); } catch (CertificateException | OperatorCreationException ex) { throw new IOException(ex); } }
From source file:org.shredzone.acme4j.util.CertificateUtils.java
License:Apache License
/** * Creates a self-signed {@link X509Certificate} that can be used for * {@link TlsSni02Challenge}. The certificate is valid for 7 days. * * @param keypair// w w w. ja v a2 s . c o m * A domain {@link KeyPair} to be used for the challenge * @param sanA * SAN-A to be used in the certificate * @param sanB * SAN-B to be used in the certificate * @return Created certificate */ public static X509Certificate createTlsSni02Certificate(KeyPair keypair, String sanA, String sanB) throws IOException { final long now = System.currentTimeMillis(); final long validSpanMs = 7 * 24 * 60 * 60 * 1000L; final String signatureAlg = "SHA256withRSA"; try { X500Name issuer = new X500Name("CN=acme.invalid"); BigInteger serial = BigInteger.valueOf(now); Date notBefore = new Date(now); Date notAfter = new Date(now + validSpanMs); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serial, notBefore, notAfter, issuer, keypair.getPublic()); GeneralName[] gns = new GeneralName[2]; gns[0] = new GeneralName(GeneralName.dNSName, sanA); gns[1] = new GeneralName(GeneralName.dNSName, sanB); certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns)); JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlg); byte[] cert = certBuilder.build(signerBuilder.build(keypair.getPrivate())).getEncoded(); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert)); } catch (CertificateException | OperatorCreationException ex) { throw new IOException(ex); } }
From source file:org.shredzone.acme4j.util.CSRBuilder.java
License:Apache License
/** * Signs the completed CSR./*from w w w . jav a2 s . c o m*/ * * @param keypair * {@link KeyPair} to sign the CSR with */ public void sign(KeyPair keypair) throws IOException { if (namelist.isEmpty()) { throw new IllegalStateException("No domain was set"); } if (keypair == null) { throw new IllegalArgumentException("keypair must not be null"); } try { GeneralName[] gns = new GeneralName[namelist.size()]; for (int ix = 0; ix < namelist.size(); ix++) { gns[ix] = new GeneralName(GeneralName.dNSName, namelist.get(ix)); } GeneralNames subjectAltName = new GeneralNames(gns); PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder( namebuilder.build(), keypair.getPublic()); ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator(); extensionsGenerator.addExtension(Extension.subjectAlternativeName, false, subjectAltName); p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate()); PrivateKey pk = keypair.getPrivate(); JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder( pk instanceof ECKey ? EC_SIGNATURE_ALG : SIGNATURE_ALG); ContentSigner signer = csBuilder.build(pk); csr = p10Builder.build(signer); } catch (OperatorCreationException ex) { throw new IOException("Could not generate CSR", ex); } }
From source file:org.signserver.module.tsa.MSAuthCodeTimeStampSigner.java
License:Open Source License
/** * The main method performing the actual timestamp operation. * Expects the signRequest to be a GenericSignRequest contining a * TimeStampRequest/*from w w w . j a va2s . c om*/ * * @param signRequest * @param requestContext * @return the sign response * @see org.signserver.server.IProcessable#processData(org.signserver.common.ProcessRequest, org.signserver.common.RequestContext) */ public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext) throws IllegalRequestException, CryptoTokenOfflineException, SignServerException { // Log values final LogMap logMap = LogMap.getInstance(requestContext); try { final ISignRequest sReq = (ISignRequest) signRequest; final byte[] requestbytes = (byte[]) sReq.getRequestData(); if (requestbytes == null || requestbytes.length == 0) { LOG.error("Request must contain data"); throw new IllegalRequestException("Request must contain data"); } // Check that the request contains a valid TimeStampRequest object. if (!(signRequest instanceof GenericSignRequest)) { final IllegalRequestException exception = new IllegalRequestException( "Recieved request wasn't an expected GenericSignRequest. "); LOG.error("Received request wasn't an expected GenericSignRequest"); throw exception; } if (!((sReq.getRequestData() instanceof TimeStampRequest) || (sReq.getRequestData() instanceof byte[]))) { final IllegalRequestException exception = new IllegalRequestException( "Recieved request data wasn't an expected TimeStampRequest. "); LOG.error("Received request data wasn't an expected TimeStampRequest"); throw exception; } if (!validChain) { LOG.error("Certificate chain not correctly configured"); throw new CryptoTokenOfflineException("Certificate chain not correctly configured"); } ASN1Primitive asn1obj = ASN1Primitive.fromByteArray(Base64.decode(requestbytes)); ASN1Sequence asn1seq = ASN1Sequence.getInstance(asn1obj); if (asn1seq.size() != 2) { LOG.error("Wrong structure, should be an ASN1Sequence with 2 elements"); throw new IllegalRequestException("Wrong structure, should be an ASN1Sequence with 2 elements"); } ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1seq.getObjectAt(0)); ASN1Sequence asn1seq1 = ASN1Sequence.getInstance(asn1seq.getObjectAt(1)); final ContentInfo ci = new ContentInfo(asn1seq1); if (!oid.getId().equals(msOID)) { LOG.error("Invalid OID in request: " + oid.getId()); throw new IllegalRequestException("Invalid OID in request: " + oid.getId()); } if (asn1seq1.size() != 2) { LOG.error( "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence"); throw new IllegalRequestException( "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence"); } oid = ASN1ObjectIdentifier.getInstance(asn1seq1.getObjectAt(0)); if (!oid.getId().equals(dataOID)) { throw new IllegalRequestException("Wrong contentType OID: " + oid.getId()); } ASN1TaggedObject tag = ASN1TaggedObject.getInstance(asn1seq1.getObjectAt(1)); if (tag.getTagNo() != 0) { throw new IllegalRequestException("Wrong tag no (should be 0): " + tag.getTagNo()); } ASN1OctetString octets = ASN1OctetString.getInstance(tag.getObject()); byte[] content = octets.getOctets(); final ITimeSource timeSrc; final Date date; byte[] der; ICryptoInstance crypto = null; try { crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext); // get signing cert certificate chain and private key List<Certificate> certList = this.getSigningCertificateChain(crypto); if (certList == null) { throw new SignServerException("Null certificate chain. This signer needs a certificate."); } Certificate[] certs = (Certificate[]) certList.toArray(new Certificate[certList.size()]); // Sign X509Certificate x509cert = (X509Certificate) certs[0]; timeSrc = getTimeSource(); if (LOG.isDebugEnabled()) { LOG.debug("TimeSource: " + timeSrc.getClass().getName()); } date = timeSrc.getGenTime(); if (date == null) { throw new ServiceUnavailableException("Time source is not available"); } ASN1EncodableVector signedAttributes = new ASN1EncodableVector(); signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(date)))); if (includeSigningCertificateAttribute) { try { final DERInteger serial = new DERInteger(x509cert.getSerialNumber()); final X509CertificateHolder certHolder = new X509CertificateHolder(x509cert.getEncoded()); final X500Name issuer = certHolder.getIssuer(); final GeneralName name = new GeneralName(issuer); final GeneralNames names = new GeneralNames(name); final IssuerSerial is = new IssuerSerial(names, ASN1Integer.getInstance(serial)); final ESSCertID essCertid = new ESSCertID( MessageDigest.getInstance("SHA-1").digest(x509cert.getEncoded()), is); signedAttributes.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, new DERSet(new SigningCertificate(essCertid)))); } catch (NoSuchAlgorithmException e) { LOG.error("Can't find SHA-1 implementation: " + e.getMessage()); throw new SignServerException("Can't find SHA-1 implementation", e); } } AttributeTable signedAttributesTable = new AttributeTable(signedAttributes); DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator( signedAttributesTable); final String provider = cryptoToken.getProvider(ICryptoToken.PROVIDERUSAGE_SIGN); SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()); signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator); JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(signatureAlgo); contentSigner.setProvider(provider); final SignerInfoGenerator sig = signerInfoBuilder.build(contentSigner.build(crypto.getPrivateKey()), new X509CertificateHolder(x509cert.getEncoded())); JcaCertStore cs = new JcaCertStore(certList); CMSTypedData cmspba = new CMSProcessableByteArray(content); CMSSignedData cmssd = MSAuthCodeCMSUtils.generate(cmspba, true, Arrays.asList(sig), MSAuthCodeCMSUtils.getCertificatesFromStore(cs), Collections.emptyList(), ci); der = ASN1Primitive.fromByteArray(cmssd.getEncoded()).getEncoded(); } finally { releaseCryptoInstance(crypto, requestContext); } // Log values logMap.put(ITimeStampLogger.LOG_TSA_TIME, String.valueOf(date.getTime())); logMap.put(ITimeStampLogger.LOG_TSA_TIMESOURCE, timeSrc.getClass().getSimpleName()); final String archiveId = createArchiveId(requestbytes, (String) requestContext.get(RequestContext.TRANSACTION_ID)); final GenericSignResponse signResponse; byte[] signedbytes = Base64.encode(der, false); logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED, new String(signedbytes)); final Collection<? extends Archivable> archivables = Arrays.asList( new DefaultArchivable(Archivable.TYPE_REQUEST, REQUEST_CONTENT_TYPE, requestbytes, archiveId), new DefaultArchivable(Archivable.TYPE_RESPONSE, RESPONSE_CONTENT_TYPE, signedbytes, archiveId)); if (signRequest instanceof GenericServletRequest) { signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes, getSigningCertificate(signRequest, requestContext), archiveId, archivables, RESPONSE_CONTENT_TYPE); } else { signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes, getSigningCertificate(signRequest, requestContext), archiveId, archivables); } // The client can be charged for the request requestContext.setRequestFulfilledByWorker(true); return signResponse; } catch (IOException e) { final IllegalRequestException exception = new IllegalRequestException("IOException: " + e.getMessage(), e); LOG.error("IOException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (CMSException e) { final SignServerException exception = new SignServerException(e.getMessage(), e); LOG.error("CMSException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (OperatorCreationException e) { final SignServerException exception = new SignServerException(e.getMessage(), e); LOG.error("OperatorCreationException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (CertificateEncodingException e) { final SignServerException exception = new SignServerException(e.getMessage(), e); LOG.error("CertificateEncodingException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } catch (ArrayIndexOutOfBoundsException e) { // the BC base64 decoder doesn't check the the base64 input length... final IllegalRequestException exception = new IllegalRequestException( "ArrayIndexOutOfBoundsException: " + e.getMessage(), e); LOG.error("ArrayIndexOutOfBoundsException: ", e); logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage()); throw exception; } }
From source file:org.signserver.validationservice.server.ValidationTestUtils.java
License:Open Source License
public static CRLDistPoint generateDistPointWithUrl(URL cdpUrl) { GeneralName gn = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(cdpUrl.toExternalForm())); GeneralNames gns = new GeneralNames(gn); DistributionPointName dpn = new DistributionPointName(0, gns); return new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(dpn, null, null) }); }
From source file:org.signserver.validationservice.server.ValidationTestUtils.java
License:Open Source License
public static CRLDistPoint generateDistPointWithIssuer(String issuer) { GeneralName gn = new GeneralName(new X509Name(issuer)); GeneralNames gns = new GeneralNames(gn); DistributionPointName dpn = new DistributionPointName(0, gns); return new CRLDistPoint(new DistributionPoint[] { new DistributionPoint(dpn, null, null) }); }
From source file:org.sipfoundry.sipxconfig.cert.CertificateGenerator.java
License:Contributor Agreement License
@Override public X509Certificate createCertificate() throws GeneralSecurityException { try {/* ww w.ja va2 s .co m*/ KeyPair pair = getKeyPair(); X509v3CertificateBuilder gen = createCertificateGenerator(m_issuer, pair.getPublic()); gen.addExtension(X509Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pair.getPublic())); gen.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(false)); List<GeneralName> names = new ArrayList<GeneralName>(); if (StringUtils.isNotBlank(m_sipDomain)) { names.add(new GeneralName(GeneralName.uniformResourceIdentifier, format("sip:%s", m_sipDomain))); } names.add(new GeneralName(GeneralName.dNSName, getCommonName())); gen.addExtension(X509Extension.subjectAlternativeName, false, new GeneralNames((GeneralName[]) names.toArray(new GeneralName[names.size()]))); return CertificateUtils.generateCert(gen, getAlgorithm(), getAuthorityPrivateKey()); } catch (CertIOException e) { throw new GeneralSecurityException(e); } }
From source file:org.sufficientlysecure.keychain.pgp.PgpToX509.java
License:Open Source License
/** * Creates a self-signed certificate from a public and private key. The (critical) key-usage * extension is set up with: digital signature, non-repudiation, key-encipherment, key-agreement * and certificate-signing. The (non-critical) Netscape extension is set up with: SSL client and * S/MIME. A URI subjectAltName may also be set up. * * @param pubKey public key/*from w w w .jav a2s . co m*/ * @param privKey private key * @param subject subject (and issuer) DN for this certificate, RFC 2253 format preferred. * @param startDate date from which the certificate will be valid (defaults to current date and time * if null) * @param endDate date until which the certificate will be valid (defaults to current date and time * if null) * * @param subjAltNameURI URI to be placed in subjectAltName * @return self-signed certificate * @throws InvalidKeyException * @throws SignatureException * @throws NoSuchAlgorithmException * @throws IllegalStateException * @throws NoSuchProviderException * @throws CertificateException * @throws Exception * @author Bruno Harbulot */ public static X509Certificate createSelfSignedCert(PublicKey pubKey, PrivateKey privKey, X509Name subject, Date startDate, Date endDate, String subjAltNameURI) throws InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException { X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator(); certGenerator.reset(); /* * Sets up the subject distinguished name. Since it's a self-signed certificate, issuer and * subject are the same. */ certGenerator.setIssuerDN(subject); certGenerator.setSubjectDN(subject); /* * Sets up the validity dates. */ if (startDate == null) { startDate = new Date(System.currentTimeMillis()); } certGenerator.setNotBefore(startDate); if (endDate == null) { endDate = new Date(startDate.getTime() + (365L * 24L * 60L * 60L * 1000L)); Log.d(Constants.TAG, "end date is=" + DateFormat.getDateInstance().format(endDate)); } certGenerator.setNotAfter(endDate); /* * The serial-number of this certificate is 1. It makes sense because it's self-signed. */ certGenerator.setSerialNumber(BigInteger.ONE); /* * Sets the public-key to embed in this certificate. */ certGenerator.setPublicKey(pubKey); /* * Sets the signature algorithm. */ String pubKeyAlgorithm = pubKey.getAlgorithm(); if (pubKeyAlgorithm.equals("DSA")) { certGenerator.setSignatureAlgorithm("SHA1WithDSA"); } else if (pubKeyAlgorithm.equals("RSA")) { certGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption"); } else { RuntimeException re = new RuntimeException("Algorithm not recognised: " + pubKeyAlgorithm); Log.e(Constants.TAG, re.getMessage(), re); throw re; } /* * Adds the Basic Constraint (CA: true) extension. */ certGenerator.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); /* * Adds the subject key identifier extension. */ SubjectKeyIdentifier subjectKeyIdentifier = new SubjectKeyIdentifierStructure(pubKey); certGenerator.addExtension(X509Extensions.SubjectKeyIdentifier, false, subjectKeyIdentifier); /* * Adds the authority key identifier extension. */ AuthorityKeyIdentifier authorityKeyIdentifier = new AuthorityKeyIdentifierStructure(pubKey); certGenerator.addExtension(X509Extensions.AuthorityKeyIdentifier, false, authorityKeyIdentifier); /* * Adds the subject alternative-name extension. */ if (subjAltNameURI != null) { GeneralNames subjectAltNames = new GeneralNames( new GeneralName(GeneralName.uniformResourceIdentifier, subjAltNameURI)); certGenerator.addExtension(X509Extensions.SubjectAlternativeName, false, subjectAltNames); } /* * Creates and sign this certificate with the private key corresponding to the public key of * the certificate (hence the name "self-signed certificate"). */ X509Certificate cert = certGenerator.generate(privKey); /* * Checks that this certificate has indeed been correctly signed. */ cert.verify(pubKey); return cert; }