Example usage for org.bouncycastle.pkcs PKCS10CertificationRequest getSubject

List of usage examples for org.bouncycastle.pkcs PKCS10CertificationRequest getSubject

Introduction

In this page you can find the example usage for org.bouncycastle.pkcs PKCS10CertificationRequest getSubject.

Prototype

public X500Name getSubject() 

Source Link

Document

Return the subject on this request.

Usage

From source file:be.neutrinet.ispng.vpn.api.VPNClientCertificate.java

@Put
public Representation storeCSR(Representation csrstream) {
    if (!getRequestAttributes().containsKey("client")) {
        return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);
    }//from   ww  w  . ja va  2s .  c  om

    StreamRepresentation sr = (StreamRepresentation) csrstream;

    // Do all kinds of security checks
    try {
        Client client = Clients.dao.queryForId(getAttribute("client").toString());
        PEMParser parser = new PEMParser(sr.getReader());
        PKCS10CertificationRequest csr = (PKCS10CertificationRequest) parser.readObject();

        SubjectPublicKeyInfo pkInfo = csr.getSubjectPublicKeyInfo();
        RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);

        // This makes the NSA work harder on their quantum computer
        // Require 4096 bit key
        // http://stackoverflow.com/a/20622933
        if (!(rsa.getModulus().bitLength() > 2048)) {
            ClientError err = new ClientError("ILLEGAL_KEY_SIZE");
            return new JacksonRepresentation(err);
        }

        X500Name subject = X500Name.getInstance(csr.getSubject());
        RDN[] rdns = subject.getRDNs(BCStyle.CN);
        if (rdns == null || rdns.length == 0) {
            return clientError("NO_CSR_CN", Status.CLIENT_ERROR_BAD_REQUEST);
        }

        String CN = IETFUtils.valueToString(rdns[0].getFirst().getValue());
        if (CN == null || CN.isEmpty()) {
            return clientError("INVALID_CSR_CN", Status.CLIENT_ERROR_BAD_REQUEST);
        }

        if (getQueryValue("rekey") != null && Boolean.parseBoolean(getQueryValue("rekey"))) {
            if (!getRequestAttributes().containsKey("cert")) {
                return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);
            }

            Certificate old = Certificates.dao.queryForId(getAttribute("cert"));

            if (old == null)
                return clientError("MALFORMED_REQUEST", Status.CLIENT_ERROR_BAD_REQUEST);

            old.revocationDate = new Date();

            if (old.get() == null) {
                // this can happen when the old certificate is no longer present on the system
                // in which case the rekey has to go through
            } else if (pkInfo.getPublicKeyData().getString()
                    .equals(old.get().getSubjectPublicKeyInfo().getPublicKeyData().getString())) {
                return clientError("REKEY_USING_SAME_KEY", Status.CLIENT_ERROR_NOT_ACCEPTABLE);
            }

            Certificates.dao.update(old);
        }

        for (Certificate existingCert : Certificates.dao.queryForEq("client_id", client)) {
            if (existingCert.revocationDate.getTime() > System.currentTimeMillis()) {
                return clientError("ANOTHER_CLIENT_CERT_ACTIVE", Status.CLIENT_ERROR_NOT_ACCEPTABLE);
            }
        }

        // couple CN to client
        client.commonName = CN;
        Clients.dao.update(client);

        String caStorePath = VPN.cfg.getProperty("ca.storeDir", "ca");
        File dir = new File(caStorePath);
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }

        Certificate cert = new Certificate();
        cert.client = client;
        Certificates.dao.create(cert);

        FileWriter fw = new FileWriter(caStorePath + "/" + cert.id + ".csr");
        PEMWriter pw = new PEMWriter(fw);
        pw.writeObject(csr);
        pw.flush();

        return new JacksonRepresentation<>(cert);
    } catch (Exception ex) {
        Logger.getLogger(getClass()).error("Failed to validate CSR and/or sign CSR", ex);
    }

    return DEFAULT_ERROR;
}

