Java Code Examples for org.bouncycastle.asn1.x509.KeyUsage

The following are top voted examples for showing how to use org.bouncycastle.asn1.x509.KeyUsage. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: gwt-crypto   File: KeyUsageValidation.java   Source Code and License 7 votes vote down vote up
public void validate(CertPathValidationContext context, X509CertificateHolder certificate)
    throws CertPathValidationException
{
    context.addHandledExtension(Extension.keyUsage);

    if (!context.isEndEntity())
    {
        KeyUsage usage = KeyUsage.fromExtensions(certificate.getExtensions());

        if (usage != null)
        {
            if (!usage.hasUsages(KeyUsage.keyCertSign))
            {
                throw new CertPathValidationException("Issuer certificate KeyUsage extension does not permit key signing");
            }
        }
        else
        {
            if (isMandatory)
            {
                throw new CertPathValidationException("KeyUsage extension not present in CA certificate");
            }
        }
    }
}
 
Example 2
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testFailingOnMissingKeyUsage() throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.decipherOnly);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setCRLSigningFilter(true);

	// operate
	try {
		this.testedInstance.check(certificate);
		fail();
	} catch (TrustLinkerResultException e) {
		assertEquals(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
				e.getReason());
	}
}
 
Example 3
Project: ipack   File: TlsUtils.java   Source Code and License 6 votes vote down vote up
static void validateKeyUsage(org.bouncycastle.asn1.x509.Certificate c, int keyUsageBits)
    throws IOException
{
    Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        KeyUsage ku = KeyUsage.fromExtensions(exts);
        if (ku != null)
        {
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);
            }
        }
    }
}
 
Example 4
Project: oscm   File: CertificateHandler.java   Source Code and License 6 votes vote down vote up
private X509Certificate generateSignedCertificate(
        PKCS10CertificationRequest csr) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException,
        CertificateParsingException, CertificateEncodingException,
        SignatureException {

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    Calendar c = Calendar.getInstance();
    certGen.setNotBefore(c.getTime());
    c.add(Calendar.YEAR, 1);
    certGen.setNotAfter(c.getTime());
    certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(csr.getPublicKey("BC"));
    certGen.setSignatureAlgorithm(ALGORITHM_SHA256_RSA);
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert.getPublicKey()));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
    certGen.addExtension(X509Extensions.BasicConstraints, true,
            new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(
            KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    X509Certificate issuedCert = certGen.generate(rootPrivateKeyEntry
            .getPrivateKey());
    return issuedCert;
}
 
Example 5
Project: gwt-crypto   File: TlsUtils.java   Source Code and License 6 votes vote down vote up
static void validateKeyUsage(org.bouncycastle.asn1.x509.Certificate c, int keyUsageBits)
    throws IOException
{
    Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        KeyUsage ku = KeyUsage.fromExtensions(exts);
        if (ku != null)
        {
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);
            }
        }
    }
}
 
Example 6
Project: photon-model   File: CertificateUtil.java   Source Code and License 6 votes vote down vote up
private static List<ExtensionHolder> getServerExtensions(X509Certificate issuerCertificate)
        throws CertificateEncodingException, NoSuchAlgorithmException, IOException {
    List<ExtensionHolder> extensions = new ArrayList<>();

    // SSO forces us to allow data encipherment
    extensions.add(new ExtensionHolder(Extension.keyUsage, true, new KeyUsage(
            KeyUsage.digitalSignature
                    | KeyUsage.keyEncipherment
                    | KeyUsage.dataEncipherment)));

    extensions.add(new ExtensionHolder(Extension.extendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)));

    Extension authorityKeyExtension = new Extension(Extension.authorityKeyIdentifier, false,
            new DEROctetString(new JcaX509ExtensionUtils()
                    .createAuthorityKeyIdentifier(issuerCertificate)));
    extensions.add(new ExtensionHolder(authorityKeyExtension.getExtnId(),
            authorityKeyExtension.isCritical(), authorityKeyExtension.getParsedValue()));

    return extensions;
}
 
Example 7
Project: dcos-commons   File: TLSArtifactsGenerator.java   Source Code and License 6 votes vote down vote up
private static byte[] generateCSR(KeyPair keyPair, CertificateNamesGenerator certificateNamesGenerator)
        throws IOException, OperatorCreationException {
    ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();
    extensionsGenerator.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
    extensionsGenerator.addExtension(Extension.extendedKeyUsage, true,
            new ExtendedKeyUsage(
                    new KeyPurposeId[] {
                            KeyPurposeId.id_kp_clientAuth,
                            KeyPurposeId.id_kp_serverAuth
                    }
            ));
    extensionsGenerator.addExtension(Extension.subjectAlternativeName, true, certificateNamesGenerator.getSANs());

    PKCS10CertificationRequest csr =
            new JcaPKCS10CertificationRequestBuilder(certificateNamesGenerator.getSubject(), keyPair.getPublic())
            .addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate())
            .build(new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate()));
    return PEMUtils.toPEM(csr);
}
 
