예제 #1
0
  private void parseCert() {
    try {
      FileInputStream fis = new FileInputStream("e:\\rongyifu.der");
      CertificateFactory cf = CertificateFactory.getInstance("X509");
      X509Certificate c = (X509Certificate) cf.generateCertificate(fis);

      System.out.println("Certficate for " + c.getSubjectDN().getName());
      System.out.println("Generated with " + c.getSigAlgName());
      System.out.println("== " + c.getSubjectDN().toString());
      String publicKey = Base64.encode(c.getPublicKey().getEncoded());
      System.out.println("publicKey=" + publicKey);

      //		      Map<String, String> map = parseSubjectDN(c.getSubjectDN().toString());
      //		      System.out.println("map: "+map);

      //		      String notBefore =c.getNotBefore().toString();//得到开始有效日期
      //		      String notAfter = c.getNotAfter().toString();//得到截止日期
      String serialNumber = c.getSerialNumber().toString(16); // 得到序列号
      String dn = c.getIssuerDN().getName(); // 得到发行者名
      String sigAlgName = c.getSigAlgName(); // 得到签名算法
      String algorithm = c.getPublicKey().getAlgorithm(); // 得到公钥算法

      SimpleDateFormat intSDF = new SimpleDateFormat("yyyyMMdd");
      System.out.println("notBefore=" + intSDF.format(c.getNotBefore()));
      System.out.println("notAfter=" + intSDF.format(c.getNotAfter()));
      System.out.println("serialNumber=" + serialNumber);
      System.out.println("dn=" + dn);
      System.out.println("sigAlgName=" + sigAlgName);
      System.out.println("algorithm=" + algorithm);

      fis.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
  public X509CertificateShortInfo(String alias, X509Certificate cert) {
    this.alias = alias;

    if (cert.getIssuerDN() != null) issuer = cert.getIssuerDN().getName();
    if (cert.getSubjectDN() != null) subject = cert.getSubjectDN().getName();
    algorithm = cert.getSigAlgName();
    notBeforeDatetime = cert.getNotBefore();
    notAfterDatetime = cert.getNotAfter();

    updateViewStyle();
  }
예제 #3
0
 @Test
 public void testSelfSignedCertificate() throws Exception {
   KeyStore keystore = createKeyStore();
   KeyStoreUtil.updateWithSelfSignedServerCertificate(keystore);
   X509Certificate cert = (X509Certificate) keystore.getCertificate("jolokia-agent");
   assertNotNull(cert);
   assertEquals(
       cert.getSubjectDN().getName(),
       "CN=Jolokia Agent "
           + Version.getAgentVersion()
           + ", OU=JVM, O=jolokia.org, L=Pegnitz, ST=Franconia, C=DE");
   assertEquals(cert.getSubjectDN(), cert.getIssuerDN());
 }
 public void testAutoCredentialCreation() {
   AssertionCredentialsManager cm = null;
   try {
     cm = Utils.getAssertionCredentialsManager();
     X509Certificate cert = cm.getIdPCertificate();
     assertNotNull(cert);
     assertNotNull(cm.getIdPKey());
     String expectedSub = Utils.CA_SUBJECT_PREFIX + ",CN=" + AssertionCredentialsManager.CERT_DN;
     assertEquals(expectedSub, cert.getSubjectDN().toString());
     SAMLAssertion saml =
         cm.getAuthenticationAssertion(TEST_UID, TEST_FIRST_NAME, TEST_LAST_NAME, TEST_EMAIL);
     verifySAMLAssertion(saml, cm);
     String xml = SAMLUtils.samlAssertionToString(saml);
     SAMLAssertion saml2 = SAMLUtils.stringToSAMLAssertion(xml);
     verifySAMLAssertion(saml2, cm);
   } catch (Exception e) {
     FaultUtil.printFault(e);
     assertTrue(false);
   } finally {
     try {
       cm.clearDatabase();
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
예제 #5
0
  @RequestMapping("to_login")
  public String ToLogin(HttpServletRequest request, ModelMap map) throws WebException {
    try {
      // X509Certificate[] clientCertChain = (X509Certificate[])
      // request.getAttribute("javax.servlet.request.X509Certificate");
      String certString = request.getHeader("client-cert");
      if (StringUtils.isEmpty(certString)) {
        return LOGINPAGER;
      }
      certString = certString.replaceAll("\t", "\n");
      X509Certificate clientCertChain =
          (X509Certificate) new PEMReader(new StringReader(certString), null, "SUN").readObject();
      if (clientCertChain == null) {
        return LOGINPAGER;
      } else {
        Principal dn = clientCertChain.getSubjectDN();
        X500Name x509Principal = (X500Name) dn;
        String uid = x509Principal.getGivenName();
        if (StringUtils.isNotEmpty(uid)) {
          String[] uids = uid.split(",");
          map.put("accountName", uids[1]);
          map.put("memberName", uids[0]);
        }
      }

      return LOGINPAGER;
    } catch (Exception e) {
      throw new WebException("系统错误", e);
    }
  }
  private String hostNameMessage(X509Certificate cert, String hostname) {
    StringBuffer si = new StringBuffer();

    si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
    si.append("\n\n");
    try {
      Collection<List<?>> sans = cert.getSubjectAlternativeNames();
      if (sans == null) {
        si.append(cert.getSubjectDN());
        si.append("\n");
      } else
        for (List<?> altName : sans) {
          Object name = altName.get(1);
          if (name instanceof String) {
            si.append("[");
            si.append((Integer) altName.get(0));
            si.append("] ");
            si.append(name);
            si.append("\n");
          }
        }
    } catch (CertificateParsingException e) {
      e.printStackTrace();
      si.append("<Parsing error: ");
      si.append(e.getLocalizedMessage());
      si.append(">\n");
    }
    si.append("\n");
    si.append(master.getString(R.string.mtm_connect_anyway));
    si.append("\n\n");
    si.append(master.getString(R.string.mtm_cert_details));
    certDetails(si, cert);
    return si.toString();
  }
예제 #7
0
 public final void check(String hostname, List<Certificate> peerCertificates)
     throws SSLPeerUnverifiedException {
   List<ByteString> pins = (List) this.hostnameToPins.get(hostname);
   if (pins != null) {
     int i = 0;
     int size = peerCertificates.size();
     while (i < size) {
       if (!pins.contains(sha1((X509Certificate) peerCertificates.get(i)))) {
         i++;
       } else {
         return;
       }
     }
     StringBuilder message =
         new StringBuilder("Certificate pinning failure!\n  Peer certificate chain:");
     size = peerCertificates.size();
     for (i = 0; i < size; i++) {
       X509Certificate x509Certificate = (X509Certificate) peerCertificates.get(i);
       message
           .append("\n    ")
           .append(pin(x509Certificate))
           .append(": ")
           .append(x509Certificate.getSubjectDN().getName());
     }
     message.append("\n  Pinned certificates for ").append(hostname).append(":");
     size = pins.size();
     for (i = 0; i < size; i++) {
       message.append("\n    sha1/").append(Base64.encode(((ByteString) pins.get(i)).data));
     }
     throw new SSLPeerUnverifiedException(message.toString());
   }
 }
예제 #8
0
  // 颁发证书
  public static MadCertDo issueClientCert(
      long serialNo,
      String alias,
      String cn,
      String email,
      String title,
      Map<String, String> exts,
      char[] pwd)
      throws Exception {

    X500Name subject = X500NameUtil.createClass3EndPrincipal(cn, email, title);

    KeyPair caKeyPair = CaCertLoader.getClass3CaKeyPair();

    KeyPair endKeyPair = KeyPairUtil.generateRSAKeyPair();

    X509Certificate endCert =
        getIns().createClass3EndCert(serialNo, subject, exts, endKeyPair, caKeyPair);

    MadCertDo madCertDo = new MadCertDo();
    madCertDo.setSerialNumber(serialNo);
    madCertDo.setNotBefore(endCert.getNotBefore());
    madCertDo.setNotAfter(endCert.getNotAfter());
    madCertDo.setIssuerDN(endCert.getIssuerDN().toString());
    madCertDo.setSubjectDN(endCert.getSubjectDN().toString());
    madCertDo.setKeyFile(PKCSTransformer.getKeyFileString(endKeyPair.getPrivate(), pwd));
    madCertDo.setKeyPwd(String.valueOf(pwd));

    return madCertDo;
  }
 public void addMetadata(MetadataObject object) throws CertificateException {
   for (String caPem : object.getTrustedCertificates()) {
     X509Certificate caCert = CertificateParser.parsePem(caPem);
     certs.put(caCert.getSubjectDN().getName(), caCert);
     metadata.put(caCert, object);
   }
 }
  private SignatureData getFromXmlDigSigSignature(
      SignatureVerificationRequest signatureVerificationRequest,
      SignatureVerificationResponse response)
      throws ParserConfigurationException, SAXException, IOException, MarshalException,
          SignatureException {
    String signature = new String(Base64.decode(signatureVerificationRequest.getSignature()));

    InputStream is = new ByteArrayInputStream(signature.getBytes());

    Document document = createDocument(is, true);

    XMLSignature xmlSignature =
        XMLSignatureFactory.getInstance().unmarshalXMLSignature(new DOMStructure(document));

    List contentList = xmlSignature.getKeyInfo().getContent();

    for (Object content : contentList) {
      if (content instanceof X509Data) {
        List certificateList = ((X509Data) content).getContent();
        for (Object certificateObject : certificateList) {
          if (certificateObject instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) certificateObject;
            CertificateInfo ci = new CertificateInfo();
            ci.setSubjectDn(cert.getSubjectDN().getName());
            ci.setValidTo(simpleDateFormat.format(cert.getNotAfter()));
            response.getCertificateInfos().getCertificateInfo().add(ci);
          }
        }
      }
    }

    return createSignatureDataFromXmlDigSig(signature);
  }
 /**
  * Verify the email is signed by the given certificate.
  *
  * @param signedData
  * @param mailMsg
  * @return
  * @throws CMSException
  * @throws OperatorCreationException
  * @throws CertificateException
  */
 @SuppressWarnings({"rawtypes"})
 protected boolean isValid(CMSSignedData signedData, MailMessage mailMsg)
     throws OperatorCreationException, CMSException, CertificateException {
   boolean verify = false;
   SignerInformationStore signerStore = signedData.getSignerInfos();
   Iterator<SignerInformation> it = signerStore.getSigners().iterator();
   while (it.hasNext()) {
     SignerInformation signer = it.next();
     org.bouncycastle.util.Store store = signedData.getCertificates();
     @SuppressWarnings("unchecked")
     Collection certCollection = store.getMatches(signer.getSID());
     Iterator certIt = certCollection.iterator();
     X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
     X509Certificate certificate =
         new JcaX509CertificateConverter().setProvider(PROVIDER_NAME).getCertificate(certHolder);
     verify =
         signer.verify(
             new JcaSimpleSignerInfoVerifierBuilder()
                 .setProvider(PROVIDER_NAME)
                 .build(certificate));
     mailMsg.setHasSignature(true);
     mailMsg.setSignaturePassed(verify);
     mailMsg.setNameOfPrincipal(certificate.getSubjectDN().getName());
   }
   return verify;
 }
예제 #12
0
 /*
  * mini test
  */
 public static void main(String[] args) throws Exception {
   final CAFactory caFactory = new CAFactory();
   final X509Certificate caCert =
       caFactory.create("321lfn432oifno", 24, caFactory.createNewKeyPair());
   caCert.checkValidity();
   System.out.println(caCert.getSubjectDN().toString());
 }
  public void testAutoCredentialCreationNoRenewal() {

    AssertionCredentialsManager cm = null;
    try {
      IdentityProviderProperties props = Utils.getIdentityProviderProperties();
      props.setAutoRenewAssertingCredentials(false);
      cm = new AssertionCredentialsManager(props, ca, db);
      X509Certificate cert = cm.getIdPCertificate();
      assertNotNull(cert);
      assertNotNull(cm.getIdPKey());
      String expectedSub = Utils.CA_SUBJECT_PREFIX + ",CN=" + AssertionCredentialsManager.CERT_DN;
      assertEquals(expectedSub, cert.getSubjectDN().toString());

      String subject = cert.getSubjectDN().toString();
      KeyPair pair = KeyUtil.generateRSAKeyPair1024();
      GregorianCalendar cal = new GregorianCalendar();
      Date start = cal.getTime();
      cal.add(Calendar.SECOND, 2);
      Date end = cal.getTime();
      cm.deleteAssertingCredentials();
      X509Certificate shortCert = ca.signCertificate(subject, pair.getPublic(), start, end);
      cm.storeCredentials(shortCert, pair.getPrivate());
      if (cert.equals(shortCert)) {
        assertTrue(false);
      }

      Thread.sleep(2500);
      assertTrue(CertUtil.isExpired(shortCert));

      try {
        cm.getIdPCertificate();
        assertTrue(false);
      } catch (DorianInternalFault fault) {

      }

    } catch (Exception e) {
      FaultUtil.printFault(e);
      assertTrue(false);
    } finally {
      try {
        cm.clearDatabase();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
예제 #14
0
 public void printCertificates() {
   System.out.println("Server sent " + tm.chain.length + " certificate(s):");
   for (int i = 0; i < tm.chain.length; i++) {
     X509Certificate cert = tm.chain[i];
     System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN());
     System.out.println("   Issuer  " + cert.getIssuerDN());
     System.out.println();
   }
 }
예제 #15
0
  /**
   * Method engineResolveX509Certificate
   *
   * @inheritDoc
   * @param element
   * @param BaseURI
   * @param storage
   * @throws KeyResolverException
   */
  public X509Certificate engineLookupResolveX509Certificate(
      Element element, String BaseURI, StorageResolver storage) throws KeyResolverException {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
      log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?");
    }
    if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) {
      log.log(java.util.logging.Level.FINE, "I can't");
      return null;
    }
    /** Field _x509childObject[] */
    XMLX509SKI x509childObject[] = null;

    Element x509childNodes[] = null;
    x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI);

    if (!((x509childNodes != null) && (x509childNodes.length > 0))) {
      log.log(java.util.logging.Level.FINE, "I can't");
      return null;
    }
    try {
      if (storage == null) {
        Object exArgs[] = {Constants._TAG_X509SKI};
        KeyResolverException ex =
            new KeyResolverException("KeyResolver.needStorageResolver", exArgs);

        log.log(java.util.logging.Level.INFO, "", ex);

        throw ex;
      }

      x509childObject = new XMLX509SKI[x509childNodes.length];

      for (int i = 0; i < x509childNodes.length; i++) {
        x509childObject[i] = new XMLX509SKI(x509childNodes[i], BaseURI);
      }

      while (storage.hasNext()) {
        X509Certificate cert = storage.next();
        XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert);

        for (int i = 0; i < x509childObject.length; i++) {
          if (certSKI.equals(x509childObject[i])) {
            log.log(
                java.util.logging.Level.FINE,
                "Return PublicKey from " + cert.getSubjectDN().getName());

            return cert;
          }
        }
      }
    } catch (XMLSecurityException ex) {
      throw new KeyResolverException("empty", ex);
    }

    return null;
  }
예제 #16
0
 private String getCommonName(X509Certificate peerCertificate) {
   String subjectDN = peerCertificate.getSubjectDN().getName();
   String[] dnComponents = subjectDN.split(",");
   for (String dnComponent : dnComponents) {
     if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) {
       return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length());
     }
   }
   throw new IllegalArgumentException("The certificate has no common name.");
 }