From source file:beta01.CreateCertByCsr.java

public CreateCertByCsr() throws Exception {
    //read p12/*from w  w  w .  j ava 2  s .co  m*/
    KeyStore pkcs12Store = KeyStore.getInstance("PKCS12", "BC");
    pkcs12Store.load(new FileInputStream("D:\\rootPrivateKey.p12"), "pass".toCharArray());

    //read root key pair and certificate
    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    X509Certificate rootCert = null;
    for (Enumeration en = pkcs12Store.aliases(); en.hasMoreElements();) {
        String alias = (String) en.nextElement();
        if (pkcs12Store.isCertificateEntry(alias)) {
            rootCert = (X509Certificate) pkcs12Store.getCertificate(alias);
            Certificate cert = pkcs12Store.getCertificate(alias);
            publicKey = cert.getPublicKey();
        } else if (pkcs12Store.isKeyEntry(alias)) {
            privateKey = (PrivateKey) pkcs12Store.getKey(alias, "pass".toCharArray());
        }
    }
    //read CSR
    String fileName = "CSR_DSA";
    FileReader fileReader = new FileReader("D:\\" + fileName + ".p10");
    PemReader pemReader = new PemReader(fileReader);
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(pemReader.readPemObject().getContent());

    //create certf
    JcaX509CertificateHolder holder = new JcaX509CertificateHolder(rootCert);
    X509v3CertificateBuilder certBuilder;
    certBuilder = new X509v3CertificateBuilder(holder.getSubject(),
            BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000), csr.getSubject(),
            csr.getSubjectPublicKeyInfo());
    certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));

    SignatureAlgorithmIdentifierFinder algFinder = new DefaultSignatureAlgorithmIdentifierFinder();
    AlgorithmIdentifier sigAlg = algFinder.find("SHA512withRSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    //RSAPrivateKey rsa = (RSAPrivateKey) privateKey;
    //AsymmetricCipherKeyPair ss =new AsymmetricCipherKeyPair
    // RSAKeyParameters rsaP = new RSAPrivateCrtKeyParameters(rsa.getModulus(), rsa.getPublicExponent(), 
    // rsa.getPrivateExponent(), rsa., BigInteger.ONE, BigInteger.ONE, BigInteger.ONE, BigInteger.ONE);
    //ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build((AsymmetricKeyParameter) privateKey);

    // AsymmetricCipherKeyPair sd = new AsymmetricCipherKeyPair(null, null)

    ContentSigner signer = new JcaContentSignerBuilder("SHA512withRSA").setProvider("BC").build(privateKey);
    X509CertificateHolder holder2 = certBuilder.build(signer);
    new SimpleGenCert().converToPem(holder2, fileName);
}

From source file:CAModulePackage.CertificateHelper.java

/**
 * Generate a new X.509 Certificate based on the input Certificate Signing
 * Request./*from   w  w w  .ja  v  a2s  .  co  m*/
 * This is the primary method that should be used for granting a user 
 * credentials on this system.
 * @param csr - Input Certificate Signing Request
 * @param issuer - Name of the Issuing Entity
 * @param issuerPriv - Private Key of the Issuing Entity.
 * @return X.509 Identity Certificate authenticating the user to this system
 */
public static X509CertificateHolder signCSR(PKCS10CertificationRequest csr, String issuer,
        PrivateKey issuerPriv) {
    Date startDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    Date endDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000);

    PublicKey pub = null;
    try {
        pub = KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(csr.getSubjectPublicKeyInfo().getEncoded()));
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(new X500Name(issuer),
            BigInteger.valueOf(System.currentTimeMillis()), startDate, endDate, csr.getSubject(), pub);

    X509CertificateHolder newCert = null;
    try {
        newCert = builder.build(
                new JcaContentSignerBuilder("SHA256withRSAEncryption").setProvider("BC").build(issuerPriv));
    } catch (OperatorCreationException e) {
        e.printStackTrace();
    }

    return newCert;
}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

License:Open Source License