Example 8
Project: Aki-SSL   File: KeyUsageValidation.java   Source Code and License 6 votes vote down vote up
public void validate(CertPathValidationContext context, X509CertificateHolder certificate)
    throws CertPathValidationException
{
    context.addHandledExtension(Extension.keyUsage);

    if (!context.isEndEntity())
    {
        KeyUsage usage = KeyUsage.fromExtensions(certificate.getExtensions());

        if (usage != null)
        {
            if (!usage.hasUsages(KeyUsage.keyCertSign))
            {
                throw new CertPathValidationException("Issuer certificate KeyUsage extension does not permit key signing");
            }
        }
        else
        {
            if (isMandatory)
            {
                throw new CertPathValidationException("KeyUsage extension not present in CA certificate");
            }
        }
    }
}
 
Example 9
Project: Aki-SSL   File: TlsUtils.java   Source Code and License 6 votes vote down vote up
static void validateKeyUsage(org.bouncycastle.asn1.x509.Certificate c, int keyUsageBits)
    throws IOException
{
    Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        KeyUsage ku = KeyUsage.fromExtensions(exts);
        if (ku != null)
        {
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);
            }
        }
    }
}
 
Example 10
Project: credhub   File: CertificateReaderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void givenASelfSignedCertificate_setsCertificateFieldsCorrectly() {
  final String distinguishedName =
      "O=test-org, ST=Jupiter, C=MilkyWay, CN=test-common-name, OU=test-org-unit, L=Europa";
  final GeneralNames generalNames = new GeneralNames(
      new GeneralName(GeneralName.dNSName, "SolarSystem"));

  CertificateReader certificateReader = new CertificateReader(CertificateStringConstants.BIG_TEST_CERT);

  assertThat(certificateReader.getSubjectName().toString(), equalTo(distinguishedName));
  assertThat(certificateReader.getKeyLength(), equalTo(4096));
  assertThat(certificateReader.getAlternativeNames(), equalTo(generalNames));
  assertThat(asList(certificateReader.getExtendedKeyUsage().getUsages()),
      containsInAnyOrder(KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth));
  assertThat(certificateReader.getKeyUsage().hasUsages(KeyUsage.digitalSignature),
      equalTo(true));
  assertThat(certificateReader.getDurationDays(), equalTo(30));
  assertThat(certificateReader.isSelfSigned(), equalTo(false));
  assertThat(certificateReader.isCa(), equalTo(false));
}
 
Example 11
Project: keystore-explorer   File: DKeyUsage.java   Source Code and License 6 votes vote down vote up
private void prepopulateWithValue(byte[] value) throws IOException {
	@SuppressWarnings("resource") // we have a ByteArrayInputStream here which does not need to be closed
	DERBitString keyUsage = DERBitString.getInstance(new ASN1InputStream(value).readObject());

	int keyUsageValue = keyUsage.intValue();

	jcbDigitalSignature.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.digitalSignature));
	jcbNonRepudiation.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.nonRepudiation));
	jcbKeyEncipherment.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.keyEncipherment));
	jcbDataEncipherment.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.dataEncipherment));
	jcbKeyAgreement.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.keyAgreement));
	jcbCertificateSigning.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.keyCertSign));
	jcbCrlSign.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.cRLSign));
	jcbEncipherOnly.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.encipherOnly));
	jcbDecipherOnly.setSelected(hasKeyUsage(keyUsageValue, KeyUsage.decipherOnly));
}
 
Example 12
Project: dss   File: CertificateService.java   Source Code and License 6 votes vote down vote up
private CertificateToken generateRootCertificateWithCrl(SignatureAlgorithm algorithm, X500Name subject, X500Name issuer, PrivateKey issuerPrivateKey,
		PublicKey publicKey, Date notBefore, Date notAfter) throws Exception {

	// generate certificate
	final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

	final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
			new BigInteger("" + new Random().nextInt(10) + System.currentTimeMillis()), notBefore, notAfter, subject, keyInfo);

	certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign));

	// Sign the new certificate with the private key of the trusted third
	final ContentSigner signer = new JcaContentSignerBuilder(algorithm.getJCEId()).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerPrivateKey);
	final X509CertificateHolder holder = certBuilder.build(signer);

	final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X509")
			.generateCertificate(new ByteArrayInputStream(holder.getEncoded()));

	return new CertificateToken(cert);
}
 
Example 13
Project: dss   File: CertificateService.java   Source Code and License 6 votes vote down vote up
private CertificateToken generateRootCertificateWithoutCrl(SignatureAlgorithm algorithm, X500Name subject, X500Name issuer, PrivateKey issuerPrivateKey,
		PublicKey publicKey, Date notBefore, Date notAfter) throws Exception {

	// generate certificate
	final SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

	final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
			new BigInteger("" + new Random().nextInt(10) + System.currentTimeMillis()), notBefore, notAfter, subject, keyInfo);

	certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));

	// Sign the new certificate with the private key of the trusted third
	final ContentSigner signer = new JcaContentSignerBuilder(algorithm.getJCEId()).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerPrivateKey);
	final X509CertificateHolder holder = certBuilder.build(signer);

	final X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X509")
			.generateCertificate(new ByteArrayInputStream(holder.getEncoded()));

	return new CertificateToken(cert);
}
 
