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: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 2
Project: ipack   File: TlsUtils.java   View source code 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 3
Project: oscm   File: CertificateHandler.java   View source code 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 4
Project: gwt-crypto   File: KeyUsageValidation.java   View source code 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 5
Project: gwt-crypto   File: TlsUtils.java   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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: credhub   File: CertificateReaderTest.java   View source code 6 votes vote down vote up
@Test
public void returnsParametersCorrectly() {
  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.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.getSubjectName().toString(), equalTo(distinguishedName));
}
 
Example 12
Project: keystore-explorer   File: DKeyUsage.java   View source code 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 13
Project: dss   File: CertificateService.java   View source code 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 14
Project: dss   File: CertificateService.java   View source code 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 15
Project: TinyTravelTracker   File: TlsUtils.java   View source code 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 16
Project: runrightfast-vertx   File: CertificateServiceImplTest.java   View source code 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 17
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 18
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 19
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 20
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 21
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 22
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 23
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 24
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 25
Project: jtrust   File: KeyUsageCertificateConstraintTest.java   View source code 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 26
Project: CryptMeme   File: TestUtils.java   View source code 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 27
Project: CryptMeme   File: TestUtils.java   View source code 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 28
Project: CryptMeme   File: TlsUtils.java   View source code 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 29
Project: freeVM   File: CertGen.java   View source code 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 30
Project: jqm   File: CertificateRequest.java   View source code 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 31
Project: irma_future_id   File: KeyUsageValidation.java   View source code 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 32
Project: irma_future_id   File: TlsUtils.java   View source code 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 33
Project: irma_future_id   File: TestUtils.java   View source code 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 34
Project: irma_future_id   File: TestUtils.java   View source code 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 35
Project: bc-java   File: KeyUsageValidation.java   View source code 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 36
Project: bc-java   File: TlsUtils.java   View source code 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 37
Project: bc-java   File: TestUtils.java   View source code 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 38
Project: bc-java   File: TestUtils.java   View source code 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 39
Project: cagrid-core   File: CertUtil.java   View source code 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   View source code 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);
}