Example usage for org.bouncycastle.asn1.x509 GeneralName GeneralName

List of usage examples for org.bouncycastle.asn1.x509 GeneralName GeneralName

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 GeneralName GeneralName.

Prototype

public GeneralName(X500Name dirName) 

Source Link

Usage

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);// w  ww.  j a v a  2  s  .  c  om
        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.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  ww w  . j av a 2  s.co  m
 *
 * @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.module.tsa.TimeStampSigner.java

License:Open Source License

private TimeStampTokenGenerator getTimeStampTokenGenerator(final ICryptoInstance crypto,
        final TimeStampRequest timeStampRequest, final LogMap logMap) throws IllegalRequestException,
        CryptoTokenOfflineException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, CertStoreException, OperatorCreationException, SignServerException {

    TimeStampTokenGenerator timeStampTokenGen = null;
    try {/*w  w  w. ja v  a 2  s  .  co  m*/
        ASN1ObjectIdentifier tSAPolicyOID = timeStampRequest.getReqPolicy();
        if (tSAPolicyOID == null) {
            tSAPolicyOID = defaultTSAPolicyOID;
        }
        logMap.put(ITimeStampLogger.LOG_TSA_POLICYID, tSAPolicyOID.getId());

        final X509Certificate signingCert = (X509Certificate) getSigningCertificate(crypto);
        if (signingCert == null) {
            throw new CryptoTokenOfflineException("No certificate for this signer");
        }

        DigestCalculatorProvider calcProv = new BcDigestCalculatorProvider();
        DigestCalculator calc = calcProv.get(new AlgorithmIdentifier(TSPAlgorithms.SHA1));

        ContentSigner cs = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(crypto.getProvider())
                .build(crypto.getPrivateKey());
        JcaSignerInfoGeneratorBuilder sigb = new JcaSignerInfoGeneratorBuilder(calcProv);
        X509CertificateHolder certHolder = new X509CertificateHolder(signingCert.getEncoded());

        // set signed attribute table generator based on property
        sigb.setSignedAttributeGenerator(
                new OptionalSigningTimeSignedAttributeTableGenerator(includeSigningTimeAttribute));

        SignerInfoGenerator sig = sigb.build(cs, certHolder);

        timeStampTokenGen = new TimeStampTokenGenerator(calc, sig, tSAPolicyOID);

        if (config.getProperties().getProperty(ACCURACYMICROS) != null) {
            timeStampTokenGen
                    .setAccuracyMicros(Integer.parseInt(config.getProperties().getProperty(ACCURACYMICROS)));
        }

        if (config.getProperties().getProperty(ACCURACYMILLIS) != null) {
            timeStampTokenGen
                    .setAccuracyMillis(Integer.parseInt(config.getProperties().getProperty(ACCURACYMILLIS)));
        }

        if (config.getProperties().getProperty(ACCURACYSECONDS) != null) {
            timeStampTokenGen
                    .setAccuracySeconds(Integer.parseInt(config.getProperties().getProperty(ACCURACYSECONDS)));
        }

        timeStampTokenGen.setOrdering(ordering);
        timeStampTokenGen.setIncludeOrdering(includeOrdering);

        if (tsaName != null) {
            final X500Name x500Name = new X500Name(tsaName);
            timeStampTokenGen.setTSA(new GeneralName(x500Name));
        } else if (tsaNameFromCert) {
            final X500Name x500Name = new JcaX509CertificateHolder(signingCert).getSubject();
            timeStampTokenGen.setTSA(new GeneralName(x500Name));
        }

        timeStampTokenGen
                .addCertificates(getCertStoreWithChain(signingCert, getSigningCertificateChain(crypto)));

    } catch (IllegalArgumentException e) {
        LOG.error("IllegalArgumentException: ", e);
        throw new IllegalRequestException(e.getMessage());
    } catch (TSPException e) {
        LOG.error("TSPException: ", e);
        throw new IllegalRequestException(e.getMessage());
    } catch (CertificateEncodingException e) {
        LOG.error("CertificateEncodingException: ", e);
        throw new IllegalRequestException(e.getMessage());
    } catch (IOException e) {
        LOG.error("IOException: ", e);
        throw new IllegalRequestException(e.getMessage());
    }

    return timeStampTokenGen;
}

From source file:org.signserver.module.tsa.TimeStampSignerTest.java

License:Open Source License

/**
 * Test setting the TSA worker property.
 * @throws Exception//from  ww w  .  j a  v  a  2s  .  com
 */
@Test
public void test32ExplicitTSAName() throws Exception {
    workerSession.setWorkerProperty(WORKER1, TimeStampSigner.TSA, "CN=test");
    workerSession.reloadConfiguration(WORKER1);

    final TimeStampResponse response = assertSuccessfulTimestamp(WORKER1, true);
    final GeneralName name = response.getTimeStampToken().getTimeStampInfo().getTsa();
    final GeneralName expectedName = new GeneralName(new X500Name("CN=test"));

    assertEquals("TSA included", expectedName, name);

    // restore
    workerSession.removeWorkerProperty(WORKER1, TimeStampSigner.TSA);
    workerSession.reloadConfiguration(WORKER1);
}