Example 14
Project: TinyTravelTracker   File: TlsUtils.java   Source Code and License 6 votes vote down vote up
static void validateKeyUsage(org.bouncycastle.asn1.x509.Certificate c, int keyUsageBits)
    throws IOException
{
    Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        KeyUsage ku = KeyUsage.fromExtensions(exts);
        if (ku != null)
        {
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);
            }
        }
    }
}
 
Example 15
Project: runrightfast-vertx   File: CertificateServiceImplTest.java   Source Code and License 6 votes vote down vote up
private CaCert caCert() throws NoSuchAlgorithmException, NoSuchProviderException {
    final DistinguishedName issuer = issuer();

    final X500Principal issuerPrincipal = issuer.toX500Principal();

    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA.name(), BOUNCY_CASTLE);
    final KeyPair certKeyPair = keyPairGenerator.generateKeyPair();

    final ImmutableList<X509CertExtension> x509CertExtensions = ImmutableList.<X509CertExtension>builder()
            .add(keyUsage(new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)))
            .build();
    final SelfSignedX509V3CertRequest selfSignedRequest = new SelfSignedX509V3CertRequest(
            issuerPrincipal,
            BigInteger.ONE,
            Instant.now(),
            Instant.ofEpochMilli(System.currentTimeMillis() + (10 * 1000)),
            certKeyPair,
            x509CertExtensions,
            new BasicConstraints(Integer.MAX_VALUE)
    );

    return new CaCert(certificateService.generateSelfSignedX509CertificateV3(selfSignedRequest), certKeyPair.getPrivate());
}
 
Example 16
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDigitalSignatureKeyUsage() throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setDigitalSignatureFilter(true);

	// operate
	this.testedInstance.check(certificate);
}
 
Example 17
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDigitalSignatureNoNonRepudiationKeyUsage() throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.digitalSignature);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setDigitalSignatureFilter(true);
	this.testedInstance.setNonRepudiationFilter(false);

	// operate
	this.testedInstance.check(certificate);
}
 
Example 18
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFailingOnUnexpectedKeyUsageKeyEncipherment()
		throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.keyEncipherment);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setKeyEnciphermentFilter(false);

	// operate
	try {
		this.testedInstance.check(certificate);
		fail();
	} catch (TrustLinkerResultException e) {
		assertEquals(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
				e.getReason());
	}
}
 
Example 19
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFailingOnUnexpectedKeyUsageDataEncipherment()
		throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.dataEncipherment);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setDataEnciphermentFilter(false);

	// operate
	try {
		this.testedInstance.check(certificate);
		fail();
	} catch (TrustLinkerResultException e) {
		assertEquals(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
				e.getReason());
	}
}
 
Example 20
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFailingOnUnexpectedKeyUsageKeyAgreement() throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.keyAgreement);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setKeyAgreementFilter(false);

	// operate
	try {
		this.testedInstance.check(certificate);
		fail();
	} catch (TrustLinkerResultException e) {
		assertEquals(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
				e.getReason());
	}
}
 
Example 21
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFailingOnUnexpectedKeyUsageKeyCertSign() throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.keyCertSign);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setKeyCertificateSigningFilter(false);

	// operate
	try {
		this.testedInstance.check(certificate);
		fail();
	} catch (TrustLinkerResultException e) {
		assertEquals(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
				e.getReason());
	}
}
 
Example 22
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFailingOnUnexpectedKeyUsageCrlSign() throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.cRLSign);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setCRLSigningFilter(false);

	// operate
	try {
		this.testedInstance.check(certificate);
		fail();
	} catch (TrustLinkerResultException e) {
		assertEquals(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
				e.getReason());
	}
}
 
Example 23
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFailingOnUnexpectedKeyUsageEncypherOnly() throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.encipherOnly);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setEncipherOnlyFilter(false);

	// operate
	try {
		this.testedInstance.check(certificate);
		fail();
	} catch (TrustLinkerResultException e) {
		assertEquals(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
				e.getReason());
	}
}
 
Example 24
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testFailingOnUnexpectedKeyUsageDecypherOnly() throws Exception {
	// setup
	KeyPair keyPair = PKITestUtils.generateKeyPair();
	DateTime notBefore = new DateTime();
	DateTime notAfter = notBefore.plusMonths(1);
	KeyUsage keyUsage = new KeyUsage(KeyUsage.decipherOnly);
	X509Certificate certificate = PKITestUtils
			.generateSelfSignedCertificate(keyPair, "CN=Test", notBefore,
					notAfter, true, 0, null, keyUsage);

	this.testedInstance.setDecipherOnlyFilter(false);

	// operate
	try {
		this.testedInstance.check(certificate);
		fail();
	} catch (TrustLinkerResultException e) {
		assertEquals(TrustLinkerResultReason.CONSTRAINT_VIOLATION,
				e.getReason());
	}
}
 
