Example usage for org.bouncycastle.asn1.x500 X500Name getInstance

List of usage examples for org.bouncycastle.asn1.x500 X500Name getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x500 X500Name getInstance.

Prototype

public static X500Name getInstance(Object obj) 

Source Link

Usage

From source file:org.jscep.server.ScepServlet.java

License:Open Source License

/**
 * {@inheritDoc}//from  ww  w.j a  v  a 2s  . co m
 */
@SuppressWarnings("unchecked")
@Override
public final void service(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {
    byte[] body = getMessageBytes(req);

    final Operation op;
    try {
        op = getOperation(req);
        if (op == null) {
            // The operation parameter must be set.
            res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing \"operation\" parameter.");
            return;
        }
    } catch (IllegalArgumentException e) {
        // The operation was not recognised.
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid \"operation\" parameter.");
        return;
    }

    LOGGER.debug("Incoming Operation: " + op);

    final String reqMethod = req.getMethod();

    if (op == Operation.PKI_OPERATION) {
        if (!reqMethod.equals(POST) && !reqMethod.equals(GET)) {
            // PKIOperation must be sent using GET or POST

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET + ", " + POST);

            return;
        }
    } else {
        if (!reqMethod.equals(GET)) {
            // Operations other than PKIOperation must be sent using GET

            res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            res.addHeader("Allow", GET);

            return;
        }
    }

    LOGGER.debug("Method " + reqMethod + " Allowed for Operation: " + op);

    if (op == Operation.GET_CA_CAPS) {
        try {
            LOGGER.debug("Invoking doGetCaCaps");
            doGetCaCaps(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetCaCert");
            doGetCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.GET_NEXT_CA_CERT) {
        try {
            LOGGER.debug("Invoking doGetNextCaCert");
            doGetNextCaCert(req, res);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    } else if (op == Operation.PKI_OPERATION) {
        // PKIOperation

        res.setHeader("Content-Type", "application/x-pki-message");

        CMSSignedData sd;
        try {
            sd = new CMSSignedData(body);
        } catch (CMSException e) {
            throw new ServletException(e);
        }

        Store reqStore = sd.getCertificates();
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        CertificateFactory factory;
        try {
            factory = CertificateFactory.getInstance("X.509");
        } catch (CertificateException e) {
            throw new ServletException(e);
        }
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert;
        try {
            reqCert = (X509Certificate) factory.generateCertificate(bais);
        } catch (CertificateException e) {
            throw new ServletException(e);
        }

        PkiMessage<?> msg;
        try {
            PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(), getRecipientKey());
            PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder);
            msg = decoder.decode(sd);
        } catch (MessageDecodingException e) {
            LOGGER.error("Error decoding request", e);
            throw new ServletException(e);
        }

        LOGGER.debug("Processing message {}", msg);

        MessageType msgType = msg.getMessageType();
        Object msgData = msg.getMessageData();

        Nonce senderNonce = Nonce.nextNonce();
        TransactionId transId = msg.getTransactionId();
        Nonce recipientNonce = msg.getSenderNonce();
        CertRep certRep;

        if (msgType == MessageType.GET_CERT) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name principal = iasn.getName();
            final BigInteger serial = iasn.getSerialNumber().getValue();

            try {
                List<X509Certificate> issued = doGetCert(principal, serial);
                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CERT_INITIAL) {
            final IssuerAndSubject ias = (IssuerAndSubject) msgData;
            final X500Name issuer = X500Name.getInstance(ias.getIssuer());
            final X500Name subject = X500Name.getInstance(ias.getSubject());

            try {
                List<X509Certificate> issued = doGetCertInitial(issuer, subject, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CRL) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X500Name issuer = iasn.getName();
            final BigInteger serialNumber = iasn.getSerialNumber().getValue();

            try {
                LOGGER.debug("Invoking doGetCrl");
                CMSSignedData messageData = getMessageData(doGetCrl(issuer, serialNumber));

                certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
            } catch (OperationFailureException e) {
                LOGGER.error("Error executing GetCRL request", e);
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                LOGGER.error("Error executing GetCRL request", e);
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.PKCS_REQ) {
            final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData;

            try {
                LOGGER.debug("Invoking doEnrol");
                List<X509Certificate> issued = doEnrol(certReq, reqCert, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (OperationFailureException e) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, e.getFailInfo());
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else {
            throw new ServletException("Unknown Message for Operation");
        }

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede");
        PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(), getSigner(),
                getSignerCertificateChain(), envEncoder);
        CMSSignedData signedData;
        try {
            signedData = encoder.encode(certRep);
        } catch (MessageEncodingException e) {
            LOGGER.error("Error decoding response", e);
            throw new ServletException(e);
        }

        res.getOutputStream().write(signedData.getEncoded());
        res.getOutputStream().close();
    } else {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unknown Operation");
    }
}

From source file:org.occiware.mart.security.CertificateManagement.java

License:Apache License

/**
 * @param name//w  w  w . j  av a 2s  .  c  o  m
 * @return
 */
private static String getCommonName(X500Principal name) {
    if (name == null) {
        return null;
    }

    return getCommonName(X500Name.getInstance(name.getEncoded()));
}

From source file:org.sipfoundry.sipxconfig.cert.CertificateUtils.java

License:Contributor Agreement License

public static X500Name x500(String txt) {
    return X500Name.getInstance(new X509Principal(txt).getEncoded());
}

From source file:org.tdmx.client.crypto.certificate.PKIXCertificate.java

License:Open Source License

private X500Name getSubjectNameConstraint() {
    Extension e = holder.getExtension(Extension.nameConstraints);
    if (e != null && e.isCritical()) {
        NameConstraints nc = NameConstraints.getInstance(e.getParsedValue());
        GeneralSubtree[] permitted = nc.getPermittedSubtrees();
        if (permitted != null && permitted.length > 0) {
            GeneralName base = permitted[0].getBase();
            if (base != null) {
                if (GeneralName.directoryName == base.getTagNo()) {
                    X500Name baseName = X500Name.getInstance(base.getName());
                    return baseName;
                }/*from   w ww  .  j  a va2  s  . c  o m*/
            }
        }
    }
    return null;
}

From source file:org.usrz.libs.crypto.cert.X509CertificateBuilder.java

License:Apache License

/**
 * Build the final {@link X509Certificate} instance.
 *///from w w w  . j  av a2 s. co m
public X509Certificate build() {
    if (subject == null)
        throw new IllegalStateException("Subject not specified");
    if (issuer == null)
        throw new IllegalStateException("Issuer not specified");
    if (serial == null)
        throw new IllegalStateException("Serial not specified");
    if (!notAfter.after(notBefore))
        throw new IllegalStateException("Date \"not-after\" before or equal to \"not-before\"");
    if (issuerPrivateKey == null)
        throw new IllegalStateException("Issuer private key not specified");
    if (subjectPublicKey == null)
        throw new IllegalStateException("Sobject public key not specified");

    /* Standard subject public key and X500 names */
    final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(subjectPublicKey.getEncoded());
    final X500Name subjectName = X500Name.getInstance(subject.getEncoded());
    final X500Name issuerName = X500Name.getInstance(issuer.getEncoded());

    /* Derive the issuer public key from the private one if needed/possible */
    if ((issuerPublicKey == null) && (issuerPrivateKey instanceof RSAPrivateCrtKey))
        try {
            final RSAPrivateCrtKey key = (RSAPrivateCrtKey) issuerPrivateKey;
            final RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            issuerPublicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
        } catch (InvalidKeySpecException | NoSuchAlgorithmException exception) {
            Logger.getLogger(this.getClass().getName()).log(Level.FINE,
                    "Unable to generate public key from private", exception);
        }

    final X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(issuerName, serial,
            notBefore, notAfter, subjectName, subjectPublicKeyInfo);

    try {
        final JcaX509ExtensionUtils utils = new JcaX509ExtensionUtils();

        /* Are we a certificate authority? */
        certificateBuilder.addExtension(Extension.basicConstraints, true,
                new BasicConstraints(Mode.AUTHORITY.equals(mode)));

        /* Add our subject key identifier */
        certificateBuilder.addExtension(Extension.subjectKeyIdentifier, false,
                utils.createSubjectKeyIdentifier(subjectPublicKeyInfo));

        /* Do we have Standard key usages? */
        if (!standardKeyUsage.isEmpty())
            certificateBuilder.addExtension(Extension.keyUsage, false,
                    new KeyUsage(StandardKeyUsage.combine(standardKeyUsage)));

        /* Do we have extended key usages? */
        if (!extendedKeyUsage.isEmpty())
            certificateBuilder.addExtension(Extension.extendedKeyUsage, false,
                    ExtendedKeyUsage.combine(extendedKeyUsage));

        /* Add our authority key identifer */
        if (issuerPublicKey != null) {
            final SubjectPublicKeyInfo authorityPublicKeyInfo = SubjectPublicKeyInfo
                    .getInstance(issuerPublicKey.getEncoded());
            certificateBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                    utils.createAuthorityKeyIdentifier(authorityPublicKeyInfo));
        }

        /* Add our alternative names */
        if (!alternativeNames.isEmpty()) {
            final GeneralName[] names = alternativeNames.toArray(new GeneralName[alternativeNames.size()]);
            certificateBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(names));
        }

        /* Add CRL distribution points */
        if (!crlDistributionPoints.isEmpty()) {
            final DistributionPoint[] distributionPoints = new DistributionPoint[crlDistributionPoints.size()];
            int position = 0;
            for (GeneralName generalName : crlDistributionPoints) {
                final DistributionPointName distributionPointName = new DistributionPointName(
                        new GeneralNames(generalName));
                distributionPoints[position++] = new DistributionPoint(distributionPointName, null, null);
            }
            final CRLDistPoint crlDistributionPoint = new CRLDistPoint(distributionPoints);
            certificateBuilder.addExtension(Extension.cRLDistributionPoints, false, crlDistributionPoint);
        }

    } catch (CertIOException | NoSuchAlgorithmException exception) {
        throw new IllegalStateException("Exception adding extensions", exception);
    }

    try {
        final CertificateFactory factory = CertificateFactory.getInstance("X.509");
        final String signatureAlgorithm = CryptoUtils.getSignatureAlgorithm(issuerPrivateKey, hash);
        final ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(issuerPrivateKey);
        final X509CertificateHolder certificateHolder = certificateBuilder.build(signer);
        return (X509Certificate) factory
                .generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));
    } catch (OperatorCreationException exception) {
        throw new IllegalStateException("Unable to create certificate signature", exception);
    } catch (IOException exception) {
        throw new IllegalStateException("Unable to generate certificate data", exception);
    } catch (CertificateException exception) {
        throw new IllegalStateException("Unable to generate certificate", exception);
    }
}

