List of usage examples for org.bouncycastle.jce X509KeyUsage cRLSign
int cRLSign
To view the source code for org.bouncycastle.jce X509KeyUsage cRLSign.
Click Source Link
From source file:org.cesecore.keybind.impl.OcspKeyBindingTest.java
License:Open Source License
@Test public void testOcspSigningCertificateValidationNegatives() throws IOException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException { assertFalse(//from www. ja v a 2 s. c om "KU!=digitalSignature|nonRepudiation and EKU=id_kp_OCSPSigning should be treated as an invalid OCSP singing certificate.", OcspKeyBinding.isOcspSigningCertificate( getCertificate(X509KeyUsage.keyAgreement + X509KeyUsage.cRLSign, ekuExtensionOnly))); assertFalse( "KU=digitalSignature and EKU!=id_kp_OCSPSigning should be treated as an invalid OCSP singing certificate.", OcspKeyBinding.isOcspSigningCertificate(getCertificate(X509KeyUsage.digitalSignature, null))); assertFalse( "KU=nonRepudiation and EKU!=id_kp_OCSPSigning should be treated as an invalid OCSP singing certificate.", OcspKeyBinding.isOcspSigningCertificate(getCertificate(X509KeyUsage.nonRepudiation, null))); }
From source file:org.cesecore.keybind.impl.OcspKeyBindingTest.java
License:Open Source License
@Test public void testOcspSigningCertificateAssertionNegatives() throws IOException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchAlgorithmException, SignatureException, IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException { try {/* ww w . j ava2 s . c o m*/ new OcspKeyBinding().assertCertificateCompatability(getCertificate(X509KeyUsage.cRLSign, null)); fail("KU=cRLSign and EKU!=id_kp_OCSPSigning should be treated as an invalid OCSP singing certificate."); } catch (CertificateImportException e) { // Expected outcome } }
From source file:org.cesecore.keys.token.CryptoTokenTestUtils.java
License:Open Source License
public static X509CA createTestCAWithSoftCryptoToken(AuthenticationToken authenticationToken, String dN) throws Exception { CaSessionRemote caSession = EjbRemoteHelper.INSTANCE.getRemoteSession(CaSessionRemote.class); CryptoTokenManagementSessionRemote cryptoTokenManagementSession = EjbRemoteHelper.INSTANCE .getRemoteSession(CryptoTokenManagementSessionRemote.class); X509CA x509ca = CaTestUtils.createTestX509CA(dN, "foo123".toCharArray(), false, X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign); // Remove any lingering test CA before starting the tests try {//w w w . ja v a2 s. c o m final int oldCaCryptoTokenId = caSession.getCAInfo(authenticationToken, x509ca.getCAId()).getCAToken() .getCryptoTokenId(); cryptoTokenManagementSession.deleteCryptoToken(authenticationToken, oldCaCryptoTokenId); } catch (CADoesntExistsException e) { // Ok. The old test run cleaned up everything properly. } caSession.removeCA(authenticationToken, x509ca.getCAId()); // Now add the test CA so it is available in the tests caSession.addCA(authenticationToken, x509ca); return x509ca; }
From source file:org.cesecore.util.CertTools.java
License:Open Source License
/** Generates a self signed certificate with keyUsage X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign, i.e. a CA certificate * @throws IOException /*from ww w .j a v a2 s . c o m*/ * @throws OperatorCreationException * @throws CertificateParsingException * */ public static X509Certificate genSelfCert(String dn, long validity, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA, String provider, boolean ldapOrder) throws CertificateParsingException, OperatorCreationException, IOException { final int keyUsage; if (isCA) { keyUsage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; } else { keyUsage = 0; } return genSelfCertForPurpose(dn, validity, policyId, privKey, pubKey, sigAlg, isCA, keyUsage, null, null, provider, ldapOrder); }
From source file:org.cesecore.util.CertTools.java
License:Open Source License
/** * Converts Sun Key usage bits to Bouncy castle key usage kits * /* www . ja va 2s. com*/ * @param sku key usage bit fields according to java.security.cert.X509Certificate#getKeyUsage, must be a boolean aray of size 9. * @return key usage int according to org.bouncycastle.jce.X509KeyUsage#X509KeyUsage, or -1 if input is null. * @see java.security.cert.X509Certificate#getKeyUsage * @see org.bouncycastle.jce.X509KeyUsage#X509KeyUsage */ public static int sunKeyUsageToBC(boolean[] sku) { if (sku == null) { return -1; } int bcku = 0; if (sku[0]) { bcku = bcku | X509KeyUsage.digitalSignature; } if (sku[1]) { bcku = bcku | X509KeyUsage.nonRepudiation; } if (sku[2]) { bcku = bcku | X509KeyUsage.keyEncipherment; } if (sku[3]) { bcku = bcku | X509KeyUsage.dataEncipherment; } if (sku[4]) { bcku = bcku | X509KeyUsage.keyAgreement; } if (sku[5]) { bcku = bcku | X509KeyUsage.keyCertSign; } if (sku[6]) { bcku = bcku | X509KeyUsage.cRLSign; } if (sku[7]) { bcku = bcku | X509KeyUsage.encipherOnly; } if (sku[8]) { bcku = bcku | X509KeyUsage.decipherOnly; } return bcku; }
From source file:org.cesecore.util.CertToolsTest.java
License:Open Source License
/** * Tests the following methods:/*w w w . j av a 2 s. c o m*/ * <ul> * <li>{@link CertTools.checkNameConstraints}</li> * <li>{@link NameConstraint.parseNameConstraintsList}</li> * <li>{@link NameConstraint.toGeneralSubtrees}</li> * </ul> */ @Test public void testNameConstraints() throws Exception { final String permitted = "C=SE,CN=example.com\n" + "example.com\n" + "@mail.example\n" + "user@host.com\n" + "10.0.0.0/8\n" + " C=SE, CN=spacing \n"; final String excluded = "forbidden.example.com\n" + "postmaster@mail.example\n" + "10.1.0.0/16\n" + "::/0"; // IPv6 final List<Extension> extensions = new ArrayList<Extension>(); GeneralSubtree[] permittedSubtrees = NameConstraint .toGeneralSubtrees(NameConstraint.parseNameConstraintsList(permitted)); GeneralSubtree[] excludedSubtrees = NameConstraint .toGeneralSubtrees(NameConstraint.parseNameConstraintsList(excluded)); byte[] extdata = new NameConstraints(permittedSubtrees, excludedSubtrees).toASN1Primitive().getEncoded(); extensions.add(new Extension(Extension.nameConstraints, false, extdata)); final KeyPair testkeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); X509Certificate cacert = CertTools.genSelfCertForPurpose("C=SE,CN=Test Name Constraints CA", 365, null, testkeys.getPrivate(), testkeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign, null, null, "BC", true, extensions); // Allowed subject DNs final X500Name validDN = new X500Name("C=SE,CN=example.com"); // re-used below CertTools.checkNameConstraints(cacert, validDN, null); CertTools.checkNameConstraints(cacert, new X500Name("C=SE,CN=spacing"), null); // Allowed subject alternative names CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.dNSName, "example.com"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.dNSName, "x.sub.example.com"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "someuser@mail.example"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "user@host.com"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("10.0.0.1").getAddress())))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("10.255.255.255").getAddress())))); // Disallowed subject DN checkNCException(cacert, new X500Name("C=DK,CN=example.com"), null, "Disallowed DN (wrong field value) was accepted"); checkNCException(cacert, new X500Name("C=SE,O=Company,CN=example.com"), null, "Disallowed DN (extra field) was accepted"); // Disallowed SAN // The commented out lines are allowed by BouncyCastle but disallowed by the RFC checkNCException(cacert, validDN, new GeneralName(GeneralName.dNSName, "bad.com"), "Disallowed SAN (wrong DNS name) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.dNSName, "forbidden.example.com"), "Disallowed SAN (excluded DNS subdomain) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.rfc822Name, "wronguser@host.com"), "Disallowed SAN (wrong e-mail) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("10.1.0.1").getAddress())), "Disallowed SAN (excluded IPv4 address) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("192.0.2.1").getAddress())), "Disallowed SAN (wrong IPv4 address) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("2001:DB8::").getAddress())), "Disallowed SAN (IPv6 address) was accepted"); }
From source file:org.cesecore.util.provider.EkuPKIXCertPathCheckerTest.java
License:Open Source License
/** @return true if the extendedKeyUsage was accepted */ private boolean validateCert(KeyPair keyPair, boolean isCa, List<String> actualOids, List<String> requiredOids) throws Exception { final long now = System.currentTimeMillis(); final List<Extension> additionalExtensions = new ArrayList<Extension>(); if (actualOids != null) { List<KeyPurposeId> actual = new ArrayList<KeyPurposeId>(); for (final String oid : actualOids) { actual.add(KeyPurposeId.getInstance(new ASN1ObjectIdentifier(oid))); }//from w w w.ja v a 2 s . c om final ExtendedKeyUsage extendedKeyUsage = new ExtendedKeyUsage(actual.toArray(new KeyPurposeId[0])); final ASN1Sequence seq = ASN1Sequence.getInstance(extendedKeyUsage.toASN1Primitive()); final Extension extension = new Extension(Extension.extendedKeyUsage, true, seq.getEncoded()); additionalExtensions.add(extension); } final int ku; if (isCa) { ku = X509KeyUsage.cRLSign | X509KeyUsage.keyCertSign; } else { ku = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment; } final X509Certificate cert = CertTools.genSelfCertForPurpose("CN=dummy", new Date(now - 3600000L), new Date(now + 3600000L), null, keyPair.getPrivate(), keyPair.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, isCa, ku, null, null, BouncyCastleProvider.PROVIDER_NAME, true, additionalExtensions); final PKIXCertPathChecker pkixCertPathChecker = new EkuPKIXCertPathChecker(requiredOids); final Collection<String> unresolvedCritExts = new ArrayList<String>( Arrays.asList(new String[] { Extension.extendedKeyUsage.getId() })); pkixCertPathChecker.check(cert, unresolvedCritExts); return !unresolvedCritExts.contains(Extension.extendedKeyUsage.getId()); }
From source file:org.ejbca.core.ejb.authentication.web.WebAuthenticationProviderSessionBeanTest.java
License:Open Source License
private static X509Certificate generateUnbornCert(String dn, String policyId, PrivateKey privKey, PublicKey pubKey, String sigAlg, boolean isCA) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException, IllegalStateException, NoSuchProviderException, OperatorCreationException, CertificateException, IOException { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; // Create self signed certificate Date firstDate = new Date(); // Set starting date to tomorrow firstDate.setTime(firstDate.getTime() + (24 * 3600 * 1000)); Date lastDate = new Date(); // Set Expiry in two days lastDate.setTime(lastDate.getTime() + ((2 * 24 * 60 * 60 * 1000))); // Transform the PublicKey to be sure we have it in a format that the X509 certificate generator handles, it might be // a CVC public key that is passed as parameter PublicKey publicKey = null;//from www . j a v a 2s.c o m if (pubKey instanceof RSAPublicKey) { RSAPublicKey rsapk = (RSAPublicKey) pubKey; RSAPublicKeySpec rSAPublicKeySpec = new RSAPublicKeySpec(rsapk.getModulus(), rsapk.getPublicExponent()); try { publicKey = KeyFactory.getInstance("RSA").generatePublic(rSAPublicKeySpec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } } else if (pubKey instanceof ECPublicKey) { ECPublicKey ecpk = (ECPublicKey) pubKey; try { ECPublicKeySpec ecspec = new ECPublicKeySpec(ecpk.getW(), ecpk.getParams()); // will throw NPE if key is "implicitlyCA" publicKey = KeyFactory.getInstance("EC").generatePublic(ecspec); } catch (InvalidKeySpecException e) { publicKey = pubKey; } catch (NullPointerException e) { publicKey = pubKey; } } else { publicKey = pubKey; } // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this // bean is created. byte[] serno = new byte[8]; SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); random.setSeed(new Date().getTime()); random.nextBytes(serno); final SubjectPublicKeyInfo pkinfo = new SubjectPublicKeyInfo( (ASN1Sequence) ASN1Primitive.fromByteArray(publicKey.getEncoded())); X509v3CertificateBuilder certbuilder = new X509v3CertificateBuilder(CertTools.stringToBcX500Name(dn), new java.math.BigInteger(serno).abs(), firstDate, lastDate, CertTools.stringToBcX500Name(dn), pkinfo); // Basic constranits is always critical and MUST be present at-least in CA-certificates. BasicConstraints bc = new BasicConstraints(isCA); certbuilder.addExtension(Extension.basicConstraints, true, bc); // Put critical KeyUsage in CA-certificates if (isCA) { X509KeyUsage ku = new X509KeyUsage(keyusage); certbuilder.addExtension(Extension.keyUsage, true, ku); } // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Firefox. try { if (isCA) { ASN1InputStream spkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); ASN1InputStream apkiAsn1InputStream = new ASN1InputStream( new ByteArrayInputStream(publicKey.getEncoded())); try { SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo( (ASN1Sequence) spkiAsn1InputStream.readObject()); X509ExtensionUtils x509ExtensionUtils = new BcX509ExtensionUtils(); SubjectKeyIdentifier ski = x509ExtensionUtils.createSubjectKeyIdentifier(spki); SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) apkiAsn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); certbuilder.addExtension(Extension.subjectKeyIdentifier, false, ski); certbuilder.addExtension(Extension.authorityKeyIdentifier, false, aki); } finally { spkiAsn1InputStream.close(); apkiAsn1InputStream.close(); } } } catch (IOException e) { // do nothing } // CertificatePolicies extension if supplied policy ID, always non-critical if (policyId != null) { PolicyInformation pi = new PolicyInformation(new ASN1ObjectIdentifier(policyId)); DERSequence seq = new DERSequence(pi); certbuilder.addExtension(Extension.certificatePolicies, false, seq); } final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder("SHA1withRSA") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privKey), 20480); final X509CertificateHolder certHolder = certbuilder.build(signer); final X509Certificate selfcert = (X509Certificate) CertTools.getCertfromByteArray(certHolder.getEncoded()); return selfcert; }
From source file:org.ejbca.core.ejb.ca.sign.SignSessionTest.java
License:Open Source License
/** * test to set specific key usage//from ww w . j a va 2 s . c om * * @throws Exception if an error occurs... */ public void test06KeyUsage() throws Exception { log.trace(">test06KeyUsage()"); userAdminSession.setUserStatus(admin, "foo", UserDataConstants.STATUS_NEW); log.debug("Reset status of 'foo' to NEW"); int keyusage1 = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment; X509Certificate cert = (X509Certificate) signSession.createCertificate(admin, "foo", "foo123", rsakeys.getPublic(), keyusage1, null, null); assertNotNull("Misslyckades skapa cert", cert); log.debug("Cert=" + cert.toString()); boolean[] retKU = cert.getKeyUsage(); assertTrue("Fel KeyUsage, digitalSignature finns ej!", retKU[0]); assertTrue("Fel KeyUsage, keyEncipherment finns ej!", retKU[2]); assertTrue("Fel KeyUsage, cRLSign finns!", !retKU[6]); userAdminSession.setUserStatus(admin, "foo", UserDataConstants.STATUS_NEW); log.debug("Reset status of 'foo' to NEW"); int keyusage2 = X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign; X509Certificate cert1 = (X509Certificate) signSession.createCertificate(admin, "foo", "foo123", rsakeys.getPublic(), keyusage2, null, null); assertNotNull("Misslyckades skapa cert", cert1); retKU = cert1.getKeyUsage(); assertTrue("Fel KeyUsage, keyCertSign finns ej!", retKU[5]); assertTrue("Fel KeyUsage, cRLSign finns ej!", retKU[6]); assertTrue("Fel KeyUsage, digitalSignature finns!", !retKU[0]); log.debug("Cert=" + cert1.toString()); log.trace("<test06KeyUsage()"); }
From source file:org.ejbca.core.ejb.ca.sign.SignSessionWithRsaTest.java
License:Open Source License
/** * test to set specific key usage// ww w. j a va 2 s . c o m * * @throws Exception if an error occurs... */ @Test public void testKeyUsage() throws Exception { log.trace(">test06KeyUsage()"); endEntityManagementSession.setUserStatus(internalAdmin, RSA_USERNAME, EndEntityConstants.STATUS_NEW); log.debug("Reset status of 'foo' to NEW"); int keyusage1 = X509KeyUsage.digitalSignature | X509KeyUsage.keyEncipherment; X509Certificate cert = (X509Certificate) signSession.createCertificate(internalAdmin, RSA_USERNAME, "foo123", new PublicKeyWrapper(rsakeys.getPublic()), keyusage1, null, null); assertNotNull("Failed to create certificate", cert); log.debug("Cert=" + cert.toString()); boolean[] retKU = cert.getKeyUsage(); assertTrue("Fel KeyUsage, digitalSignature finns ej!", retKU[0]); assertTrue("Fel KeyUsage, keyEncipherment finns ej!", retKU[2]); assertTrue("Fel KeyUsage, cRLSign finns!", !retKU[6]); endEntityManagementSession.setUserStatus(internalAdmin, RSA_USERNAME, EndEntityConstants.STATUS_NEW); log.debug("Reset status of 'foo' to NEW"); int keyusage2 = X509KeyUsage.keyCertSign | X509KeyUsage.cRLSign; X509Certificate cert1 = (X509Certificate) signSession.createCertificate(internalAdmin, RSA_USERNAME, "foo123", new PublicKeyWrapper(rsakeys.getPublic()), keyusage2, null, null); assertNotNull("Failed to create certificate", cert1); retKU = cert1.getKeyUsage(); assertTrue("Fel KeyUsage, keyCertSign finns ej!", retKU[5]); assertTrue("Fel KeyUsage, cRLSign finns ej!", retKU[6]); assertTrue("Fel KeyUsage, digitalSignature finns!", !retKU[0]); log.debug("Cert=" + cert1.toString()); log.trace("<test06KeyUsage()"); }