List of usage examples for java.security.cert X509Certificate checkValidity
public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException;
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
/** * Verifies the signature on an enveloped digital signature on a UDDI * entity, such as a business, service, tmodel or binding template. * <br><Br>/*w w w. ja v a 2s . c o m*/ * It is expected that either the public key of the signing certificate * is included within the signature keyinfo section OR that sufficient * information is provided in the signature to reference a public key * located within the Trust Store provided<br><Br> Optionally, this * function also validate the signing certificate using the options * provided to the configuration map. * * @param obj an enveloped signed JAXB object * @param OutErrorMessage a human readable error message explaining the * reason for failure * @return true if the validation passes the signature validation test, * and optionally any certificate validation or trust chain validation * @throws IllegalArgumentException for null input */ public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage) throws IllegalArgumentException { if (OutErrorMessage == null) { OutErrorMessage = new AtomicReference<String>(); OutErrorMessage.set(""); } if (obj == null) { throw new IllegalArgumentException("obj"); } try { DOMResult domResult = new DOMResult(); JAXB.marshal(obj, domResult); Document doc = ((Document) domResult.getNode()); Element docElement = doc.getDocumentElement(); //this is our signed node X509Certificate signingcert = getSigningCertificatePublicKey(docElement); if (signingcert != null) { logger.info( "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString()); if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) { signingcert.checkValidity(); } if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) { logger.info("verifying revocation status via OSCP for X509 public key " + signingcert.getSubjectDN().toString()); X500Principal issuerX500Principal = signingcert.getIssuerX500Principal(); logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by " + issuerX500Principal.getName() + ", attempting to retrieve certificate"); Security.setProperty("ocsp.enable", "false"); X509Certificate issuer = FindCertByDN(issuerX500Principal); if (issuer == null) { OutErrorMessage.set( "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. " + OutErrorMessage.get()); //throw new CertificateException("unable to locate the issuers certificate in the trust store"); } else { RevocationStatus check = OCSP.check(signingcert, issuer); logger.info("certificate " + signingcert.getSubjectDN().toString() + " revocation status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) { OutErrorMessage .set("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString() + "." + OutErrorMessage.get()); //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); } } } if (map.containsKey(CHECK_REVOCATION_STATUS_CRL) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) { logger.info("verifying revokation status via CRL for X509 public key " + signingcert.getSubjectDN().toString()); Security.setProperty("ocsp.enable", "false"); System.setProperty("com.sun.security.enableCRLDP", "true"); X509CertSelector targetConstraints = new X509CertSelector(); targetConstraints.setCertificate(signingcert); PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(true); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); try { PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; logger.info("revokation status via CRL PASSED for X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } if (map.containsKey(CHECK_TRUST_CHAIN) && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) { logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString()); try { PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(false); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; TrustAnchor ta = pkixResult.getTrustAnchor(); X509Certificate cert = ta.getTrustedCert(); logger.info( "trust chain validated X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage); if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) { //no error message and its cryptographically valid return true; } return false; } //last chance validation logger.info( "signature did not have an embedded X509 public key. reverting to user specified certificate"); //cert wasn't included in the signature, revert to some other means KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE)); URL url = Thread.currentThread().getContextClassLoader() .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); if (url == null) { try { url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL(); } catch (Exception x) { } } if (url == null) { try { url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); } catch (Exception x) { } } if (url == null) { logger.error(""); OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and" + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get()); return false; } KeyStore.PrivateKeyEntry keyEntry = null; ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()); if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray())); } else { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray())); } Certificate origCert = keyEntry.getCertificate(); if (map.containsKey(CHECK_TIMESTAMPS)) { if (origCert.getPublicKey() instanceof X509Certificate) { X509Certificate x = (X509Certificate) origCert.getPublicKey(); x.checkValidity(); } } PublicKey validatingKey = origCert.getPublicKey(); return verifySignature(docElement, validatingKey, OutErrorMessage); } catch (Exception e) { //throw new RuntimeException(e); logger.error("Error caught validating signature", e); OutErrorMessage.set(e.getMessage()); return false; } }
From source file:org.texai.x509.X509Utils.java
/** Generates a self-signed certificate to use as a CA root certificate. * * @param keyPair the root public/private key pair * @return a self-signed CA root certificate * * @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 *///from ww w .j a v a 2 s . com protected static X509Certificate generateRootX509Certificate(final KeyPair keyPair) throws CertificateEncodingException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, IOException { //Preconditions assert keyPair != null : "keyPair must not be null"; final UUID rootUUID = UUID.randomUUID(); // provide items to X500Principal in reverse order final X500Principal rootX500Principal = new X500Principal( "UID=" + rootUUID + ", O=Texai Certification Authority, CN=texai.org"); final X500Name subject = new X500Name(rootX500Principal.getName()); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder( new X500Name(rootX500Principal.getName()), // issuer, getNextSerialNumber(), // serial new Date(System.currentTimeMillis() - 10000L), // notBefore, new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter, subject, new SubjectPublicKeyInfo(ASN1Sequence.getInstance(keyPair.getPublic().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 subject key identifier x509v3CertificateBuilder.addExtension(Extension.subjectKeyIdentifier, false, // isCritical jcaX509ExtensionUtils.createSubjectKeyIdentifier(keyPair.getPublic())); // add basic constraints x509v3CertificateBuilder.addExtension(Extension.basicConstraints, true, // isCritical new BasicConstraints(true)); // is a CA certificate with an unlimited certification path length final KeyUsage keyUsage = new KeyUsage( // 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); // add key usage x509v3CertificateBuilder.addExtension(Extension.keyUsage, true, // isCritical keyUsage); X509Certificate rootX509Certificate; try { final ContentSigner contentSigner = new JcaContentSignerBuilder(DIGITAL_SIGNATURE_ALGORITHM) .setProvider(BOUNCY_CASTLE_PROVIDER).build(keyPair.getPrivate()); final X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner); final JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter(); rootX509Certificate = jcaX509CertificateConverter.getCertificate(x509CertificateHolder); } catch (CertificateException | OperatorCreationException ex) { throw new TexaiException(ex); } //Postconditions try { rootX509Certificate.checkValidity(); rootX509Certificate.verify(keyPair.getPublic()); return rootX509Certificate; } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException | CertificateException ex) { throw new TexaiException(ex); } }
From source file:org.texai.x509.X509Utils.java
/** Generates an intermediate CA certificate, that is to be used to sign end-use certificates. * * @param myPublicKey the public key for this certificate * @param issuerPrivateKey the issuer's private key * @param issuerCertificate the issuer's certificate, which is either the root CA certificate or another intermediate * CA certificate/*from w w w. j a v a 2s.c o m*/ * @param pathLengthConstraint the maximum number of CA certificates that may follow this certificate in a certification * path. (Note: One end-entity certificate will follow the final CA certificate in the path. The last certificate in a path * is considered an end-entity certificate, whether the subject of the certificate is a CA or not.) * @return an intermediate CA 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 generateIntermediateX509Certificate(final PublicKey myPublicKey, final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, int pathLengthConstraint) 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"; //final X500Name issuer = new X500Name(issuerCertificate.getSubjectX500Principal().getName()); final X500Name issuer = new X500Name( StringUtils.reverseCommaDelimitedString(issuerCertificate.getSubjectX500Principal().getName())); final UUID intermediateUUID = UUID.randomUUID(); // provide items to X500Principal in reverse order final X500Principal x500Principal = new X500Principal( "UID=" + intermediateUUID + ", DC=IntermediateCertificate, CN=texai.org"); final X500Name subject = new X500Name(x500Principal.getName()); SubjectPublicKeyInfo publicKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(myPublicKey.getEncoded())); final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuer, getNextSerialNumber(), // serial new Date(System.currentTimeMillis() - 10000L), // notBefore, new Date(System.currentTimeMillis() + VALIDITY_PERIOD), // notAfter, subject, 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(pathLengthConstraint)); // is a CA certificate with specified certification path length // add key usage final KeyUsage keyUsage = new KeyUsage( // 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); 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); } return x509Certificate; }
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.//from w w w. j a v a 2 s .co m * * @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:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * ? ? ? ?? ?_1 //from w w w .j a va2 s .c om * ? ? ? * * @param signers * @param clientCerts * @return * @throws CertStoreException */ private boolean checkNucOneCertificateType(SignerInformationStore signers, CertStore clientCerts) throws CertStoreException { Iterator it = signers.getSigners().iterator(); boolean result = false; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertSelector signerConstraints = signer.getSID(); Collection certCollection = clientCerts.getCertificates(signerConstraints); Iterator certIt = certCollection.iterator(); if (certCollection.size() == 0) { throw new RuntimeException( " ? ? ."); } while (certIt.hasNext()) { X509Certificate userCert = (X509Certificate) certIt.next(); X509Certificate certForCheck = null; boolean isMyVersion = false; try { if (TypeOfRespondent.FIRM.equals(typeOfRespondent)) { X509Certificate certNuc1Gost = (X509Certificate) createCerificate_nuc1_gost(); userCert.verify(certNuc1Gost.getPublicKey(), providerName); certForCheck = certNuc1Gost; } else { X509Certificate certNuc1Rsa = (X509Certificate) createCerificate_nuc1_rsa(); userCert.verify(certNuc1Rsa.getPublicKey(), providerName); certForCheck = certNuc1Rsa; } isMyVersion = true; } catch (Exception ex) { // ? ? ? ? 1 result = false; } if (isMyVersion) { // ? ? ? ?? ?_1 try { certForCheck.checkValidity(); // ? ? ? } catch (CertificateExpiredException ex) { throw new RuntimeException( " ? ? ? 1.0, ? ? 1.0 ? ??"); } catch (CertificateNotYetValidException ex) { throw new RuntimeException( " ? ? ? 1.0, ? ? 1.0 ?."); } try { if (isNotRevokedCertNucOne(userCert)) { // ? ? ? return true; } else { throw new RuntimeException( "C ? ."); } } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } } } return result; }
From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java
/** * ? ? ? ?? ?_2 //from ww w .j av a2s .com * ? ? ? * * @param signers * @param clientCerts * @return * @throws CertStoreException */ private boolean checkNucTwoCertificateType(SignerInformationStore signers, CertStore clientCerts) throws CertStoreException { Iterator it = signers.getSigners().iterator(); boolean result = false; while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertSelector signerConstraints = signer.getSID(); Collection certCollection = clientCerts.getCertificates(signerConstraints); Iterator certIt = certCollection.iterator(); //System.out.println( ); if (certCollection.size() == 0) { throw new RuntimeException( " ? ? ."); } while (certIt.hasNext()) { X509Certificate userCert = (X509Certificate) certIt.next(); boolean isMyVersion = false; X509Certificate certForCheck = null; try { if (TypeOfRespondent.FIRM.equals(typeOfRespondent)) { X509Certificate certNuc2Gost = (X509Certificate) createCerificate_nuc2_gost(); X509Certificate certKucGost = (X509Certificate) createCerificate_kuc_gost(); userCert.verify(certNuc2Gost.getPublicKey(), providerName); certNuc2Gost.verify(certKucGost.getPublicKey(), providerName); certForCheck = certNuc2Gost; } else { X509Certificate certNuc2Rsa = (X509Certificate) createCerificate_nuc2_rsa(); X509Certificate certKucRsa = (X509Certificate) createCerificate_kuc_rsa(); userCert.verify(certNuc2Rsa.getPublicKey(), providerName); certNuc2Rsa.verify(certKucRsa.getPublicKey(), providerName); certForCheck = certNuc2Rsa; } isMyVersion = true; } catch (Exception ex) { result = false; } if (isMyVersion) { // ? ? ? ?? ?_1 try { certForCheck.checkValidity(); } catch (CertificateExpiredException ex) { throw new RuntimeException( " ? ? ? 2.0, ? ? 2.0 ? ??"); } catch (CertificateNotYetValidException ex) { throw new RuntimeException( " ? ? ? 2.0, ? ? 2.0 ?."); } try { if (isNotRevokedCertNucTwo(userCert)) { result = true; return true; } else { throw new RuntimeException( "C ? ."); } } catch (Exception ex) { throw new RuntimeException(ex.getMessage()); } } } } return result; }
From source file:com.idevity.card.read.ShowCHUID.java
/** * Method onCreateView.//from w w w.ja v a2 s. c o m * * @param inflater * LayoutInflater * @param container * ViewGroup * @param savedInstanceState * Bundle * @return View */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Globals g = Globals.getInstance(); String issuer = new String(); String subject = new String(); String validfrom = new String(); String validto = new String(); boolean certvalid = true; boolean sigvalid = false; CMSSignedDataObject chuidSig = null; X509Certificate pcs = null; View chuidLayout = inflater.inflate(R.layout.activity_show_chuid, container, false); // get card data byte[] _data = g.getCard(); CardData80073 carddata = new CardData80073(_data); // get chuid PIVCardHolderUniqueID chuid = null; PIVDataTempl chuidInDataTempl = carddata.getPIVCardHolderUniqueID(); if (chuidInDataTempl != null) { byte[] chuidData = chuidInDataTempl.getData(); if (chuidData == null) { chuidData = chuidInDataTempl.getEncoded(); } chuid = new PIVCardHolderUniqueID(chuidData); } if (chuid != null) { try { // get chuid signature object chuidSig = new CMSSignedDataObject(chuid.getSignatureBytes(), chuid.getSignatureDataBytes()); chuidSig.setProviderName("OpenSSLFIPSProvider"); // validate the signature, don't do PDVAL sigvalid = chuidSig.verifySignature(false); } catch (SignatureException e) { Log.e(TAG, "Error: " + e.getMessage()); } // get x509 cert if (chuidSig != null) { pcs = chuidSig.getSigner(); } // get values from x509 if (pcs != null) { issuer = pcs.getIssuerDN().getName(); subject = pcs.getSubjectDN().getName(); validfrom = pcs.getNotBefore().toString(); validto = pcs.getNotAfter().toString(); } } ImageView sigthumbs = (ImageView) chuidLayout.findViewById(R.id.chuidindicator1); TextView sigtext = (TextView) chuidLayout.findViewById(R.id.chuid1); if (sigvalid) { sigthumbs.setImageResource(R.drawable.cert_good); } else { sigthumbs.setImageResource(R.drawable.cert_bad); sigtext.setTextColor(getResources().getColor(R.color.idredmain)); } /* * Note to self. I am not thrilled how Java almost forces you to assume * a certificate if valid unless an exception is thrown! */ TextView vfText = (TextView) chuidLayout.findViewById(R.id.chuid4); TextView vtText = (TextView) chuidLayout.findViewById(R.id.chuid5); try { if (pcs != null) { pcs.checkValidity(); } } catch (CertificateNotYetValidException e) { certvalid = false; vfText.setTextColor(getResources().getColor(R.color.idredmain)); if (debug) { Log.d(TAG, "Error: Authentication Certificate Not Vaid Yet!"); } } catch (CertificateExpiredException e) { certvalid = false; vtText.setTextColor(getResources().getColor(R.color.idredmain)); if (debug) { Log.d(TAG, "Error: Card Authentication Certificate Expired!"); } } ImageView certthumbs = (ImageView) chuidLayout.findViewById(R.id.chuidindicator2); TextView certtext = (TextView) chuidLayout.findViewById(R.id.chuid2); if (certvalid && pcs != null) { certthumbs.setImageResource(R.drawable.cert_good); } else { certthumbs.setImageResource(R.drawable.cert_bad); certtext.setTextColor(getResources().getColor(R.color.idredmain)); } // setting all values in activity TextView editChuidSubject = (TextView) chuidLayout.findViewById(R.id.chuid_subject); editChuidSubject.setText(subject); TextView editValidFrom = (TextView) chuidLayout.findViewById(R.id.chuid_date); editValidFrom.setText(validfrom); TextView editValidTo = (TextView) chuidLayout.findViewById(R.id.chuid_expiry); editValidTo.setText(validto); TextView editIssuer = (TextView) chuidLayout.findViewById(R.id.chuid_issuer); editIssuer.setText(issuer); return chuidLayout; }
From source file:org.apache.hadoop.hdfsproxy.ProxyFilter.java
/** {@inheritDoc} */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest rqst = (HttpServletRequest) request; HttpServletResponse rsp = (HttpServletResponse) response; if (LOG.isDebugEnabled()) { StringBuilder b = new StringBuilder("Request from ").append(rqst.getRemoteHost()).append("/") .append(rqst.getRemoteAddr()).append(":").append(rqst.getRemotePort()); @SuppressWarnings("unchecked") Enumeration<String> e = rqst.getAttributeNames(); for (; e.hasMoreElements();) { String attribute = e.nextElement(); b.append("\n " + attribute + " => " + rqst.getAttribute(attribute)); }/*from ww w . j a v a 2s .c om*/ X509Certificate[] userCerts = (X509Certificate[]) rqst .getAttribute("javax.servlet.request.X509Certificate"); if (userCerts != null) for (X509Certificate cert : userCerts) b.append("\n Client certificate Subject Name is " + cert.getSubjectX500Principal().getName()); b.append("\n The Scheme is " + rqst.getScheme()); b.append("\n The Auth Type is " + rqst.getAuthType()); b.append("\n The Path Info is " + rqst.getPathInfo()); b.append("\n The Translated Path Info is " + rqst.getPathTranslated()); b.append("\n The Context Path is " + rqst.getContextPath()); b.append("\n The Query String is " + rqst.getQueryString()); b.append("\n The Remote User is " + rqst.getRemoteUser()); b.append("\n The User Principal is " + rqst.getUserPrincipal()); b.append("\n The Request URI is " + rqst.getRequestURI()); b.append("\n The Request URL is " + rqst.getRequestURL()); b.append("\n The Servlet Path is " + rqst.getServletPath()); LOG.debug(b.toString()); } boolean unitTest = false; if (rqst.getScheme().equalsIgnoreCase("http") && rqst.getParameter("UnitTest") != null) unitTest = true; if (rqst.getScheme().equalsIgnoreCase("https") || unitTest) { boolean isAuthorized = false; X509Certificate[] certs = (X509Certificate[]) rqst .getAttribute("javax.servlet.request.X509Certificate"); if (unitTest) { try { LOG.debug("==> Entering https unit test"); String SslPath = rqst.getParameter("SslPath"); InputStream inStream = new FileInputStream(SslPath); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream); inStream.close(); certs = new X509Certificate[] { cert }; } catch (Exception e) { // do nothing here } } if (certs == null || certs.length == 0) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "No client SSL certificate received"); LOG.info("No Client SSL certificate received"); return; } for (X509Certificate cert : certs) { try { cert.checkValidity(); } catch (CertificateExpiredException e) { LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " expired"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate expired"); return; } catch (CertificateNotYetValidException e) { LOG.info("Received cert for " + cert.getSubjectX500Principal().getName() + " is not yet valid"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Certificate is not yet valid"); return; } } String[] tokens = certs[0].getSubjectX500Principal().getName().split("\\s*,\\s*"); String userID = null; for (String s : tokens) { if (s.startsWith("CN=")) { userID = s; break; } } if (userID == null || userID.length() < 4) { LOG.info("Can't retrieve user ID from SSL certificate"); rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Can't retrieve user ID from SSL certificate"); return; } userID = userID.substring(3); String servletPath = rqst.getServletPath(); if (unitTest) { servletPath = rqst.getParameter("TestSevletPathInfo"); LOG.info("this is for unit test purpose only"); } if (HFTP_PATTERN.matcher(servletPath).matches()) { // request is an HSFTP request if (FILEPATH_PATTERN.matcher(servletPath).matches()) { // file path as part of the URL isAuthorized = checkPath(userID, certs[0], rqst.getPathInfo() != null ? rqst.getPathInfo() : "/"); } else { // file path is stored in "filename" parameter isAuthorized = checkPath(userID, certs[0], rqst.getParameter("filename")); } } else if (RELOAD_PATTERN.matcher(servletPath).matches() && checkUser("Admin", certs[0])) { Configuration conf = new Configuration(false); conf.addResource("hdfsproxy-default.xml"); Map<String, Set<Path>> permsMap = getPermMap(conf); Map<String, Set<BigInteger>> certsMap = getCertsMap(conf); if (permsMap == null || certsMap == null) { LOG.warn("Permission files reloading failed"); rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Permission files reloading failed"); return; } ProxyFilter.permsMap = permsMap; ProxyFilter.certsMap = certsMap; LOG.info("User permissions and user certs files reloaded"); rsp.setStatus(HttpServletResponse.SC_OK); return; } if (!isAuthorized) { rsp.sendError(HttpServletResponse.SC_FORBIDDEN, "Unauthorized access"); return; } // request is authorized, set ugi for servlets UserGroupInformation ugi = UserGroupInformation.createRemoteUser(userID); rqst.setAttribute("authorized.ugi", ugi); rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", userID); } else if (rqst.getScheme().equalsIgnoreCase("http")) { // http request, set ugi for servlets, only for testing purposes String ugi = rqst.getParameter("ugi"); if (ugi != null) { rqst.setAttribute("authorized.ugi", UserGroupInformation.createRemoteUser(ugi)); rqst.setAttribute("org.apache.hadoop.hdfsproxy.authorized.userID", ugi.split(",")[0]); } } chain.doFilter(request, response); }
From source file:org.cesecore.util.CertTools.java
/** * Checks if a certificate is valid.//from www. j av a 2 s.c o m * Does also print a WARN if the certificate is about to expire. * * @param signerCert the certificate to be tested * @return true if the certificate is valid */ public static boolean isCertificateValid(final X509Certificate signerCert) { try { signerCert.checkValidity(); } catch (CertificateExpiredException e) { log.error(intres.getLocalizedMessage("ocsp.errorcerthasexpired", signerCert.getSerialNumber(), signerCert.getIssuerDN())); return false; } catch (CertificateNotYetValidException e) { log.error(intres.getLocalizedMessage("ocsp.errornotyetvalid", signerCert.getSerialNumber(), signerCert.getIssuerDN())); return false; } final long warnBeforeExpirationTime = OcspConfiguration.getWarningBeforeExpirationTime(); if (warnBeforeExpirationTime < 1) { return true; } final Date warnDate = new Date(new Date().getTime() + warnBeforeExpirationTime); try { signerCert.checkValidity(warnDate); } catch (CertificateExpiredException e) { log.warn(intres.getLocalizedMessage("ocsp.warncertwillexpire", signerCert.getSerialNumber(), signerCert.getIssuerDN(), signerCert.getNotAfter())); } catch (CertificateNotYetValidException e) { throw new Error("This should never happen.", e); } if (log.isDebugEnabled()) { log.debug("Time for \"certificate will soon expire\" not yet reached. You will be warned after: " + new Date(signerCert.getNotAfter().getTime() - warnBeforeExpirationTime)); } return true; }
From source file:com.idevity.card.read.ShowCert.java
/** * Method onCreateView./* w w w .j ava2 s . c o m*/ * * @param inflater * LayoutInflater * @param container * ViewGroup * @param savedInstanceState * Bundle * @return View */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Globals g = Globals.getInstance(); byte[] _data = g.getCard(); CardData80073 carddata = new CardData80073(_data); X509Certificate cardAuth = null; String issuer = new String(); String subject = new String(); String validfrom = new String(); String validto = new String(); try { PIVCertificate pca = null; PIVDataTempl dataTempl = carddata.getCardAuthCertificate(); if (dataTempl != null) { byte[] data = dataTempl.getData(); if (data == null) { data = dataTempl.getEncoded(); } pca = new PIVCertificate(data); } cardAuth = pca.getCertificate(); } catch (NullPointerException e) { if (debug) { Log.d(TAG, "Error: No Card Authentication Certificate Received"); } } catch (Throwable e) { Log.e(TAG, "Error: " + e.getMessage()); } if (cardAuth != null) { /* * The default implementation does not decode the * DN in a very human friendly form. The following * Map and Format variables will help to better decode * the X500Principal object to a String value. */ HashMap<String, String> oidMap = new HashMap<String, String>(); oidMap.put("2.5.4.5", "SERIALNUMBER"); String dnFormat = "RFC1779"; /* * Get the values from the certificate */ issuer = cardAuth.getIssuerX500Principal().getName(dnFormat, oidMap); subject = cardAuth.getSubjectX500Principal().getName(dnFormat, oidMap); validfrom = cardAuth.getNotBefore().toString(); validto = cardAuth.getNotAfter().toString(); /* * Populate the UI */ View certLayout = inflater.inflate(R.layout.activity_show_cert, container, false); ImageView valPeriodIndicator = (ImageView) certLayout.findViewById(R.id.cert_ind_vp); ImageView popIndicator = (ImageView) certLayout.findViewById(R.id.cert_ind_pop); TextView valPeriodLabel = (TextView) certLayout.findViewById(R.id.cert_vp_label); TextView popLabel = (TextView) certLayout.findViewById(R.id.cert_pop_label); TextView vfText = (TextView) certLayout.findViewById(R.id.cert_nb_label); TextView vtText = (TextView) certLayout.findViewById(R.id.cert_na_label); /* * Assume the cert is good unless an exception * is thrown below. */ valPeriodIndicator.setImageResource(R.drawable.cert_good); /* * Note to self. I am not thrilled how Java almost forces you * to assume a certificate if valid unless an exception is thrown! */ try { cardAuth.checkValidity(); } catch (CertificateNotYetValidException e) { valPeriodIndicator.setImageResource(R.drawable.cert_bad); valPeriodLabel.setTextColor(getResources().getColor(R.color.idredmain)); vfText.setTextColor(getResources().getColor(R.color.idredmain)); if (debug) { Log.d(TAG, "Error: Authentication Certificate Not Valid Yet!"); } } catch (CertificateExpiredException e) { valPeriodIndicator.setImageResource(R.drawable.cert_bad); valPeriodLabel.setTextColor(getResources().getColor(R.color.idredmain)); vtText.setTextColor(getResources().getColor(R.color.idredmain)); if (debug) { Log.d(TAG, "Error: Card Authentication Certificate Expired!"); } } CAKChallenge popVerify = new CAKChallenge(cardAuth, carddata.getCAKPoPNonce(), carddata.getCAKPoPSig()); try { if (popVerify.validatePOP()) { popIndicator.setImageResource(R.drawable.cert_good); if (debug) { Log.d(TAG, "Proof of Possession Verified!"); } } else { popIndicator.setImageResource(R.drawable.cert_bad); popLabel.setTextColor(getResources().getColor(R.color.idredmain)); if (debug) { Log.d(TAG, "Proof of Possession Failed!"); } } } catch (SignatureException e) { popIndicator.setImageResource(R.drawable.cert_bad); popLabel.setTextColor(getResources().getColor(R.color.idredmain)); if (debug) { Log.d(TAG, "Problem with Proof of Possession: " + e.getMessage()); } } TextView editCertSubject = (TextView) certLayout.findViewById(R.id.cert_sub_dn); editCertSubject.setText(subject); TextView editValidFrom = (TextView) certLayout.findViewById(R.id.cert_nb_date); editValidFrom.setText(validfrom); TextView editValidTo = (TextView) certLayout.findViewById(R.id.cert_na_date); editValidTo.setText(validto); TextView editIssuer = (TextView) certLayout.findViewById(R.id.cert_iss_dn); editIssuer.setText(issuer); return certLayout; } else { View certLayout = inflater.inflate(R.layout.activity_no_cert, container, false); return certLayout; } }