Example 25
Project: CryptMeme   File: TestUtils.java   Source Code and License 6 votes vote down vote up
public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert)
    throws Exception
{
    X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X509Principal("CN=Test Intermediate Certificate"));
    certGen.setPublicKey(intKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    return certGen.generate(caKey, "BC");
}
 
Example 26
Project: CryptMeme   File: TestUtils.java   Source Code and License 6 votes vote down vote up
public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert)
    throws Exception
{
    X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X509Principal("CN=Test End Certificate"));
    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    return certGen.generate(caKey, "BC");
}
 
Example 27
Project: CryptMeme   File: TlsUtils.java   Source Code and License 6 votes vote down vote up
static void validateKeyUsage(org.bouncycastle.asn1.x509.Certificate c, int keyUsageBits)
    throws IOException
{
    Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        KeyUsage ku = KeyUsage.fromExtensions(exts);
        if (ku != null)
        {
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);
            }
        }
    }
}
 
Example 28
Project: freeVM   File: CertGen.java   Source Code and License 6 votes vote down vote up
public X509Certificate getCertificate() throws InvalidKeyException, NoSuchProviderException, SecurityException, SignatureException {
    if (getKeyusageparameters() == 0) {
        throw new SecurityException("No KeyUsageParameters defined...");
    }
    if (getIssuer() == null) {
        throw new SecurityException("No certificate authority and/or entity associated with the public key");
    }
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN="+getIssuer()));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 500000000));
    certGen.setSubjectDN(new X500Principal("CN="+getIssuer()));
    certGen.setPublicKey(pair.getPublic( ));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, isCriticalkeyusage(), new KeyUsage(getKeyusageparameters()));
    //certGen.addExtennullsion(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));    
    certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name,"[email protected]")));
    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}
 
Example 29
Project: jqm   File: CertificateRequest.java   Source Code and License 6 votes vote down vote up
public void generateCA(String prettyName)
{
    this.prettyName = prettyName;

    Subject = "CN=JQM-CA,OU=ServerProducts,O=Oxymores,C=FR";
    size = 4096;

    EKU = new KeyPurposeId[4];
    EKU[0] = KeyPurposeId.id_kp_codeSigning;
    EKU[1] = KeyPurposeId.id_kp_serverAuth;
    EKU[2] = KeyPurposeId.id_kp_clientAuth;
    EKU[3] = KeyPurposeId.id_kp_emailProtection;

    keyUsage = KeyUsage.cRLSign | KeyUsage.keyCertSign;

    generateAll();
}
 
Example 30
Project: irma_future_id   File: KeyUsageValidation.java   Source Code and License 6 votes vote down vote up
public void validate(CertPathValidationContext context, X509CertificateHolder certificate)
    throws CertPathValidationException
{
    context.addHandledExtension(Extension.keyUsage);

    if (!context.isEndEntity())
    {
        KeyUsage usage = KeyUsage.fromExtensions(certificate.getExtensions());

        if (usage != null)
        {
            if (!usage.hasUsages(KeyUsage.keyCertSign))
            {
                throw new CertPathValidationException("Issuer certificate KeyUsage extension does not permit key signing");
            }
        }
        else
        {
            if (isMandatory)
            {
                throw new CertPathValidationException("KeyUsage extension not present in CA certificate");
            }
        }
    }
}
 
Example 31
Project: irma_future_id   File: TlsUtils.java   Source Code and License 6 votes vote down vote up
static void validateKeyUsage(org.bouncycastle.asn1.x509.Certificate c, int keyUsageBits)
    throws IOException
{
    Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        KeyUsage ku = KeyUsage.fromExtensions(exts);
        if (ku != null)
        {
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);
            }
        }
    }
}
 
Example 32
Project: irma_future_id   File: TestUtils.java   Source Code and License 6 votes vote down vote up
public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert)
    throws Exception
{
    X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X509Principal("CN=Test Intermediate Certificate"));
    certGen.setPublicKey(intKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    return certGen.generate(caKey, "BC");
}
 
Example 33
Project: irma_future_id   File: TestUtils.java   Source Code and License 6 votes vote down vote up
public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert)
    throws Exception
{
    X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X509Principal("CN=Test End Certificate"));
    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    return certGen.generate(caKey, "BC");
}
 
Example 34
Project: bc-java   File: KeyUsageValidation.java   Source Code and License 6 votes vote down vote up
public void validate(CertPathValidationContext context, X509CertificateHolder certificate)
    throws CertPathValidationException
{
    context.addHandledExtension(Extension.keyUsage);

    if (!context.isEndEntity())
    {
        KeyUsage usage = KeyUsage.fromExtensions(certificate.getExtensions());

        if (usage != null)
        {
            if (!usage.hasUsages(KeyUsage.keyCertSign))
            {
                throw new CertPathValidationException("Issuer certificate KeyUsage extension does not permit key signing");
            }
        }
        else
        {
            if (isMandatory)
            {
                throw new CertPathValidationException("KeyUsage extension not present in CA certificate");
            }
        }
    }
}
 