From source file:org.signserver.module.tsa.TimeStampSignerTest.java

License:Open Source License

/**
 * Test using the TSA_FROM_CERT property to set the TSA name from
 * the signing cert./*from   www . j  a va  2s . c  om*/
 * 
 * @throws Exception
 */
@Test
public void test34TSANameFromCert() throws Exception {
    workerSession.setWorkerProperty(WORKER1, TimeStampSigner.TSA_FROM_CERT, "true");
    workerSession.reloadConfiguration(WORKER1);

    final TimeStampResponse response = assertSuccessfulTimestamp(WORKER1, true);
    final GeneralName name = response.getTimeStampToken().getTimeStampInfo().getTsa();
    final GeneralName expectedName = new GeneralName(
            new X500Name("CN=TS Signer 1,OU=Testing,O=SignServer,C=SE"));

    assertEquals("TSA included", expectedName, name);

    final GeneralName certName = new GeneralName(
            new JcaX509CertificateHolder((X509Certificate) workerSession.getSignerCertificate(WORKER1))
                    .getSubject());
    assertTrue("TSA name content equals cert", Arrays.equals(certName.getEncoded(), name.getEncoded()));

    // restore
    workerSession.removeWorkerProperty(WORKER1, TimeStampSigner.TSA_FROM_CERT);
    workerSession.reloadConfiguration(WORKER1);
}

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.xipki.ca.certprofile.XmlX509CertprofileUtil.java

License:Open Source License

private static GeneralSubtree buildGeneralSubtree(final GeneralSubtreeBaseType type)
        throws CertprofileException {
    GeneralName base = null;//from  w w w  . j  a v  a  2s.  co  m
    if (type.getDirectoryName() != null) {
        base = new GeneralName(X509Util.reverse(new X500Name(type.getDirectoryName())));
    } else if (type.getDNSName() != null) {
        base = new GeneralName(GeneralName.dNSName, type.getDNSName());
    } else if (type.getIpAddress() != null) {
        base = new GeneralName(GeneralName.iPAddress, type.getIpAddress());
    } else if (type.getRfc822Name() != null) {
        base = new GeneralName(GeneralName.rfc822Name, type.getRfc822Name());
    } else if (type.getUri() != null) {
        base = new GeneralName(GeneralName.uniformResourceIdentifier, type.getUri());
    } else {
        throw new RuntimeException("should not reach here, unknown child of GeneralSubtreeBaseType");
    }

    Integer i = type.getMinimum();
    if (i != null && i < 0) {
        throw new CertprofileException("negative minimum is not allowed: " + i);
    }

    BigInteger minimum = (i == null) ? null : BigInteger.valueOf(i.intValue());

    i = type.getMaximum();
    if (i != null && i < 0) {
        throw new CertprofileException("negative maximum is not allowed: " + i);
    }

    BigInteger maximum = (i == null) ? null : BigInteger.valueOf(i.intValue());

    return new GeneralSubtree(base, minimum, maximum);
}

From source file:org.xipki.ca.client.impl.CmpRequestor.java

License:Open Source License

public CmpRequestor(final X509Certificate requestorCert, final X509Certificate responderCert,
        final SecurityFactory securityFactory) {
    ParamChecker.assertNotNull("requestorCert", requestorCert);
    ParamChecker.assertNotNull("securityFactory", securityFactory);

    this.requestor = null;
    this.securityFactory = securityFactory;
    this.signRequest = false;

    X500Name x500Name = X500Name.getInstance(requestorCert.getSubjectX500Principal().getEncoded());
    this.sender = new GeneralName(x500Name);

    if (responderCert != null) {
        setResponderCert(responderCert);
    }//  w w  w. j  a  va  2 s  .c o  m
}

From source file:org.xipki.ca.client.impl.CmpRequestor.java

License:Open Source License

public CmpRequestor(ConcurrentContentSigner requestor, final X509Certificate responderCert,
        final SecurityFactory securityFactory, final boolean signRequest) {
    ParamChecker.assertNotNull("requestor", requestor);
    ParamChecker.assertNotNull("securityFactory", securityFactory);

    this.requestor = requestor;
    this.securityFactory = securityFactory;
    this.signRequest = signRequest;

    X500Name x500Name = X500Name.getInstance(requestor.getCertificate().getSubjectX500Principal().getEncoded());
    this.sender = new GeneralName(x500Name);

    if (responderCert != null) {
        setResponderCert(responderCert);
    }//from ww  w.  j  av  a2 s  .  c  om
}

From source file:org.xipki.ca.client.impl.CmpRequestor.java

License:Open Source License

private void setResponderCert(final X509Certificate responderCert) {
    ParamChecker.assertNotNull("responderCert", responderCert);

    this.responderCert = responderCert;
    X500Name subject = X500Name.getInstance(responderCert.getSubjectX500Principal().getEncoded());
    this.recipient = new GeneralName(subject);
    this.c14nRecipientName = getSortedRFC4519Name(subject);
}