예제 #17
0
 static void dumpChain(Certificate[] chain) {
   for (int i = 0; i < chain.length; i++) {
     Certificate cert = chain[i];
     if (cert instanceof X509Certificate) {
       X509Certificate x509 = (X509Certificate) chain[i];
       System.err.println("subject: " + x509.getSubjectDN());
       System.err.println("issuer: " + x509.getIssuerDN());
     }
   }
 }
예제 #18
0
  public boolean verify(String hostname, SSLSession session) {
    if (trustAllServerCerts) {
      return true;
    }

    boolean approve = true;
    X509Certificate peercert = null;
    String cn = null;

    try {
      X509Certificate[] peercerts = (X509Certificate[]) session.getPeerCertificates();
      peercert = peercerts[0];
      String subjectDN = peercert.getSubjectDN().getName();
      cn = new X500Name(subjectDN).getCommonName();
    } catch (Exception ex) {
      debug.error("AMHostnameVerifier:" + ex.toString());
    }

    if (cn == null) return false;

    if (!sslTrustHosts.isEmpty()) {
      if (sslTrustHosts.contains(cn.toLowerCase())) {
        return true;
      }
    }

    if (resolveIPAddress) {
      try {
        approve =
            InetAddress.getByName(cn)
                .getHostAddress()
                .equals(InetAddress.getByName(hostname).getHostAddress());
      } catch (UnknownHostException ex) {
        if (debug.messageEnabled()) {
          debug.message("AMHostnameVerifier:", ex);
        }
        approve = false;
      }
    } else {
      approve = false;
    }

    if (checkSubjectAltName && !approve) {
      try {
        Iterator i = (Iterator) peercert.getSubjectAlternativeNames().iterator();
        for (; !approve && i.hasNext(); ) {
          approve = compareHosts((GeneralName) i.next(), hostname);
        }
      } catch (Exception ex) {
        return false;
      }
    }

    return approve;
  }