From source file:org.wso2.carbon.identity.certificateauthority.endpoint.scep.ScepEndpoint.java

License:Open Source License

private Response pkiOperation(int tenantId, HttpServletRequest request) {
    try {//from  ww w  .  j  a v a  2s .c  o  m
        byte[] body = getMessageBytes(request);
        CMSSignedData sd = new CMSSignedData(body);

        Store reqStore = sd.getCertificates();
        Collection<X509CertificateHolder> reqCerts = reqStore.getMatches(null);

        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        X509CertificateHolder holder = reqCerts.iterator().next();
        ByteArrayInputStream bais = new ByteArrayInputStream(holder.getEncoded());
        X509Certificate reqCert = (X509Certificate) factory.generateCertificate(bais);

        PkcsPkiEnvelopeDecoder envDecoder = new PkcsPkiEnvelopeDecoder(getRecipient(tenantId),
                getRecipientKey(tenantId));
        PkiMessageDecoder decoder = new PkiMessageDecoder(reqCert, envDecoder);
        PkiMessage<?> msg = decoder.decode(sd);
        MessageType msgType = msg.getMessageType();
        Object msgData = msg.getMessageData();

        Nonce senderNonce = Nonce.nextNonce();
        TransactionId transId = msg.getTransactionId();
        Nonce recipientNonce = msg.getSenderNonce();
        CertRep certRep;

        if (msgType == MessageType.GET_CERT) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X509Name principal = iasn.getName();
            final BigInteger serial = iasn.getSerialNumber().getValue();
            List<X509Certificate> issued = doGetCert(principal, serial);
            if (issued.size() == 0) {
                certRep = new CertRep(transId, senderNonce, recipientNonce, FailInfo.badCertId);
            } else {
                CMSSignedData messageData = getMessageData(issued);

                certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
            }
        } else if (msgType == MessageType.GET_CERT_INITIAL) {
            final IssuerAndSubject ias = (IssuerAndSubject) msgData;
            final X500Name issuer = X500Name.getInstance(ias.getIssuer());
            final X500Name subject = X500Name.getInstance(ias.getSubject());

            try {
                List<X509Certificate> issued = doGetCertInitial(tenantId, issuer, subject, transId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.GET_CRL) {
            final IssuerAndSerialNumber iasn = (IssuerAndSerialNumber) msgData;
            final X509Name issuer = iasn.getName();
            final BigInteger serialNumber = iasn.getSerialNumber().getValue();

            try {
                CMSSignedData messageData = getMessageData(doGetCrl(tenantId, issuer, serialNumber));

                certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else if (msgType == MessageType.PKCS_REQ) {
            final PKCS10CertificationRequest certReq = (PKCS10CertificationRequest) msgData;

            try {
                List<X509Certificate> issued = doEnrol(certReq, transId, tenantId);

                if (issued.size() == 0) {
                    certRep = new CertRep(transId, senderNonce, recipientNonce);
                } else {
                    CMSSignedData messageData = getMessageData(issued);

                    certRep = new CertRep(transId, senderNonce, recipientNonce, messageData);
                }
            } catch (Exception e) {
                throw new ServletException(e);
            }
        } else {
            log.error("Unknown message for operation");
            return ResponseUtils.badRequest("Unknown message for operation");
        }

        PkcsPkiEnvelopeEncoder envEncoder = new PkcsPkiEnvelopeEncoder(reqCert, "DESede");
        PkiMessageEncoder encoder = new PkiMessageEncoder(getSignerKey(tenantId), getSigner(tenantId),
                envEncoder);
        CMSSignedData signedData = encoder.encode(certRep);

        return Response.ok().type("application/x-pki-message").entity(signedData.getEncoded()).build();
    } catch (Exception e) {
        log.error(e);
        return ResponseUtils.serverError();
    }
}

From source file:org.xipki.ca.api.X509CertWithDBCertId.java

License:Open Source License

public X509CertWithDBCertId(final X509Certificate cert, final byte[] encodedCert) {
    ParamChecker.assertNotNull("cert", cert);

    this.cert = cert;
    X500Principal x500Subject = cert.getSubjectX500Principal();
    this.subject = X509Util.getRFC4519Name(x500Subject);
    this.subjectAsX500Name = X500Name.getInstance(x500Subject.getEncoded());
    try {/*from   ww w . j av a 2s.  co  m*/
        this.subjectKeyIdentifer = X509Util.extractSKI(cert);
    } catch (CertificateEncodingException e) {
        throw new RuntimeException("CertificateEncodingException: " + e.getMessage());
    }

    if (encodedCert == null) {
        try {
            this.encodedCert = cert.getEncoded();
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("CertificateEncodingException: " + e.getMessage());
        }
    } else {
        this.encodedCert = encodedCert;
    }
}

From source file:org.xipki.ca.client.api.dto.IssuerSerialEntryType.java

License:Open Source License

public IssuerSerialEntryType(final String id, final X509Certificate cert) {
    this(id, X500Name.getInstance(cert.getIssuerX500Principal().getEncoded()), cert.getSerialNumber());
}

From source file:org.xipki.ca.client.api.dto.RevokeCertRequestEntryType.java

License:Open Source License

public RevokeCertRequestEntryType(final String id, final X509Certificate cert, final int reason,
        final Date invalidityDate) {
    this(id, X500Name.getInstance(cert.getIssuerX500Principal().getEncoded()), cert.getSerialNumber(), reason,
            invalidityDate);/*ww w.  j a v a2s  . c om*/
}

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

License:Open Source License

@Override
public CertIdOrError revokeCert(final X509Certificate cert, final int reason, final Date invalidityDate,
        final RequestResponseDebug debug) throws CAClientException, PKIErrorException {
    X500Name issuer = X500Name.getInstance(cert.getIssuerX500Principal().getEncoded());
    return revokeCert(issuer, cert.getSerialNumber(), reason, invalidityDate, debug);
}