Example 35
Project: bc-java   File: TlsUtils.java   Source Code and License 6 votes vote down vote up
static void validateKeyUsage(org.bouncycastle.asn1.x509.Certificate c, int keyUsageBits)
    throws IOException
{
    Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        KeyUsage ku = KeyUsage.fromExtensions(exts);
        if (ku != null)
        {
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                throw new TlsFatalAlert(AlertDescription.certificate_unknown);
            }
        }
    }
}
 
Example 36
Project: bc-java   File: TestUtils.java   Source Code and License 6 votes vote down vote up
public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert)
    throws Exception
{
    X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X509Principal("CN=Test Intermediate Certificate"));
    certGen.setPublicKey(intKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    return certGen.generate(caKey, "BC");
}
 
Example 37
Project: bc-java   File: TestUtils.java   Source Code and License 6 votes vote down vote up
public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert)
    throws Exception
{
    X509V3CertificateGenerator  certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(1));
    certGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X509Principal("CN=Test End Certificate"));
    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(entityKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    return certGen.generate(caKey, "BC");
}
 
Example 38
Project: cagrid-core   File: CertUtil.java   Source Code and License 6 votes vote down vote up
public static X509Certificate generateCACertificate(String provider, X509Name subject, Date start, Date expired,
    KeyPair pair, int numberOfCAs, String signartureAlgorthm) throws InvalidKeyException, NoSuchProviderException,
    SignatureException, IOException {
    // generate the certificate
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(subject);
    certGen.setNotBefore(start);
    certGen.setNotAfter(expired);
    certGen.setSubjectDN(subject);
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm(signartureAlgorthm);
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numberOfCAs));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature
        | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(
        new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject());
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki));

    SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(
        new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject());
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki));
    return certGen.generateX509Certificate(pair.getPrivate(), provider);
}
 
Example 39
Project: cagrid2   File: CertUtil.java   Source Code and License 6 votes vote down vote up
public static X509Certificate generateCACertificate(String provider, X509Name subject, Date start, Date expired,
    KeyPair pair, int numberOfCAs, String signartureAlgorthm) throws InvalidKeyException, NoSuchProviderException,
    SignatureException, IOException {
    // generate the certificate
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(subject);
    certGen.setNotBefore(start);
    certGen.setNotAfter(expired);
    certGen.setSubjectDN(subject);
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm(signartureAlgorthm);
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numberOfCAs));
    certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature
        | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(
        new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject());
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki));

    SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(
        new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject());
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki));
    return certGen.generateX509Certificate(pair.getPrivate(), provider);
}
 
Example 40
Project: cagrid2   File: CertUtil.java   Source Code and License 6 votes vote down vote up
public static X509Certificate generateCACertificate(String provider, X509Name subject, Date start, Date expired, KeyPair pair, int numberOfCAs, String signatureAlgorthm)
		throws CertificateEncodingException, IllegalStateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException {
	// generate the certificate
	X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
	certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
	certGen.setIssuerDN(subject);
	certGen.setNotBefore(start);
	certGen.setNotAfter(expired);
	certGen.setSubjectDN(subject);
	certGen.setPublicKey(pair.getPublic());
	certGen.setSignatureAlgorithm(signatureAlgorthm);
	certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(numberOfCAs));
	certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

	SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject());
	certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifier(spki));

	SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pair.getPublic().getEncoded())).readObject());
	certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(apki));
	return certGen.generate(pair.getPrivate(), provider);
}
 
Example 41
Project: jradius   File: TlsRSAKeyExchange.java   Source Code and License 6 votes vote down vote up
private void validateKeyUsage(X509CertificateStructure c, int keyUsageBits) throws IOException
{
    X509Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
        if (ext != null)
        {
            KeyUsage ku = KeyUsage.getInstance(ext);
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                handler.failWithError(TlsProtocolHandler.AL_fatal,
                    TlsProtocolHandler.AP_certificate_unknown);
            }
        }
    }
}
 
Example 42
Project: jradius   File: TlsDHKeyExchange.java   Source Code and License 6 votes vote down vote up
private void validateKeyUsage(X509CertificateStructure c, int keyUsageBits) throws IOException
{
    X509Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
        if (ext != null)
        {
            KeyUsage ku = KeyUsage.getInstance(ext);
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                handler.failWithError(TlsProtocolHandler.AL_fatal,
                    TlsProtocolHandler.AP_certificate_unknown);
            }
        }
    }
}
 
