List of usage examples for java.security.cert X509Certificate getKeyUsage
public abstract boolean[] getKeyUsage();
From source file:org.texai.x509.X509Utils.java
/** Generates a signed end-use certificate that cannot be used to sign other certificates, but can be used for authentication * and for message signing.//w w w .j a va2s. c om * * @param myPublicKey the public key for this certificate * @param issuerPrivateKey the issuer's private key * @param issuerCertificate the issuer's certificate * @param uid the subject UID * @param domainComponent the domain component, e.g. TexaiLauncher or NodeRuntime * @return a signed end-use certificate * * @throws CertificateParsingException when the certificate cannot be parsed * @throws CertificateEncodingException when the certificate cannot be encoded * @throws NoSuchProviderException when an invalid provider is given * @throws NoSuchAlgorithmException when an invalid algorithm is given * @throws SignatureException when the an invalid signature is present * @throws InvalidKeyException when the given key is invalid * @throws IOException if an input/output error occurs while processing the serial number file */ public static X509Certificate generateX509Certificate(final PublicKey myPublicKey, final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid, final String domainComponent) throws CertificateParsingException, CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { //Preconditions assert myPublicKey != null : "myPublicKey must not be null"; assert issuerPrivateKey != null : "issuerPrivateKey must not be null"; assert issuerCertificate != null : "issuerCertificate must not be null"; assert uid != null : "uid must not be null"; final String x500PrincipalString; // provide items to X500Principal in reverse order if (domainComponent == null || domainComponent.isEmpty()) { x500PrincipalString = "UID=" + uid + ", CN=texai.org"; } else { x500PrincipalString = "UID=" + uid + ", DC=" + domainComponent + " ,CN=texai.org"; } final X500Principal x500Principal = new X500Principal(x500PrincipalString); LOGGER.info("issuer: " + issuerCertificate.getIssuerX500Principal().getName()); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( new X500Name(StringUtils .reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())), // issuer, getNextSerialNumber(), // serial new Date(System.currentTimeMillis() - 10000L), // notBefore, new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter, new X500Name(x500Principal.getName()), // subject, new SubjectPublicKeyInfo(ASN1Sequence.getInstance(myPublicKey.getEncoded()))); // publicKeyInfo // see http://www.ietf.org/rfc/rfc3280.txt // see http://stackoverflow.com/questions/20175447/creating-certificates-for-ssl-communication final JcaX509ExtensionUtils jcaX509ExtensionUtils = new JcaX509ExtensionUtils(); // Add authority key identifier x509v3CertificateBuilder.addExtension(Extension.authorityKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createAuthorityKeyIdentifier(issuerCertificate)); // Add subject key identifier x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createSubjectKeyIdentifier(myPublicKey)); // add basic constraints x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical new BasicConstraints(false)); // is not a CA certificate // add key usage final KeyUsage keyUsage = new KeyUsage( // the digitalSignature usage indicates that the subject public key may be used with a digital signature // mechanism to support security services other than non-repudiation, certificate signing, or revocation // information signing KeyUsage.digitalSignature | // the nonRepudiation usage indicates that the subject public key may be used to verify digital signatures // used to provide a non-repudiation service which protects against the signing entity falsely denying some // action, excluding certificate or CRL signing KeyUsage.nonRepudiation | // the keyEncipherment usage indicates that the subject public key may be used for key transport, e.g. the // exchange of efficient symmetric keys in SSL KeyUsage.keyEncipherment | // the dataEncipherment usage indicates that the subject public key may be used for enciphering user data, // other than cryptographic keys KeyUsage.dataEncipherment | // the keyAgreement usage indicates that the subject public key may be used for key agreement, e.g. when a // Diffie-Hellman key is to be used for key management KeyUsage.keyAgreement | // the keyCertSign bit indicates that the subject public key may be used for verifying a signature on // certificates KeyUsage.keyCertSign | // the cRLSign indicates that the subject public key may be used for verifying a signature on revocation // information KeyUsage.cRLSign | // see http://www.docjar.com/html/api/sun/security/validator/EndEntityChecker.java.html - bit 0 needs to set for SSL // client authorization KeyUsage.encipherOnly); x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical keyUsage); X509Certificate x509Certificate; try { final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM) .setProvider(BOUNCY_CASTLE_PROVIDER).build(issuerPrivateKey); final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); x509Certificate = makeCanonicalX509Certificate( jcaX509CertificateConverter.getCertificate(x509CertificateHolder)); } catch (CertificateException | OperatorCreationException ex) { throw new TexaiException(ex); } //Postconditions try { x509Certificate.checkValidity(); x509Certificate.verify(issuerCertificate.getPublicKey()); } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | SignatureException ex) { throw new TexaiException(ex); } assert x509Certificate.getKeyUsage()[0] : "must have digital signature key usage"; return x509Certificate; }
From source file:org.texai.x509.X509Utils.java
/** Returns whether the given certificate has the given key usage bit set, i.e. digitalSignature usage. * * digitalSignature (0)/*from w ww .j a v a2 s . c o m*/ * nonRepudiation (1) * keyEncipherment (2) * dataEncipherment (3) * keyAgreement (4) * keyCertSign (5) * cRLSign (6) * encipherOnly (7) * decipherOnly (8) * * @param x509Certificate the given certificate * @param keyUsageBitMask the given key usage bit, i.e. KeyUsage.digitalSignature * @return whether the given certificate has the given key usage bit set */ public static boolean hasKeyUsage(final X509Certificate x509Certificate, final int keyUsageBitMask) { //Preconditions assert x509Certificate != null : "x509Certificate must not be null"; final boolean[] keyUsage = x509Certificate.getKeyUsage(); int certificateKeyUsageBitmask = 0; final int keyUsage_len = keyUsage.length - 1; // ignore pad bit for (int i = 0; i < keyUsage_len; i++) { if (keyUsage[i]) { certificateKeyUsageBitmask += Math.pow(2, (keyUsage_len - i - 1)); } } return (certificateKeyUsageBitmask & keyUsageBitMask) != 0; }
From source file:org.warlock.itk.distributionenvelope.Payload.java
/** * Add an X.509v3 certificate for a recipient. * /*from w ww. j av a 2s . c o m*/ * @param r */ public void addReaderCertificate(X509Certificate r) throws Exception { if (r == null) { throw new Exception("Null certificate"); } // Date range check against current date and time // r.checkValidity(); // Allowed use check. Need to check that the certificate is issued // for usages that include "data encipherment". By default, require a // "key usage" extension unless the compile-time "allowNonUsageCertificates" // has been set. // // This is here where other certificate checking steps are handled elsewhere, // because the "data encipherment" usage is a specific usage type for the // content encryption. // boolean[] usage = r.getKeyUsage(); if (usage != null) { if (!usage[DATAENCIPHERMENTUSAGE]) { throw new Exception( "Certificate " + r.getSubjectDN().getName() + " not valid for data encipherment"); } } else { if (!allowNonUsageCertificates) { throw new Exception("Certificate " + r.getSubjectDN().getName() + " has no key usage extension."); } } // This is included but commented out specifically to make the point that // section 4.2.1.3, "Key Usage" in RFC2459 says that the "key encipherment" // usage is for key management, so it isn't relevant here. // // if (!usage[KEYENCIPHERMENTUSAGE]) { // throw new Exception("Certificate " + r.getSubjectDN().getName() + " not valid for key encipherment"); // } encrypted = true; readerCerts.add(r); }
From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java
private boolean validateCRL(X509CRL x509crl, X509Certificate certificate, X509Certificate issuerCertificate, Date validationDate) {/*from w w w. j av a2 s.co m*/ Principal subjectX500Principal = certificate.getSubjectX500Principal(); if (x509crl == null) { log.error("No CRL found for certificate '" + subjectX500Principal + "'"); return false; } if (log.isTraceEnabled()) { try { log.trace("CRL number: " + getCrlNumber(x509crl)); } catch (IOException ex) { log.error("Failed to get CRL number", ex); } } if (!x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) { log.error("The CRL must be signed by the issuer '" + subjectX500Principal + "' but instead is signed by '" + x509crl.getIssuerX500Principal() + "'"); return false; } try { x509crl.verify(issuerCertificate.getPublicKey()); } catch (Exception ex) { log.error("The signature verification for CRL cannot be performed", ex); return false; } log.debug("CRL validationDate: " + validationDate); log.debug("CRL nextUpdate: " + x509crl.getThisUpdate()); log.debug("CRL thisUpdate: " + x509crl.getNextUpdate()); if (x509crl.getNextUpdate() != null && validationDate.after(x509crl.getNextUpdate())) { log.error("CRL is too old"); return false; } if (issuerCertificate.getKeyUsage() == null) { log.error("There is no KeyUsage extension for certificate '" + subjectX500Principal + "'"); return false; } if (!issuerCertificate.getKeyUsage()[6]) { log.error("cRLSign bit is not set for CRL certificate'" + subjectX500Principal + "'"); return false; } return true; }
From source file:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java
@Test public void testSign() throws Exception { // setup//w ww .ja v a 2 s .com KeyPair caKeyPair = generateKeyPair(); KeyPair entityKeyPair = generateKeyPair(); X500Principal subject = new X500Principal("CN=Test"); PublicKey pubKey = entityKeyPair.getPublic(); X500Principal issuer = new X500Principal("CN=CA"); PublicKey caPubKey = caKeyPair.getPublic(); PrivateKey caKey = caKeyPair.getPrivate(); Date begin = new Date(); Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30); BigInteger serialNo = BigInteger.valueOf(1234); JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils(); // operate X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends, serialNo, null); // verify assertNotNull(resultCert); LOG.debug("result certificate: " + resultCert); resultCert.verify(caPubKey); assertEquals(subject, resultCert.getSubjectX500Principal()); assertEquals(issuer, resultCert.getIssuerX500Principal()); assertEquals(serialNo, resultCert.getSerialNumber()); assertEquals(pubKey, resultCert.getPublicKey()); LOG.debug("expected begin: " + begin.getTime()); LOG.debug("actual begin: " + resultCert.getNotBefore().getTime()); /* * BouncyCastle drops the milliseconds. */ assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000); assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000); byte[] subjectKeyIdentifierExtValue = resultCert .getExtensionValue(X509Extension.subjectKeyIdentifier.getId()); assertNotNull(subjectKeyIdentifierExtValue); ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils .parseExtensionValue(subjectKeyIdentifierExtValue); ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive(); assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded()); byte[] authorityKeyIdentifierExtValue = resultCert .getExtensionValue(X509Extension.authorityKeyIdentifier.getId()); ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils .parseExtensionValue(authorityKeyIdentifierExtValue); ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive(); assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded()); assertEquals(-1, resultCert.getBasicConstraints()); byte[] netscapeCertTypeExtValue = resultCert .getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId()); assertNotNull(netscapeCertTypeExtValue); DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil .fromExtensionValue(netscapeCertTypeExtValue); NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt); assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient); assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer); assertTrue(resultCert.getKeyUsage()[0]); assertTrue(resultCert.getKeyUsage()[2]); byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId()); assertNotNull(extendedKeyUsageExtValue); ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage .getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue)); assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth)); assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth)); }
From source file:view.CertificatePropertiesDialog.java
private void setCertificateProperties(X509Certificate x509Certificate) { selectedCertificate = x509Certificate; jTextField1.setText(null);//from w w w .j a va 2s .co m jTextField2.setText(null); jTextField3.setText(null); jTextField4.setText(null); jTextField5.setText(null); jTextField6.setText(null); jTextField7.setText(null); jTextField9.setText(null); jTextField10.setText(null); jTextField11.setText(null); jTextField12.setText(null); X500Name x500subject = null; X500Name x500issuer = null; try { x500subject = new JcaX509CertificateHolder(x509Certificate).getSubject(); x500issuer = new JcaX509CertificateHolder(x509Certificate).getIssuer(); } catch (CertificateEncodingException ex) { controller.Logger.getLogger().addEntry(ex); } RDN subjectCN = null; if (x500subject.getRDNs(BCStyle.CN).length > 0) { subjectCN = x500subject.getRDNs(BCStyle.CN)[0]; } RDN subjectOU1 = null; if (x500subject.getRDNs(BCStyle.OU).length >= 1) { subjectOU1 = x500subject.getRDNs(BCStyle.OU)[0]; jTextField2.setText(IETFUtils.valueToString(subjectOU1.getFirst().getValue())); jTextField2.setCaretPosition(0); } RDN subjectOU2 = null; if (x500subject.getRDNs(BCStyle.OU).length >= 2) { subjectOU2 = x500subject.getRDNs(BCStyle.OU)[1]; jTextField3.setText(IETFUtils.valueToString(subjectOU2.getFirst().getValue())); jTextField3.setCaretPosition(0); } RDN subjectO = null; if (x500subject.getRDNs(BCStyle.O).length > 0) { subjectO = x500subject.getRDNs(BCStyle.O)[0]; } RDN subjectC = null; if (x500subject.getRDNs(BCStyle.C).length > 0) { subjectC = x500subject.getRDNs(BCStyle.C)[0]; } if (!x500issuer.equals(x500subject)) { RDN issuerCN = x500issuer.getRDNs(BCStyle.CN)[0]; if (1 == x500issuer.getRDNs(BCStyle.OU).length) { RDN issuerOU1 = x500issuer.getRDNs(BCStyle.OU)[0]; jTextField7.setText(IETFUtils.valueToString(issuerOU1.getFirst().getValue())); jTextField7.setCaretPosition(0); } RDN issuerO = x500issuer.getRDNs(BCStyle.O)[0]; RDN issuerC = x500issuer.getRDNs(BCStyle.C)[0]; jTextField6.setText(IETFUtils.valueToString(issuerCN.getFirst().getValue())); jTextField6.setCaretPosition(0); jTextField9.setText(IETFUtils.valueToString(issuerO.getFirst().getValue())); jTextField9.setCaretPosition(0); jTextField10.setText(IETFUtils.valueToString(issuerC.getFirst().getValue())); jTextField10.setCaretPosition(0); } Date since = x509Certificate.getNotBefore(); Date until = x509Certificate.getNotAfter(); jTextField1.setText( WordUtils.capitalize(IETFUtils.valueToString(subjectCN.getFirst().getValue()).toLowerCase())); jTextField1.setCaretPosition(0); if (subjectO != null) { jTextField4.setText(IETFUtils.valueToString(subjectO.getFirst().getValue())); } jTextField4.setCaretPosition(0); if (subjectC != null) { jTextField5.setText(IETFUtils.valueToString(subjectC.getFirst().getValue())); } jTextField5.setCaretPosition(0); jTextField11.setText(since.toLocaleString()); jTextField11.setCaretPosition(0); jTextField12.setText(until.toLocaleString()); jTextField12.setCaretPosition(0); boolean usage[] = x509Certificate.getKeyUsage(); if (null != usage) { boolean digitalSignature = usage[0]; boolean nonRepudiation = usage[1]; boolean keyEncipherment = usage[2]; boolean dataEncipherment = usage[3]; boolean keyAgreement = usage[4]; boolean keyCertSign = usage[5]; boolean cRLSign = usage[6]; boolean encipherOnly = usage[7]; boolean decipherOnly = usage[8]; String uso = (digitalSignature ? Bundle.getBundle().getString("digitalSignature") + ", " : "") + (nonRepudiation ? Bundle.getBundle().getString("nonRepudiation") + ", " : "") + (keyEncipherment ? Bundle.getBundle().getString("keyEncipherment") + ", " : "") + (dataEncipherment ? Bundle.getBundle().getString("dataEncipherment") + ", " : "") + (keyAgreement ? Bundle.getBundle().getString("keyAgreement") + ", " : "") + (keyCertSign ? Bundle.getBundle().getString("keyCertSign") + ", " : "") + (cRLSign ? Bundle.getBundle().getString("cRLSign") + ", " : "") + (encipherOnly ? Bundle.getBundle().getString("encipherOnly") + ", " : "") + (decipherOnly ? Bundle.getBundle().getString("decipherOnly") + ", " : ""); if (uso.length() == 0) { lblUso.setText(Bundle.getBundle().getString("label.none")); } else if (uso.endsWith(", ")) { lblUso.setText(uso.substring(0, uso.length() - 2)); } } else { lblUso.setText(Bundle.getBundle().getString("unknown")); } }