public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair)
        throws Exception {
    SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance(ALG_RSA);
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() - DateConstant.ONE_DAY),
            new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
            .build(pKeyPair.getPrivate());
    X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
            .getCertificate(certBuilder.build(signer));
    signedCert.verify(pKeyPair.getPublic());

    return signedCert;
}

From source file:com.helger.ebinterface.signature.CreateCertHelper.java

License:Apache License

@Nonnull
public static X509Certificate signCSR(final PKCS10CertificationRequest inputCSR, final PrivateKey caPrivate,
        final KeyPair pair, @Nonnull @Nonempty final String sRootCommonName,
        @Nonnull @Nonempty final String sRootOrganization, @Nonnull @Nonempty final String sRootCountry,
        final Date notAfter) throws Exception {

    final AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(SIGNING_ALGO);
    final AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

    final AsymmetricKeyParameter foo = PrivateKeyFactory.createKey(caPrivate.getEncoded());
    final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());

    final X509v3CertificateBuilder myCertificateGenerator = new X509v3CertificateBuilder(
            x500(sRootCommonName, sRootOrganization, sRootCountry),
            new BigInteger(64, SecureRandom.getInstanceStrong()), now(), notAfter, inputCSR.getSubject(),
            keyInfo);/*from   ww w .  j a  v a 2s.c  o m*/

    final ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(foo);

    final X509CertificateHolder holder = myCertificateGenerator.build(sigGen);

    final org.bouncycastle.asn1.x509.Certificate eeX509CertificateStructure = holder.toASN1Structure();

    // Read Certificate
    try (final InputStream is1 = new NonBlockingByteArrayInputStream(eeX509CertificateStructure.getEncoded(),
            false)) {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509", PROVIDER);
        final X509Certificate theCert = (X509Certificate) cf.generateCertificate(is1);
        return theCert;
    }
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static String extractX509CSRCommonName(PKCS10CertificationRequest certReq) {

    String cn = null;/*from  w w w. j a  v a2 s  .  co m*/
    X500Name x500name = certReq.getSubject();
    RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0];
    if (cnRdn != null) {
        cn = IETFUtils.valueToString(cnRdn.getFirst().getValue());
    }
    return cn;
}

From source file:com.yahoo.athenz.auth.util.Crypto.java

License:Apache License