Example 43
Project: jradius   File: TlsSRPKeyExchange.java   Source Code and License 6 votes vote down vote up
private void validateKeyUsage(X509CertificateStructure c, int keyUsageBits) throws IOException
{
    X509Extensions exts = c.getTBSCertificate().getExtensions();
    if (exts != null)
    {
        X509Extension ext = exts.getExtension(X509Extensions.KeyUsage);
        if (ext != null)
        {
            KeyUsage ku = KeyUsage.getInstance(ext);
            int bits = ku.getBytes()[0] & 0xff;
            if ((bits & keyUsageBits) != keyUsageBits)
            {
                handler.failWithError(TlsProtocolHandler.AL_fatal,
                    TlsProtocolHandler.AP_certificate_unknown);
            }
        }
    }
}
 
Example 44
Project: ipack   File: TlsRSAKeyExchange.java   Source Code and License 5 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate)
    throws IOException
{

    if (serverCertificate.isEmpty())
    {
        throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
    }

    // Sanity check the PublicKeyFactory
    if (this.serverPublicKey.isPrivate())
    {
        throw new TlsFatalAlert(AlertDescription.internal_error);
    }

    this.rsaServerPublicKey = validateRSAPublicKey((RSAKeyParameters)this.serverPublicKey);

    TlsUtils.validateKeyUsage(x509Cert, KeyUsage.keyEncipherment);

    super.processServerCertificate(serverCertificate);
}
 
Example 45
Project: ipack   File: TlsPSKKeyExchange.java   Source Code and License 5 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate)
    throws IOException
{

    if (keyExchange != KeyExchangeAlgorithm.RSA_PSK)
    {
        throw new TlsFatalAlert(AlertDescription.unexpected_message);
    }
    if (serverCertificate.isEmpty())
    {
        throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
    }

    // Sanity check the PublicKeyFactory
    if (this.serverPublicKey.isPrivate())
    {
        throw new TlsFatalAlert(AlertDescription.internal_error);
    }

    this.rsaServerPublicKey = validateRSAPublicKey((RSAKeyParameters)this.serverPublicKey);

    TlsUtils.validateKeyUsage(x509Cert, KeyUsage.keyEncipherment);

    super.processServerCertificate(serverCertificate);
}
 
Example 46
Project: ipack   File: TlsSRPKeyExchange.java   Source Code and License 5 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate)
    throws IOException
{

    if (tlsSigner == null)
    {
        throw new TlsFatalAlert(AlertDescription.unexpected_message);
    }
    if (serverCertificate.isEmpty())
    {
        throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        throw new TlsFatalAlert(AlertDescription.unsupported_certificate);
    }

    if (!tlsSigner.isValidPublicKey(this.serverPublicKey))
    {
        throw new TlsFatalAlert(AlertDescription.certificate_unknown);
    }

    TlsUtils.validateKeyUsage(x509Cert, KeyUsage.digitalSignature);

    super.processServerCertificate(serverCertificate);
}
 
Example 47
Project: calcite-avatica   File: SslDriverTest.java   Source Code and License 5 votes vote down vote up
private X509CertificateObject generateCert(String keyName, KeyPair kp, boolean isCertAuthority,
    PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException,
    CertIOException, OperatorCreationException, CertificateException,
    NoSuchAlgorithmException {
  Calendar startDate = DateTimeUtils.calendar();
  Calendar endDate = DateTimeUtils.calendar();
  endDate.add(Calendar.YEAR, 100);

  BigInteger serialNumber = BigInteger.valueOf(startDate.getTimeInMillis());
  X500Name issuer = new X500Name(
      IETFUtils.rDNsFromString("cn=localhost", RFC4519Style.INSTANCE));
  JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer,
      serialNumber, startDate.getTime(), endDate.getTime(), issuer, kp.getPublic());
  JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
  certGen.addExtension(Extension.subjectKeyIdentifier, false,
      extensionUtils.createSubjectKeyIdentifier(kp.getPublic()));
  certGen.addExtension(Extension.basicConstraints, false,
      new BasicConstraints(isCertAuthority));
  certGen.addExtension(Extension.authorityKeyIdentifier, false,
      extensionUtils.createAuthorityKeyIdentifier(signerPublicKey));
  if (isCertAuthority) {
    certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
  }
  X509CertificateHolder cert = certGen.build(
      new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey));
  return new X509CertificateObject(cert.toASN1Structure());
}
 
Example 48
Project: nifi-registry   File: CertificateUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 */
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(dn)),
                getUniqueSerialNumber(),
                startDate, endDate,
                reverseX500Name(new X500Name(dn)),
                subPubKeyInfo);

        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth}));

        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
 
Example 49
Project: nifi-registry   File: CertificateUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Generates an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 *
 * @param dn the distinguished name to use
 * @param publicKey the public key to issue the certificate to
 * @param extensions extensions extracted from the CSR
 * @param issuer the issuer's certificate
 * @param issuerKeyPair the issuer's keypair
 * @param signingAlgorithm the signing algorithm to use
 * @param days the number of days it should be valid for
 * @return an issued {@link X509Certificate} from the given issuer certificate and {@link KeyPair}
 * @throws CertificateException if there is an error issuing the certificate
 */