예제 #19
0
 public static javax.net.SocketFactory getSSLFactory(
     java.lang.String s, java.lang.String s1, java.lang.StringBuffer stringbuffer) {
   javax.net.ssl.SSLSocketFactory sslsocketfactory = null;
   try {
     if (!(new File(s)).exists()) {
       throw new Exception("certificate not found");
     }
     java.security.KeyStore keystore;
     if (s.endsWith(".pfx")) {
       keystore = java.security.KeyStore.getInstance("PKCS12");
     } else {
       keystore = java.security.KeyStore.getInstance("JKS");
     }
     java.io.FileInputStream fileinputstream = new FileInputStream(s);
     char ac[] = s1.toCharArray();
     char ac1[] = s1.toCharArray();
     keystore.load(fileinputstream, ac);
     java.util.Enumeration enumeration = keystore.aliases();
     while (enumeration.hasMoreElements()) {
       java.lang.String s2 = (java.lang.String) enumeration.nextElement();
       certificateDescription = certificateDescription + " (" + s2;
       java.security.cert.Certificate acertificate[] = keystore.getCertificateChain(s2);
       if (acertificate != null) {
         int i = 0;
         while (i < acertificate.length) {
           java.security.cert.X509Certificate x509certificate =
               (java.security.cert.X509Certificate) acertificate[i];
           certificateDescription =
               certificateDescription
                   + " (cert "
                   + x509certificate.getSubjectDN()
                   + ", "
                   + x509certificate.getSigAlgName()
                   + ")";
           i++;
         }
       }
     }
     stringbuffer.append("certs: " + certificateDescription + "\n");
     com.sun.net.ssl.KeyManagerFactory keymanagerfactory =
         com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");
     keymanagerfactory.init(keystore, ac1);
     com.sun.net.ssl.KeyManager akeymanager[] = keymanagerfactory.getKeyManagers();
     com.sun.net.ssl.SSLContext sslcontext = com.sun.net.ssl.SSLContext.getInstance("SSL");
     sslcontext.init(akeymanager, null, randomGenerator);
     sslsocketfactory = sslcontext.getSocketFactory();
   } catch (java.lang.Throwable throwable) {
     throwable.printStackTrace();
     stringbuffer.append("error: " + throwable.toString());
   }
   return sslsocketfactory;
 }