public static X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq,
        PrivateKey caPrivateKey, X500Name issuer, int validityTimeout, boolean basicConstraints) {

    // set validity for the given number of minutes from now

    Date notBefore = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(notBefore);//ww w .  j ava 2s  .  c  o  m
    cal.add(Calendar.MINUTE, validityTimeout);
    Date notAfter = cal.getTime();

    // Generate self-signed certificate

    X509Certificate cert = null;
    try {
        JcaPKCS10CertificationRequest jcaPKCS10CertificationRequest = new JcaPKCS10CertificationRequest(
                certReq);
        PublicKey publicKey = jcaPKCS10CertificationRequest.getPublicKey();

        X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder(issuer,
                BigInteger.valueOf(System.currentTimeMillis()), notBefore, notAfter, certReq.getSubject(),
                publicKey)
                        .addExtension(Extension.basicConstraints, false, new BasicConstraints(basicConstraints))
                        .addExtension(Extension.keyUsage, true,
                                new X509KeyUsage(X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment))
                        .addExtension(Extension.extendedKeyUsage, true,
                                new ExtendedKeyUsage(new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth,
                                        KeyPurposeId.id_kp_serverAuth }));

        // see if we have the dns/rfc822/ip address extensions specified in the csr

        ArrayList<GeneralName> altNames = new ArrayList<>();
        Attribute[] certAttributes = jcaPKCS10CertificationRequest
                .getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        if (certAttributes != null && certAttributes.length > 0) {
            for (Attribute attribute : certAttributes) {
                Extensions extensions = Extensions.getInstance(attribute.getAttrValues().getObjectAt(0));
                GeneralNames gns = GeneralNames.fromExtensions(extensions, Extension.subjectAlternativeName);
                if (gns == null) {
                    continue;
                }
                GeneralName[] names = gns.getNames();
                for (int i = 0; i < names.length; i++) {
                    switch (names[i].getTagNo()) {
                    case GeneralName.dNSName:
                    case GeneralName.iPAddress:
                    case GeneralName.rfc822Name:
                        altNames.add(names[i]);
                        break;
                    }
                }
            }
            if (!altNames.isEmpty()) {
                caBuilder.addExtension(Extension.subjectAlternativeName, false,
                        new GeneralNames(altNames.toArray(new GeneralName[altNames.size()])));
            }
        }

        String signatureAlgorithm = getSignatureAlgorithm(caPrivateKey.getAlgorithm(), SHA256);
        ContentSigner caSigner = new JcaContentSignerBuilder(signatureAlgorithm).setProvider(BC_PROVIDER)
                .build(caPrivateKey);

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider(BC_PROVIDER);
        cert = converter.getCertificate(caBuilder.build(caSigner));

    } catch (CertificateException ex) {
        LOG.error("generateX509Certificate: Caught CertificateException when generating certificate: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (OperatorCreationException ex) {
        LOG.error(
                "generateX509Certificate: Caught OperatorCreationException when creating JcaContentSignerBuilder: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (InvalidKeyException ex) {
        LOG.error("generateX509Certificate: Caught InvalidKeySpecException, invalid key spec is being used: "
                + ex.getMessage());
        throw new CryptoException(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOG.error(
                "generateX509Certificate: Caught NoSuchAlgorithmException, check to make sure the algorithm is supported by the provider: "
                        + ex.getMessage());
        throw new CryptoException(ex);
    } catch (Exception ex) {
        LOG.error("generateX509Certificate: unable to generate X509 Certificate: " + ex.getMessage());
        throw new CryptoException("Unable to generate X509 Certificate");
    }

    return cert;
}

From source file:com.yahoo.athenz.auth.util.CryptoTest.java

License:Apache License

@Test
public void testGetPKCS10CertRequest() throws IOException {

    Path path = Paths.get("src/test/resources/valid.csr");
    String certStr = new String(Files.readAllBytes(path));

    PKCS10CertificationRequest req = Crypto.getPKCS10CertRequest(certStr);
    assertNotNull(req);/*from w  ww  . j  av a  2s.  c  o m*/
    assertEquals(req.getSubject().toString(), "C=US,ST=CA,L=Sunnyvale,O=My Test Company,CN=athenz.syncer");
}

From source file:com.yahoo.athenz.zts.utils.ZTSUtilsTest.java

License:Apache License

@Test
public void testValidateCertReqCommonNameException() {

    PKCS10CertificationRequest certReq = Mockito.mock(PKCS10CertificationRequest.class);
    Mockito.when(certReq.getSubject()).thenThrow(new CryptoException());

    assertFalse(ZTSUtils.validateCertReqCommonName(certReq, "athenz.syncer"));
}

From source file:com.yahoo.athenz.zts.ZTSClientTest.java

License:Apache License

@Test
public void testGenerateInstanceRefreshRequestSubDomain() {

    File privkey = new File("./src/test/resources/test_private_k0.pem");
    PrivateKey privateKey = Crypto.loadPrivateKey(privkey);

    InstanceRefreshRequest req = ZTSClient.generateInstanceRefreshRequest("coretech.system", "test", privateKey,
            "aws", 3600);
    assertNotNull(req);/*w ww  .  j av a2s  .c  o  m*/

    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(req.getCsr());
    assertEquals("coretech.system.test", Crypto.extractX509CSRCommonName(certReq));

    X500Name x500name = certReq.getSubject();
    RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0];
    assertEquals("coretech.system.test", IETFUtils.valueToString(cnRdn.getFirst().getValue()));
    assertEquals("test.coretech-system.aws.athenz.cloud", Crypto.extractX509CSRDnsNames(certReq).get(0));
}