public static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, Extensions extensions, X509Certificate issuer, KeyPair issuerKeyPair, String signingAlgorithm, int days)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(issuerKeyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(days));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(issuer.getSubjectX500Principal().getName())),
                getUniqueSerialNumber(),
                startDate, endDate,
                reverseX500Name(new X500Name(dn)),
                subPubKeyInfo);

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(publicKey));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(issuerKeyPair.getPublic()));
        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyAgreement | KeyUsage.nonRepudiation));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(false));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth}));

        // (3) subjectAlternativeName
        if(extensions != null && extensions.getExtension(Extension.subjectAlternativeName) != null) {
            certBuilder.addExtension(Extension.subjectAlternativeName, false, extensions.getExtensionParsedValue(Extension.subjectAlternativeName));
        }

        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}
 
Example 50
Project: TLS-Attacker   File: KeyStoreGenerator.java   Source Code and License 5 votes vote down vote up
public static KeyStore createKeyStore(KeyPair keyPair, BadRandom random) throws CertificateException, IOException,
        InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException,
        SignatureException, OperatorCreationException {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    X500Name issuerName = new X500Name("CN=127.0.0.1, O=TLS-Attacker, L=RUB, ST=NRW, C=DE");
    X500Name subjectName = issuerName;

    BigInteger serial = BigInteger.valueOf(random.nextInt());
    Date before = new Date(System.currentTimeMillis() - 5000);
    Date after = new Date(System.currentTimeMillis() + 600000);
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, before, after,
            subjectName, publicKey);
    builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment);
    builder.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    builder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

    String algorithm = createSigningAlgorithm(keyPair);
    X509Certificate cert = signCertificate(algorithm, builder, privateKey);
    cert.checkValidity(new Date());
    cert.verify(publicKey);

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry(ALIAS, privateKey, PASSWORD.toCharArray(), new java.security.cert.Certificate[] { cert });

    return keyStore;
}
 
Example 51
Project: gwt-crypto   File: TlsRSAKeyExchange.java   Source Code and License 5 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate)
    throws IOException
{
    if (serverCertificate.isEmpty())
    {
        throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
    }

    // Sanity check the PublicKeyFactory
    if (this.serverPublicKey.isPrivate())
    {
        throw new TlsFatalAlert(AlertDescription.internal_error);
    }

    this.rsaServerPublicKey = validateRSAPublicKey((RSAKeyParameters)this.serverPublicKey);

    TlsUtils.validateKeyUsage(x509Cert, KeyUsage.keyEncipherment);

    super.processServerCertificate(serverCertificate);
}
 
Example 52
Project: gwt-crypto   File: TlsPSKKeyExchange.java   Source Code and License 5 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate) throws IOException
{
    if (keyExchange != KeyExchangeAlgorithm.RSA_PSK)
    {
        throw new TlsFatalAlert(AlertDescription.unexpected_message);
    }
    if (serverCertificate.isEmpty())
    {
        throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
    }

    // Sanity check the PublicKeyFactory
    if (this.serverPublicKey.isPrivate())
    {
        throw new TlsFatalAlert(AlertDescription.internal_error);
    }

    this.rsaServerPublicKey = validateRSAPublicKey((RSAKeyParameters)this.serverPublicKey);

    TlsUtils.validateKeyUsage(x509Cert, KeyUsage.keyEncipherment);

    super.processServerCertificate(serverCertificate);
}
 
Example 53
Project: gwt-crypto   File: TlsSRPKeyExchange.java   Source Code and License 5 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate) throws IOException
{
    if (tlsSigner == null)
    {
        throw new TlsFatalAlert(AlertDescription.unexpected_message);
    }
    if (serverCertificate.isEmpty())
    {
        throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
    }

    if (!tlsSigner.isValidPublicKey(this.serverPublicKey))
    {
        throw new TlsFatalAlert(AlertDescription.certificate_unknown);
    }

    TlsUtils.validateKeyUsage(x509Cert, KeyUsage.digitalSignature);

    super.processServerCertificate(serverCertificate);
}
 
Example 54
Project: signer   File: CertificateHelper.java   Source Code and License 5 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority, String keyStoreType)
		throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, IOException,
		OperatorCreationException, CertificateException, KeyStoreException {

	KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

	X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
	nameBuilder.addRDN(BCStyle.CN, authority.commonName());
	nameBuilder.addRDN(BCStyle.O, authority.organization());
	nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

	X500Name issuer = nameBuilder.build();
	BigInteger serial = BigInteger.valueOf(initRandomSerial());
	X500Name subject = issuer;
	PublicKey pubKey = keyPair.getPublic();

	X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER,
			subject, pubKey);

	generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey));
	generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

	KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
			| KeyUsage.dataEncipherment | KeyUsage.cRLSign);
	generator.addExtension(Extension.keyUsage, false, usage);

	ASN1EncodableVector purposes = new ASN1EncodableVector();
	purposes.add(KeyPurposeId.id_kp_serverAuth);
	purposes.add(KeyPurposeId.id_kp_clientAuth);
	purposes.add(KeyPurposeId.anyExtendedKeyUsage);
	generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

	X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

	KeyStore result = KeyStore.getInstance(keyStoreType/* , PROVIDER_NAME */);
	result.load(null, null);
	result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert });
	return result;
}
 