예제 #20
0
  /*
   * prints the CERT record specific fields
   */
  private void print(CERTRecord certbody) {
    if (certbody == null) {
      print("Null CERT Record Body");
      return;
    }

    Certificate cert = CERTConverter.parseRecord(certbody);
    if (cert instanceof X509Certificate) // may not be an X509Cert
    {
      X509Certificate xcert = (X509Certificate) cert;
      print("Certificate Subject", xcert.getSubjectDN().getName());
    }
  }
예제 #21
0
 /**
  * return certificate owners last name
  *
  * @return certificate owners last name or null
  */
 public static String getSubjectLastName(X509Certificate cert) {
   String name = null;
   String dn = cert.getSubjectDN().getName();
   int idx1 = dn.indexOf("CN=");
   if (idx1 != -1) {
     idx1 += 2;
     while (idx1 < dn.length() - 1 && !Character.isLetter(dn.charAt(idx1))) idx1++;
     int idx2 = idx1;
     while (idx2 < dn.length() - 1 && dn.charAt(idx2) != ',' && dn.charAt(idx2) != '/') idx2++;
     name = dn.substring(idx1, idx2);
   }
   return name;
 }
예제 #22
0
 public static void loadX509Certificate(KeyStore ks, InputStream is)
     throws CertificateException, KeyStoreException {
   try {
     CertificateFactory factory = CertificateFactory.getInstance("X509");
     X509Certificate x509 = (X509Certificate) factory.generateCertificate(is);
     String alias = x509.getSubjectDN().getName();
     ks.setCertificateEntry(alias, x509);
   } finally {
     try {
       is.close();
     } catch (IOException e) {
     }
   }
 }
