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:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
static private X509V3CertificateGenerator addCaExtensions(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); gen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyCertSign | KeyUsage.cRLSign)); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // gen.addExtension(X509Extensions.SubjectAlternativeName, false, // new GeneralNames(new GeneralName(GeneralName.rfc822Name, // "test@test.test"))); // netscape-cert-type "2.16.840.1.113730.1.1" // * bit-0 SSL client - 128 // * bit-1 SSL server - 64 // * bit-2 S/MIME - 32 // * bit-3 Object Signing - 16 // * bit-4 Reserved - 8 // * bit-5 SSL CA - 4 // * bit-6 S/MIME CA - 2 // * bit-7 Object Signing CA - 1 gen.addExtension(netscapeCertType, false, new DERBitString(new byte[] { Byte.MAX_VALUE })); // was 4 addSubjectKeyIdentifier(gen, pubKey); addAuthorityKeyIdentifier(gen, pubKey); return gen;/*from www . j av a 2 s .c o m*/ }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
@SuppressWarnings("unused") static private X509V3CertificateGenerator addServerExtensions(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); gen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment)); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); // gen.addExtension(X509Extensions.SubjectAlternativeName, false, // new GeneralNames(new GeneralName(GeneralName.rfc822Name, // "test@test.test"))); // netscape-cert-type "2.16.840.1.113730.1.1" // * bit-0 SSL client - 128 // * bit-1 SSL server - 64 // * bit-2 S/MIME - 32 // * bit-3 Object Signing - 16 // * bit-4 Reserved - 8 // * bit-5 SSL CA - 4 // * bit-6 S/MIME CA - 2 // * bit-7 Object Signing CA - 1 gen.addExtension(netscapeCertType, false, new DERBitString(new byte[] { -16 })); // was 4 addSubjectKeyIdentifier(gen, pubKey); addAuthorityKeyIdentifier(gen, pubKey); return gen;// ww w . j a v a 2 s .c o m }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
static private X509V3CertificateGenerator addSSLServerExtensions(X509V3CertificateGenerator gen) { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); gen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature)); Vector<DERObjectIdentifier> extendedKeyUsageV = new Vector<DERObjectIdentifier>(); extendedKeyUsageV.add(KeyPurposeId.id_kp_serverAuth); extendedKeyUsageV.add(KeyPurposeId.id_kp_clientAuth); // Netscape Server Gated Crypto // extendedKeyUsageV.add(new DERObjectIdentifier("2.16.840.1.113730.4.1")); // Microsoft Server Gated Crypto // extendedKeyUsageV // .add(new DERObjectIdentifier("1.3.6.1.4.1.311.10.3.3")); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(extendedKeyUsageV)); // gen.addExtension(X509Extensions.SubjectAlternativeName, false, // new GeneralNames(new GeneralName(GeneralName.rfc822Name, // "test@test.test"))); // gen.addExtension(netscapeCertType, false, new DERBitString( // new byte[] { 64 })); return gen;//from w ww . j a v a 2 s. c om }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
License:Open Source License
static private X509V3CertificateGenerator addClientExtensions(X509V3CertificateGenerator gen) throws Exception { gen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); gen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.keyCertSign)); gen.addExtension(X509Extensions.ExtendedKeyUsage, getExtendedKeyUsageCriticality(), new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth)); return gen;// www. j a va2 s . c om }
From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java
License:Apache License
private X509Certificate generateV3Certificate(KeyPair pair, String certSubjectDN, Calendar before, Calendar expiry) throws CryptoException { X509V3CertificateGenerator cert = new X509V3CertificateGenerator(); /* Set the certificate serial number to a random number */ Random rand = new Random(); rand.setSeed(System.currentTimeMillis()); /* Generates a number between 0 and 2^32 as the serial */ BigInteger serial = BigInteger.valueOf(rand.nextInt(Integer.MAX_VALUE)); logger.info("Setting X509 Cert Serial to: " + serial); cert.setSerialNumber(serial);/*from w w w .j a v a2 s . c o m*/ /* Set the certificate issuer */ cert.setIssuerDN(new X500Principal(this.certIssuerDN)); /* Set the start of valid period. */ cert.setNotBefore(before.getTime()); /* Set the certificate expiry date. */ cert.setNotAfter(expiry.getTime()); /* Set the subject */ cert.setSubjectDN(new X500Principal(certSubjectDN)); cert.setPublicKey(pair.getPublic()); /* Signature algorithm, this may need to be changed if not all hosts have SHA256 and RSA implementations */ cert.setSignatureAlgorithm("SHA512withRSA"); cert.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); /* Only for signing */ cert.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign)); cert.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth)); /* Set a contact email address for the issuer */ cert.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, this.certIssuerEmail))); logger.debug("Generating X509Certificate for key pair: " + pair); try { /* Use the BouncyCastle provider to actually generate the X509Certificate now */ return cert.generateX509Certificate(pair.getPrivate(), "BC"); } catch (InvalidKeyException e) { this.logger.error("InvalidKeyException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (NoSuchProviderException e) { this.logger.error("NoSuchProviderException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (SecurityException e) { this.logger.error("SecurityException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } catch (SignatureException e) { this.logger.error("SignatureException thrown, " + e.getLocalizedMessage()); this.logger.debug(e.toString()); throw new CryptoException(e.getLocalizedMessage(), e); } }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateComplianceCA_IT.java
License:Open Source License
/** * checks Key Usage constraints of a java certificate. */* w ww .ja va 2 s. c o m*/ * @param m_JavaCert * the certificate to check as java object. * @return true if the given certificate has a KeyUsage extension of 'non * repudiation' (OID: 2.5.29.15) marked as critical. * @see PKCS11Signer#findCertificateWithNonRepudiationCritical() */ private boolean isKeyUsageNonRepudiationCritical(java.security.cert.X509Certificate javaCert) { boolean isNonRepudiationPresent = false; boolean isKeyUsageCritical = false; Set<String> oids = javaCert.getCriticalExtensionOIDs(); if (oids != null) { // check presence between critical extensions of oid:2.5.29.15 // (KeyUsage) isKeyUsageCritical = oids.contains(X509Extensions.KeyUsage.getId()); } boolean[] keyUsages = javaCert.getKeyUsage(); if (keyUsages != null) { //check non repudiation (index 1) /* * now check the elements on KeyUsage, only nonRepudiation should be there * nothing else is allowed, see (only Italian available): * Deliberazione CNIPA del 17 febbraio 2005 n 4 * Articolo 4 - Profilo dei certificati qualificati * comma 5, punto a * */ //keyusage isNonRepudiationPresent = (keyUsages[1] & //nonRepudiation !(keyUsages[0] | // digitalSignature (0), keyUsages[2] | // keyEncipherment (2), keyUsages[3] | // dataEncipherment (3), keyUsages[4] | // keyAgreement (4), keyUsages[5] | // keyCertSign (5), keyUsages[6] | // cRLSign (6), keyUsages[7] | // encipherOnly (7), keyUsages[8] // decipherOnly (8) } )); } return (isKeyUsageCritical && isNonRepudiationPresent); }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateCompliance_IT.java
License:Open Source License
@Override public CertificateState verifyCertificateCompliance(XFrame _xFrame, Object arg0) throws IllegalArgumentException, Exception { m_xQc = (XOX_X509Certificate) UnoRuntime.queryInterface(XOX_X509Certificate.class, arg0); if (m_xQc == null) throw (new IllegalArgumentException( "XOX_CertificateComplianceProcedure#verifyCertificateCertificateCompliance wrong argument")); m_aCertificateState = CertificateState.OK; m_aLogger.log("verifyCertificateCompliance"); //convert the certificate to java internal representation java.security.cert.CertificateFactory cf; try {//from w w w. java 2 s . co m cf = java.security.cert.CertificateFactory.getInstance("X.509"); java.io.ByteArrayInputStream bais = null; bais = new java.io.ByteArrayInputStream(m_xQc.getCertificateAttributes().getDEREncoded()); m_JavaCert = (java.security.cert.X509Certificate) cf.generateCertificate(bais); //check for version, if version is not 3, exits, certificate cannot be used if (m_JavaCert.getVersion() != 3) { m_xQc.setCertificateElementErrorState(GlobConstant.m_sX509_CERTIFICATE_VERSION, CertificateElementState.INVALID_value); setCertificateStateHelper(CertificateState.MALFORMED_CERTIFICATE); m_xQc.getCertificateDisplayObj().setCertificateElementCommentString(CertificateElementID.VERSION, "Version MUST be V3"); return m_aCertificateState; } //check for validity date try { /* //test for date information //not yet valid GregorianCalendar aCal = new GregorianCalendar(2008,12,12); //expired GregorianCalendar aCal = new GregorianCalendar(2019,12,12); m_JavaCert.checkValidity(aCal.getTime());*/ m_JavaCert.checkValidity(); } catch (CertificateExpiredException e) { m_xQc.setCertificateElementErrorState(GlobConstant.m_sX509_CERTIFICATE_NOT_AFTER, CertificateElementState.INVALID_value); setCertificateStateHelper(CertificateState.EXPIRED); m_xQc.getCertificateDisplayObj().setCertificateElementCommentString(CertificateElementID.NOT_AFTER, "The date is elapsed."); } catch (CertificateNotYetValidException e) { m_xQc.setCertificateElementErrorState(GlobConstant.m_sX509_CERTIFICATE_NOT_BEFORE, CertificateElementState.INVALID_value); setCertificateStateHelper(CertificateState.NOT_ACTIVE); m_xQc.getCertificateDisplayObj().setCertificateElementCommentString(CertificateElementID.NOT_BEFORE, "The date is not yet arrived."); } //check the KeyUsage extension int tempState = CertificateElementState.OK_value; if (!isKeyUsageNonRepudiationCritical(m_JavaCert)) { tempState = CertificateElementState.INVALID_value; setCertificateStateHelper(CertificateState.NOT_COMPLIANT); } m_xQc.setCertificateElementErrorState(X509Extensions.KeyUsage.getId(), tempState); } catch (CertificateException e) { m_aLogger.severe(e); setCertificateStateHelper(CertificateState.MALFORMED_CERTIFICATE); throw (new com.sun.star.uno.Exception(" wrapped exception: ")); } //convert to Bouncy Castle representation ByteArrayInputStream as = new ByteArrayInputStream(m_xQc.getCertificateAttributes().getDEREncoded()); ASN1InputStream aderin = new ASN1InputStream(as); DERObject ado = null; try { ado = aderin.readObject(); X509CertificateStructure x509Str = new X509CertificateStructure((ASN1Sequence) ado); //check issuer field for conformance TBSCertificateStructure xTBSCert = x509Str.getTBSCertificate(); //check if both IssuerUniqueID and SubjectUniqueID are present //ETSI 102 280 5.3 if (!isOKUniqueIds(xTBSCert)) { setCertificateStateHelper(CertificateState.CORE_CERTIFICATE_ELEMENT_INVALID); return m_aCertificateState; } if (!isIssuerIdOk(xTBSCert)) { m_xQc.setCertificateElementErrorState("IssuerName", CertificateElementState.INVALID_value); setCertificateStateHelper(CertificateState.NOT_COMPLIANT); } //check if qcStatements are present //the function set the error itself if (!hasQcStatements(xTBSCert)) { return m_aCertificateState; } } catch (java.io.IOException e) { m_aLogger.severe(e); setCertificateStateHelper(CertificateState.MALFORMED_CERTIFICATE); throw (new com.sun.star.uno.Exception(" wrapped exception: ")); } catch (java.lang.Exception e) { m_aLogger.severe(e); setCertificateStateHelper(CertificateState.MALFORMED_CERTIFICATE); throw (new com.sun.star.uno.Exception(" wrapped exception: ")); } return m_aCertificateState; }
From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateCompliance_IT.java
License:Open Source License
/** * checks Key Usage constraints of a java certificate. */*from www.j av a2 s. c o m*/ * @param m_JavaCert * the certificate to check as java object. * @return true if the given certificate has a KeyUsage extension of 'non * repudiation' (OID: 2.5.29.15) marked as critical. * @see PKCS11Signer#findCertificateWithNonRepudiationCritical() */ private boolean isKeyUsageNonRepudiationCritical(java.security.cert.X509Certificate javaCert) { boolean isNonRepudiationPresent = false; boolean isKeyUsageCritical = false; String err = ""; Set<String> oids = javaCert.getCriticalExtensionOIDs(); if (oids != null) { // check presence between critical extensions of oid:2.5.29.15 // (KeyUsage) isKeyUsageCritical = oids.contains(X509Extensions.KeyUsage.getId()); } else err = "Key usage is NOT marked critical" + "\r"; boolean[] keyUsages = javaCert.getKeyUsage(); if (keyUsages != null) { //check non repudiation (index 1) /* * now check the elements on KeyUsage, only nonRepudiation should be there * nothing else is allowed, see (only Italian available): * Deliberazione CNIPA del 17 febbraio 2005 n 4 * Articolo 4 - Profilo dei certificati qualificati * comma 5, punto a * */ //keyusage isNonRepudiationPresent = (keyUsages[1] & //nonRepudiation !(keyUsages[0] | // digitalSignature (0), keyUsages[2] | // keyEncipherment (2), keyUsages[3] | // dataEncipherment (3), keyUsages[4] | // keyAgreement (4), keyUsages[5] | // keyCertSign (5), keyUsages[6] | // cRLSign (6), keyUsages[7] | // encipherOnly (7), keyUsages[8] // decipherOnly (8) } )); } if (!isNonRepudiationPresent) err = err + "missing nonRepudiation"; m_xQc.getCertificateDisplayObj().setCertificateExtensionCommentString(X509Extensions.KeyUsage.getId(), err); return (isKeyUsageCritical && isNonRepudiationPresent); }
From source file:cybervillains.ca.CertificateCreator.java
License:Open Source License
/** * Creates a typical Certification Authority (CA) certificate. * //from www.j ava2 s . com * @throws SecurityException * @throws InvalidKeyException * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws CertificateException */ @SuppressWarnings("deprecation") public static X509Certificate createTypicalMasterCert(final KeyPair keyPair) throws SignatureException, InvalidKeyException, SecurityException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException { X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); X509Principal issuer = new X509Principal( "O=CyberVillians.com,OU=CyberVillians Certification Authority,C=US"); // Create v3CertGen.setSerialNumber(BigInteger.valueOf(1)); v3CertGen.setIssuerDN(issuer); v3CertGen.setSubjectDN(issuer); // Set validity period v3CertGen .setNotBefore(new Date(System.currentTimeMillis() - 12 /* months */ * (1000L * 60 * 60 * 24 * 30))); v3CertGen .setNotAfter(new Date(System.currentTimeMillis() + 240 /* months */ * (1000L * 60 * 60 * 24 * 30))); // Set signature algorithm & public key v3CertGen.setPublicKey(keyPair.getPublic()); v3CertGen.setSignatureAlgorithm(CertificateCreator.SIGN_ALGO); // Add typical extensions for signing cert v3CertGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic())); v3CertGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); v3CertGen.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.cRLSign | KeyUsage.keyCertSign)); DERSequence typicalCAExtendedKeyUsages = new DERSequence( new ASN1Encodable[] { new DERObjectIdentifier(ExtendedKeyUsageConstants.serverAuth), new DERObjectIdentifier(ExtendedKeyUsageConstants.OCSPSigning), new DERObjectIdentifier(ExtendedKeyUsageConstants.verisignUnknown) }); v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false, typicalCAExtendedKeyUsages); X509Certificate cert = v3CertGen.generate(keyPair.getPrivate(), "BC"); cert.checkValidity(new Date()); cert.verify(keyPair.getPublic()); return cert; }
From source file:de.mendelson.util.security.keygeneration.KeyGenerator.java
/** * Generates a self-signed X509 Version 3 certificate * *///from w w w . jav a2 s. c o m private X509Certificate generateCertificate(PublicKey publicKey, PrivateKey privateKey, KeyGenerationValues generationValues) throws Exception { //Stores certificate attributes Hashtable<ASN1ObjectIdentifier, String> attributes = new Hashtable<ASN1ObjectIdentifier, String>(); Vector<ASN1ObjectIdentifier> order = new Vector<ASN1ObjectIdentifier>(); attributes.put(X509Name.CN, generationValues.getCommonName()); order.add(0, X509Name.CN); attributes.put(X509Name.OU, generationValues.getOrganisationUnit()); order.add(0, X509Name.OU); attributes.put(X509Name.O, generationValues.getOrganisationName()); order.add(0, X509Name.O); attributes.put(X509Name.L, generationValues.getLocalityName()); order.add(0, X509Name.L); attributes.put(X509Name.ST, generationValues.getStateName()); order.add(0, X509Name.ST); attributes.put(X509Name.C, generationValues.getCountryCode()); order.add(0, X509Name.C); attributes.put(X509Name.E, generationValues.getEmailAddress()); order.add(0, X509Name.E); X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator(); // Set the issuer distinguished name certificateGenerator.setIssuerDN(new X509Principal(order, attributes)); //add a key extension if this is requested if (generationValues.getKeyExtension() != null) { certificateGenerator.addExtension(X509Extensions.KeyUsage, true, generationValues.getKeyExtension()); } //add a extended key extension if this is requested if (generationValues.getExtendedKeyExtension() != null) { certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, false, generationValues.getExtendedKeyExtension()); } // Valid before and after dates now to iValidity days in the future Date startDate = new Date(System.currentTimeMillis()); long duration = TimeUnit.DAYS.toMillis(generationValues.getKeyValidInDays()); Date endDate = new Date(startDate.getTime() + duration); certificateGenerator.setNotBefore(startDate); certificateGenerator.setNotAfter(endDate); certificateGenerator.setSubjectDN(new X509Principal(order, attributes)); certificateGenerator.setPublicKey(publicKey); certificateGenerator.setSignatureAlgorithm(generationValues.getSignatureAlgorithm()); BigInteger serialNumber = new BigInteger(Long.toString(System.currentTimeMillis() / 1000)); certificateGenerator.setSerialNumber(serialNumber); // Generate an X.509 certificate, based on the current issuer and subject X509Certificate cert = certificateGenerator.generate(privateKey, "BC"); // Return the certificate return cert; }