Example 55
Project: kodokojo   File: SSLUtils.java   Source Code and License 5 votes vote down vote up
private static void addASN1AndKeyUsageExtensions(JcaX509v3CertificateBuilder certificateBuilder) throws CertIOException {
    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    certificateBuilder.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

    KeyUsage keyUsage = new KeyUsage(keyCertSign | digitalSignature | keyEncipherment | dataEncipherment | cRLSign);
    certificateBuilder.addExtension(Extension.keyUsage, false, keyUsage);
}
 
Example 56
Project: shortcircuit-proxy   File: MitmCertificate.java   Source Code and License 5 votes vote down vote up
public void initializeKeyStore() throws GeneralSecurityException, IOException {
    KeyPair keyPair = generateKeyPair(1024);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, commonName);
    nameBuilder.addRDN(BCStyle.O, organization);
    nameBuilder.addRDN(BCStyle.OU, organizationalUnitName);

    X500Name issuer = nameBuilder.build();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());
    X500Name subject = issuer;
    PublicKey pubKey = keyPair.getPublic();
    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER,
            subject, pubKey);

    generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey));
    generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    generator.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

    X509Certificate cert = signCertificate(generator, keyPair.getPrivate());
    KeyStore keystore = KeyStore.getInstance(KEY_STORE_TYPE);
    keystore.load(null, null);
    keystore.setKeyEntry(alias, keyPair.getPrivate(), password, new Certificate[] { cert });
    try (OutputStream os = new FileOutputStream(aliasFile(KEY_STORE_FILE_EXTENSION))) {
        keystore.store(os, password);
    }
    exportPem(aliasFile(".pem"), cert);
}
 
Example 57
Project: photon-model   File: CertificateUtil.java   Source Code and License 5 votes vote down vote up
private static List<ExtensionHolder> getClientExtensions() {
    List<ExtensionHolder> extensions = new ArrayList<>();

    extensions.add(new ExtensionHolder(Extension.basicConstraints, true,
            new BasicConstraints(false)));
    extensions.add(new ExtensionHolder(Extension.keyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature)));
    extensions.add(new ExtensionHolder(Extension.extendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)));

    return extensions;
}
 
Example 58
Project: milo   File: SelfSignedCertificateGenerator.java   Source Code and License 5 votes vote down vote up
protected void addKeyUsage(X509v3CertificateBuilder certificateBuilder) throws CertIOException {
    certificateBuilder.addExtension(
        Extension.keyUsage,
        false,
        new KeyUsage(
            KeyUsage.dataEncipherment |
                KeyUsage.digitalSignature |
                KeyUsage.keyAgreement |
                KeyUsage.keyCertSign |
                KeyUsage.keyEncipherment |
                KeyUsage.nonRepudiation
        )
    );
}
 
Example 59
Project: Aki-SSL   File: TlsRSAKeyExchange.java   Source Code and License 5 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate)
    throws IOException
{
    if (serverCertificate.isEmpty())
    {
        throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
    }

    // Sanity check the PublicKeyFactory
    if (this.serverPublicKey.isPrivate())
    {
        throw new TlsFatalAlert(AlertDescription.internal_error);
    }

    this.rsaServerPublicKey = validateRSAPublicKey((RSAKeyParameters)this.serverPublicKey);

    TlsUtils.validateKeyUsage(x509Cert, KeyUsage.keyEncipherment);

    super.processServerCertificate(serverCertificate);
}
 
Example 60
Project: Aki-SSL   File: TlsPSKKeyExchange.java   Source Code and License 5 votes vote down vote up
public void processServerCertificate(Certificate serverCertificate) throws IOException
{
    if (keyExchange != KeyExchangeAlgorithm.RSA_PSK)
    {
        throw new TlsFatalAlert(AlertDescription.unexpected_message);
    }
    if (serverCertificate.isEmpty())
    {
        throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try
    {
        this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    }
    catch (RuntimeException e)
    {
        throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
    }

    // Sanity check the PublicKeyFactory
    if (this.serverPublicKey.isPrivate())
    {
        throw new TlsFatalAlert(AlertDescription.internal_error);
    }

    this.rsaServerPublicKey = validateRSAPublicKey((RSAKeyParameters)this.serverPublicKey);

    TlsUtils.validateKeyUsage(x509Cert, KeyUsage.keyEncipherment);

    super.processServerCertificate(serverCertificate);
}