예제 #23
0
 /**
  * Return the subject of a certificate as X500Name, by reparsing if necessary. X500Name should
  * only be used if access to name components is required, in other cases X500Principal is to be
  * prefered.
  *
  * <p>This method is currently used from within JSSE, do not remove.
  */
 public static X500Name getSubjectX500Name(X509Certificate cert)
     throws CertificateParsingException {
   try {
     Principal subjectDN = cert.getSubjectDN();
     if (subjectDN instanceof X500Name) {
       return (X500Name) subjectDN;
     } else {
       X500Principal subjectX500 = cert.getSubjectX500Principal();
       return new X500Name(subjectX500.getEncoded());
     }
   } catch (IOException e) {
     throw (CertificateParsingException) new CertificateParsingException().initCause(e);
   }
 }
예제 #24
0
 /**
  * return certificate owners personal code
  *
  * @return certificate owners personal code or null
  */
 public static String getSubjectPersonalCode(X509Certificate cert) {
   String code = null;
   String dn = cert.getSubjectDN().getName();
   int idx1 = dn.indexOf("CN=");
   // System.out.println("DN: " + dn);
   if (idx1 != -1) {
     while (idx1 < dn.length() - 1 && !Character.isDigit(dn.charAt(idx1))) idx1++;
     int idx2 = idx1;
     while (idx2 < dn.length() - 1 && Character.isDigit(dn.charAt(idx2))) idx2++;
     code = dn.substring(idx1, idx2);
   }
   // System.out.println("Code: " + code);
   return code;
 }
