List of usage examples for org.bouncycastle.asn1.x509 X509Extensions KeyUsage
ASN1ObjectIdentifier KeyUsage
To view the source code for org.bouncycastle.asn1.x509 X509Extensions KeyUsage.
Click Source Link
From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java
License:Apache License
protected void checkProxyConstraints(TBSCertificateStructure proxy, TBSCertificateStructure issuer, X509Certificate checkedProxy) throws ProxyPathValidatorException, IOException { logger.debug("enter: checkProxyConstraints"); X509Extensions extensions;/*from w w w . ja v a 2s. c o m*/ DERObjectIdentifier oid; X509Extension ext; X509Extension proxyKeyUsage = null; extensions = proxy.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); while (e.hasMoreElements()) { oid = (DERObjectIdentifier) e.nextElement(); ext = extensions.getExtension(oid); if (oid.equals(X509Extensions.SubjectAlternativeName) || oid.equals(X509Extensions.IssuerAlternativeName)) { // No Alt name extensions - 3.2 & 3.5 throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "Proxy certificate cannot contain subject or issuer alternative name extension"); } else if (oid.equals(X509Extensions.BasicConstraints)) { // Basic Constraint must not be true - 3.8 BasicConstraints basicExt = BouncyCastleUtil.getBasicConstraints(ext); if (basicExt.isCA()) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "Proxy certificate cannot have BasicConstraint CA=true"); } } else if (oid.equals(X509Extensions.KeyUsage)) { proxyKeyUsage = ext; boolean[] keyUsage = BouncyCastleUtil.getKeyUsage(ext); // these must not be asserted if (keyUsage[1] || keyUsage[5]) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "The keyCertSign and nonRepudiation bits must not be asserted in Proxy Certificate"); } boolean[] issuerKeyUsage = getKeyUsage(issuer); if (issuerKeyUsage != null) { for (int i = 0; i < 9; i++) { if (i == 1 || i == 5) { continue; } if (!issuerKeyUsage[i] && keyUsage[i]) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "Bad KeyUsage in Proxy Certificate"); } } } } } } extensions = issuer.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); while (e.hasMoreElements()) { oid = (DERObjectIdentifier) e.nextElement(); ext = extensions.getExtension(oid); if (oid.equals(X509Extensions.KeyUsage)) { // If issuer has it then proxy must have it also if (proxyKeyUsage == null) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "KeyUsage extension missing in Proxy Certificate"); } // If issuer has it as critical so does the proxy if (ext.isCritical() && !proxyKeyUsage.isCritical()) { throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy, "KeyUsage extension in Proxy Certificate is not critical"); } } } } logger.debug("exit: checkProxyConstraints"); }
From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java
License:Apache License
protected void checkUnsupportedCriticalExtensions(TBSCertificateStructure crt, int certType, X509Certificate checkedProxy) throws ProxyPathValidatorException { logger.debug("enter: checkUnsupportedCriticalExtensions"); X509Extensions extensions = crt.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); if (ext.isCritical()) { if (oid.equals(X509Extensions.BasicConstraints) || oid.equals(X509Extensions.KeyUsage) || (oid.equals(ProxyCertInfo.OID) && CertUtil.isGsi4Proxy(certType)) || (oid.equals(ProxyCertInfo.OLD_OID) && CertUtil.isGsi3Proxy(certType))) { } else { throw new ProxyPathValidatorException(ProxyPathValidatorException.UNSUPPORTED_EXTENSION, checkedProxy, "Unsuppored critical exception : " + oid.getId()); }/*from w w w . j ava 2 s . c o m*/ } } } logger.debug("exit: checkUnsupportedCriticalExtensions"); }
From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java
License:Apache License
protected boolean[] getKeyUsage(TBSCertificateStructure crt) throws IOException { X509Extensions extensions = crt.getExtensions(); if (extensions == null) { return null; }//ww w . j a v a 2 s . c o m X509Extension ext = extensions.getExtension(X509Extensions.KeyUsage); return (ext != null) ? BouncyCastleUtil.getKeyUsage(ext) : null; }
From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java
License:Apache License
public static X509Certificate[] buildChain() throws Exception { // create the certification request KeyPair pair = Utils.generateRSAKeyPair(); PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair); // create a root certificate KeyPair rootPair = Utils.generateRSAKeyPair(); X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair); // validate the certification request if (!request.verify("BC")) { System.out.println("request failed to verify!"); System.exit(1);/*from w ww . ja va 2 s . c om*/ } // create the certificate using the information in the request X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(rootCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(rootCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // extract the extension request attribute ASN1Set attributes = request.getCertificationRequestInfo().getAttributes(); for (int i = 0; i != attributes.size(); i++) { Attribute attr = Attribute.getInstance(attributes.getObjectAt(i)); // process extension request if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) { X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0)); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets()); } } } X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate()); return new X509Certificate[] { issuedCert, rootCert }; }
From source file:io.aos.crypto.spl06.X509V3CreateExample.java
License:Apache License
public static X509Certificate generateV3Certificate(KeyPair pair) throws InvalidKeyException, NoSuchProviderException, SignatureException { // generate the certificate X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X500Principal("CN=Test Certificate")); certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(new X500Principal("CN=Test Certificate")); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); return certGen.generateX509Certificate(pair.getPrivate(), "BC"); }
From source file:io.aos.crypto.spl07.Utils.java
License:Apache License
/** * Generate a sample V3 certificate to use as an intermediate CA certificate *//* w w w . j a v a2 s.c o m*/ public static X509Certificate generateIntermediateCert(PublicKey intKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test Intermediate Certificate")); certGen.setPublicKey(intKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); 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.generateX509Certificate(caKey, "BC"); }
From source file:io.aos.crypto.spl07.Utils.java
License:Apache License
/** * Generate a sample V3 certificate to use as an end entity certificate *///from w ww . j av a 2 s.c o m public static X509Certificate generateEndEntityCert(PublicKey entityKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test End Certificate")); certGen.setPublicKey(entityKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); 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.generateX509Certificate(caKey, "BC"); }
From source file:io.aos.crypto.spl08.CertReqSolution.java
License:Apache License
public static void main(String... args) throws Exception { // create the CA certificates X500PrivateCredential rootCredential = Utils.createRootCredential(); X500PrivateCredential interCredential = Utils.createIntermediateCredential(rootCredential.getPrivateKey(), rootCredential.getCertificate()); // parse the request PEMReader pRd = new PEMReader(new InputStreamReader(new FileInputStream("pkcs10.req"))); PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject(); // get our validation certificate X509Certificate caCert = interCredential.getCertificate(); X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000)); certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject()); certGen.setPublicKey(request.getPublicKey("BC")); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); // provide some basic extensions and mark the certificate as appropriate for signing and encipherment certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(request.getPublicKey("BC"))); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); // create the chain List chain = Arrays//w w w. j av a2 s . c o m .asList(new Certificate[] { certGen.generateX509Certificate(interCredential.getPrivateKey(), "BC"), interCredential.getCertificate(), rootCredential.getCertificate() }); // create the CertPath CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC"); CertPath path = fact.generateCertPath(chain); // write it out FileOutputStream fOut = new FileOutputStream("pkcs7.pth"); fOut.write(path.getEncoded("PKCS7")); fOut.close(); }
From source file:io.spikex.core.Main.java
License:Apache License
private void createKeyStore(final YamlDocument conf) { YamlDocument confKeyStore = conf.getDocument(CONF_KEY_KEYSTORE); boolean generate = confKeyStore.getValue(CONF_KEY_GENERATE, DEF_GENERATE_KEYSTORE); if (generate) { Path keyStorePath = Paths .get(confKeyStore.getValue(CONF_KEY_PATH, m_confPath.resolve(DEF_KEYSTORE_PATH).toString())) .toAbsolutePath().normalize(); if (!Files.exists(keyStorePath)) { Provider bcProvider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME); if (bcProvider == null) { Security.addProvider(new BouncyCastleProvider()); }/*from w w w . j a v a2 s . co m*/ String password = confKeyStore.getValue(CONF_KEY_PASSWORD, DEF_KEYSTORE_PASSWORD); String hostFqdn = confKeyStore.getValue(CONF_KEY_HOST_FQDN, HostOs.hostName()); List<String> subjAltNames = confKeyStore.getValue(CONF_KEY_SUBJECT_ALT_NAME, new ArrayList()); try (FileOutputStream out = new FileOutputStream(keyStorePath.toFile())) { m_logger.info("Generating keystore: {}", keyStorePath); KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME); SecureRandom rnd = new SecureRandom(); generator.initialize(2048, rnd); KeyPair pair = generator.generateKeyPair(); // DN X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.C, System.getProperty("user.country.format", "NU")); nameBuilder.addRDN(BCStyle.OU, "Self-signed test certificate"); nameBuilder.addRDN(BCStyle.OU, "For testing purposes only"); nameBuilder.addRDN(BCStyle.O, "Spike.x"); nameBuilder.addRDN(BCStyle.CN, hostFqdn); long oneDay = 24 * 60 * 60 * 1000; Date notBefore = new Date(System.currentTimeMillis() - oneDay); // Yesterday Date notAfter = new Date(System.currentTimeMillis() + (oneDay * 3 * 365)); // 3 years BigInteger serialNum = BigInteger.valueOf(rnd.nextLong()); X509v3CertificateBuilder x509v3Builder = new JcaX509v3CertificateBuilder(nameBuilder.build(), serialNum, notBefore, notAfter, nameBuilder.build(), pair.getPublic()); // // Extensions // x509v3Builder.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); x509v3Builder.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); x509v3Builder.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); GeneralName[] dnsNames = new GeneralName[subjAltNames.size()]; for (int i = 0; i < subjAltNames.size(); i++) { String name = subjAltNames.get(i); m_logger.info("Adding subject alt name: {}", name); dnsNames[i] = new GeneralName(GeneralName.dNSName, name); } x509v3Builder.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(dnsNames)); ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(pair.getPrivate()); X509Certificate cert = new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(x509v3Builder.build(signer)); // Validate cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); // Save in keystore KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); ks.setKeyEntry(hostFqdn, pair.getPrivate(), password.toCharArray(), new Certificate[] { cert }); m_logger.info("Created self-signed certificate: {}", hostFqdn); ks.store(out, password.toCharArray()); } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | NoSuchProviderException | OperatorCreationException | InvalidKeyException | SignatureException e) { throw new RuntimeException("Failed to create keystore: " + keyStorePath, e); } } } }
From source file:krypto.KryptoService.java
License:Apache License
/** * Erzeugt ein x509 v3-Zertifikat, das 1 Tag lang gltig ist. * @return/* w w w .ja v a2 s .c o m*/ * @throws Exception */ public static X509Certificate generateCertificate(String algorithm) { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); KeyPair pair = null; try { pair = generateKeyPair(algorithm, 1024); } catch (Exception e) { try { pair = generateKeyPair(algorithm, 512); } catch (Exception e2) { System.out.println(e2.getMessage()); } } long day = 24 * 60 * 60 * 1000; // 1 Tag gltig certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); certGen.setIssuerDN(new X509Name(new X500Principal("CN=Test Certificate").getName())); certGen.setNotBefore(new Date(System.currentTimeMillis() - 500000)); certGen.setNotAfter(new Date(System.currentTimeMillis() + day)); certGen.setSubjectDN(new X509Name(new X500Principal("CN=Test Certificate").getName())); certGen.setPublicKey(pair.getPublic()); certGen.setSignatureAlgorithm("SHA256WithRSAEncryption"); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); certGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment)); certGen.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); certGen.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test"))); X509Certificate cert = null; try { cert = certGen.generate(pair.getPrivate(), "BC"); } catch (CertificateEncodingException e) { System.out.println("CertificateEncodingException"); } catch (InvalidKeyException e2) { System.out.println("InvalidKeyException: " + e2.getMessage()); } catch (Exception e3) { // do nothing } return cert; }