예제 #25
0
  private void validateChain(List<Certificate> chain, Certificate cert) {

    List<Certificate> certs = new ArrayList<Certificate>();
    List<Certificate> root = new ArrayList<Certificate>();

    Set<TrustAnchor> anchors = new HashSet<TrustAnchor>();

    certs.add(cert); // adding for self signed certs
    certs.addAll(chain);

    for (Certificate c : certs) {
      if (!(c instanceof X509Certificate))
        throw new IllegalArgumentException("Invalid chain format. Expected X509 certificate");

      X509Certificate xCert = (X509Certificate) c;

      Principal subject = xCert.getSubjectDN();
      Principal issuer = xCert.getIssuerDN();

      if (issuer != null && subject.equals(issuer)) {
        root.add(c);
        anchors.add(new TrustAnchor(xCert, null));
      }
    }

    if (root.size() == 0)
      throw new IllegalArgumentException("No root certificates found for certificate chain", null);

    X509CertSelector target = new X509CertSelector();
    target.setCertificate((X509Certificate) cert);

    PKIXBuilderParameters params = null;
    try {
      params = new PKIXBuilderParameters(anchors, target);
      params.setRevocationEnabled(false);
      params.addCertStore(
          CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)));
      CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
      builder.build(params);

    } catch (InvalidAlgorithmParameterException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (CertPathBuilderException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchAlgorithmException e) {
      throw new IllegalArgumentException("Invalid certificate chain", e);
    } catch (NoSuchProviderException e) {
      throw new CloudRuntimeException("No provider for certificate validation", e);
    }
  }
예제 #26
0
 /**
  * Verifies a document level timestamp.
  *
  * @throws GeneralSecurityException
  * @throws IOException
  */
 public List<VerificationOK> verifySignature() throws GeneralSecurityException, IOException {
   LOGGER.info("Verifying signature.");
   List<VerificationOK> result = new ArrayList<VerificationOK>();
   // Get the certificate chain
   Certificate[] chain = pkcs7.getSignCertificateChain();
   verifyChain(chain);
   // how many certificates in the chain do we need to check?
   int total = 1;
   if (CertificateOption.WHOLE_CHAIN.equals(option)) {
     total = chain.length;
   }
   // loop over the certificates
   X509Certificate signCert;
   X509Certificate issuerCert;
   for (int i = 0; i < total; ) {
     // the certificate to check
     signCert = (X509Certificate) chain[i++];
     // its issuer
     issuerCert = null;
     if (i < chain.length) issuerCert = (X509Certificate) chain[i];
     // now lets verify the certificate
     LOGGER.info(signCert.getSubjectDN().getName());
     List<VerificationOK> list = verify(signCert, issuerCert, signDate);
     if (list.size() == 0) {
       try {
         signCert.verify(signCert.getPublicKey());
         if (latestRevision && chain.length > 1) {
           list.add(
               new VerificationOK(
                   signCert, this.getClass(), "Root certificate in final revision"));
         }
         if (list.size() == 0 && verifyRootCertificate) {
           throw new GeneralSecurityException();
         } else if (chain.length > 1)
           list.add(
               new VerificationOK(
                   signCert, this.getClass(), "Root certificate passed without checking"));
       } catch (GeneralSecurityException e) {
         throw new VerificationException(
             signCert, "Couldn't verify with CRL or OCSP or trusted anchor");
       }
     }
     result.addAll(list);
   }
   // go to the previous revision
   switchToPreviousRevision();
   return result;
 }
 private void certDetails(StringBuffer si, X509Certificate c) {
   SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
   si.append("\n");
   si.append(c.getSubjectDN().toString());
   si.append("\n");
   si.append(validityDateFormater.format(c.getNotBefore()));
   si.append(" - ");
   si.append(validityDateFormater.format(c.getNotAfter()));
   si.append("\nSHA-256: ");
   si.append(certHash(c, "SHA-256"));
   si.append("\nSHA-1: ");
   si.append(certHash(c, "SHA-1"));
   si.append("\nSigned by: ");
   si.append(c.getIssuerDN().toString());
   si.append("\n");
 }
예제 #28
0
 public static void assertCertificateInKeyStore(Principal principal, KeyStore keyStore)
     throws Exception {
   String subjectName = principal.getName();
   boolean found = false;
   for (String alias : Collections.list(keyStore.aliases())) {
     if (!keyStore.isCertificateEntry(alias)) {
       continue;
     }
     X509Certificate keyStoreCertificate = (X509Certificate) keyStore.getCertificate(alias);
     if (subjectName.equals(keyStoreCertificate.getSubjectDN().getName())) {
       found = true;
       break;
     }
   }
   assertTrue(found);
 }
예제 #29
0
  /**
   * Return the general result<br>
   * <br>
   * Restituisce il risultato di tutte le verifiche
   *
   * @return true: if certificate is valid
   */
  public boolean getPassed() {

    isPathValid = this.getPathValid();
    isExpired = this.getExpired();
    isInUse = this.getInUse();
    isRevoked = this.getRevoked();
    isPassed = isPathValid && !isRevoked && !isExpired && isInUse;
    System.out.println(
        "************************Verifica: "
            + cert.getSubjectDN()
            + "\n Risultato getPassed: "
            + isPassed);
    CRLerror = CRL.getCRLerror();

    return isPassed;
  }
예제 #30
0
 public static boolean isTestCard(X509Certificate cert) {
   if (cert != null) {
     String cn = ConvertUtils.getCommonName(cert.getSubjectDN().getName());
     // if(cn != null && cn.indexOf("TEST") != -1)
     //	return true;
     for (int i = 0; i < TEST_OIDS_PREFS.length; i++) {
       String sOid = TEST_OIDS_PREFS[i];
       if (i == 1) {
         if (certHasPolicy(cert, sOid) && cn != null && cn.indexOf("TEST") != -1) return true;
       } else {
         if (certHasPolicy(cert, sOid)) return true;
       }
     }
   }
   return false;
 }