public void processServerCertificate(Certificate serverCertificate) throws IOException {
    if (serverCertificate.isEmpty()) {
      throw new TlsFatalAlert(AlertDescription.bad_certificate);
    }

    org.ripple.bouncycastle.asn1.x509.Certificate x509Cert = serverCertificate.getCertificateAt(0);

    SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo();
    try {
      this.serverPublicKey = PublicKeyFactory.createKey(keyInfo);
    } catch (RuntimeException e) {
      throw new TlsFatalAlert(AlertDescription.unsupported_certificate, e);
    }

    if (tlsSigner == null) {
      try {
        this.dhAgreePublicKey =
            TlsDHUtils.validateDHPublicKey((DHPublicKeyParameters) this.serverPublicKey);
        this.dhParameters = validateDHParameters(dhAgreePublicKey.getParameters());
      } catch (ClassCastException e) {
        throw new TlsFatalAlert(AlertDescription.certificate_unknown, e);
      }

      TlsUtils.validateKeyUsage(x509Cert, KeyUsage.keyAgreement);
    } else {
      if (!tlsSigner.isValidPublicKey(this.serverPublicKey)) {
        throw new TlsFatalAlert(AlertDescription.certificate_unknown);
      }

      TlsUtils.validateKeyUsage(x509Cert, KeyUsage.digitalSignature);
    }

    super.processServerCertificate(serverCertificate);
  }
  public void checkValidity(Date date)
      throws CertificateExpiredException, CertificateNotYetValidException {
    if (date.getTime() > this.getNotAfter().getTime()) // for other VM compatibility
    {
      throw new CertificateExpiredException("certificate expired on " + c.getEndDate().getTime());
    }

    if (date.getTime() < this.getNotBefore().getTime()) {
      throw new CertificateNotYetValidException(
          "certificate not valid till " + c.getStartDate().getTime());
    }
  }
 /** return the signature parameters, or null if there aren't any. */
 public byte[] getSigAlgParams() {
   if (c.getSignatureAlgorithm().getParameters() != null) {
     try {
       return c.getSignatureAlgorithm()
           .getParameters()
           .toASN1Primitive()
           .getEncoded(ASN1Encoding.DER);
     } catch (IOException e) {
       return null;
     }
   } else {
     return null;
   }
 }
 public Principal getIssuerDN() {
   try {
     return new X509Principal(X500Name.getInstance(c.getIssuer().getEncoded()));
   } catch (IOException e) {
     return null;
   }
 }
 public PublicKey getPublicKey() {
   try {
     return BouncyCastleProvider.getPublicKey(c.getSubjectPublicKeyInfo());
   } catch (IOException e) {
     return null; // should never happen...
   }
 }
 public byte[] getEncoded() throws CertificateEncodingException {
   try {
     return c.getEncoded(ASN1Encoding.DER);
   } catch (IOException e) {
     throw new CertificateEncodingException(e.toString());
   }
 }
  public final void verify(PublicKey key, String sigProvider)
      throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
          NoSuchProviderException, SignatureException {
    String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm());
    Signature signature = Signature.getInstance(sigName, sigProvider);

    checkSignature(key, signature);
  }
  private Certificate readPEMCertificate(InputStream in)
      throws IOException, CertificateParsingException {
    ASN1Sequence seq = PEM_PARSER.readPEMObject(in);

    if (seq != null) {
      return new X509CertificateObject(
          org.ripple.bouncycastle.asn1.x509.Certificate.getInstance(seq));
    }

    return null;
  }
  private void checkSignature(PublicKey key, Signature signature)
      throws CertificateException, NoSuchAlgorithmException, SignatureException,
          InvalidKeyException {
    if (!isAlgIdEqual(c.getSignatureAlgorithm(), c.getTBSCertificate().getSignature())) {
      throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
    }

    ASN1Encodable params = c.getSignatureAlgorithm().getParameters();

    // TODO This should go after the initVerify?
    X509SignatureUtil.setSignatureParameters(signature, params);

    signature.initVerify(key);

    signature.update(this.getTBSCertificate());

    if (!signature.verify(this.getSignature())) {
      throw new SignatureException("certificate does not verify with supplied key");
    }
  }
  private byte[] getExtensionBytes(String oid) {
    Extensions exts = c.getTBSCertificate().getExtensions();

    if (exts != null) {
      Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid));
      if (ext != null) {
        return ext.getExtnValue().getOctets();
      }
    }

    return null;
  }
  public X500Principal getSubjectX500Principal() {
    try {
      ByteArrayOutputStream bOut = new ByteArrayOutputStream();
      ASN1OutputStream aOut = new ASN1OutputStream(bOut);

      aOut.writeObject(c.getSubject());

      return new X500Principal(bOut.toByteArray());
    } catch (IOException e) {
      throw new IllegalStateException("can't encode issuer DN");
    }
  }
  private Certificate getCertificate() throws CertificateParsingException {
    if (sData != null) {
      while (sDataObjectCount < sData.size()) {
        Object obj = sData.getObjectAt(sDataObjectCount++);

        if (obj instanceof ASN1Sequence) {
          return new X509CertificateObject(
              org.ripple.bouncycastle.asn1.x509.Certificate.getInstance(obj));
        }
      }
    }

    return null;
  }
  public final void verify(PublicKey key)
      throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
          NoSuchProviderException, SignatureException {
    Signature signature;
    String sigName = X509SignatureUtil.getSignatureName(c.getSignatureAlgorithm());

    try {
      signature = Signature.getInstance(sigName, BouncyCastleProvider.PROVIDER_NAME);
    } catch (Exception e) {
      signature = Signature.getInstance(sigName);
    }

    checkSignature(key, signature);
  }
  public boolean[] getSubjectUniqueID() {
    DERBitString id = c.getTBSCertificate().getSubjectUniqueId();

    if (id != null) {
      byte[] bytes = id.getBytes();
      boolean[] boolId = new boolean[bytes.length * 8 - id.getPadBits()];

      for (int i = 0; i != boolId.length; i++) {
        boolId[i] = (bytes[i / 8] & (0x80 >>> (i % 8))) != 0;
      }

      return boolId;
    }

    return null;
  }
  public byte[] getExtensionValue(String oid) {
    Extensions exts = c.getTBSCertificate().getExtensions();

    if (exts != null) {
      Extension ext = exts.getExtension(new ASN1ObjectIdentifier(oid));

      if (ext != null) {
        try {
          return ext.getExtnValue().getEncoded();
        } catch (Exception e) {
          throw new IllegalStateException("error parsing " + e.toString());
        }
      }
    }

    return null;
  }
  private Certificate readDERCertificate(InputStream in)
      throws IOException, CertificateParsingException {
    ASN1InputStream dIn = new ASN1InputStream(in);
    ASN1Sequence seq = (ASN1Sequence) dIn.readObject();

    if (seq.size() > 1 && seq.getObjectAt(0) instanceof DERObjectIdentifier) {
      if (seq.getObjectAt(0).equals(PKCSObjectIdentifiers.signedData)) {
        sData =
            new SignedData(ASN1Sequence.getInstance((ASN1TaggedObject) seq.getObjectAt(1), true))
                .getCertificates();

        return getCertificate();
      }
    }

    return new X509CertificateObject(
        org.ripple.bouncycastle.asn1.x509.Certificate.getInstance(seq));
  }
  public Set getNonCriticalExtensionOIDs() {
    if (this.getVersion() == 3) {
      Set set = new HashSet();
      Extensions extensions = c.getTBSCertificate().getExtensions();

      if (extensions != null) {
        Enumeration e = extensions.oids();

        while (e.hasMoreElements()) {
          ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
          Extension ext = extensions.getExtension(oid);

          if (!ext.isCritical()) {
            set.add(oid.getId());
          }
        }

        return set;
      }
    }

    return null;
  }
  public boolean hasUnsupportedCriticalExtension() {
    if (this.getVersion() == 3) {
      Extensions extensions = c.getTBSCertificate().getExtensions();

      if (extensions != null) {
        Enumeration e = extensions.oids();

        while (e.hasMoreElements()) {
          ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
          String oidId = oid.getId();

          if (oidId.equals(RFC3280CertPathUtilities.KEY_USAGE)
              || oidId.equals(RFC3280CertPathUtilities.CERTIFICATE_POLICIES)
              || oidId.equals(RFC3280CertPathUtilities.POLICY_MAPPINGS)
              || oidId.equals(RFC3280CertPathUtilities.INHIBIT_ANY_POLICY)
              || oidId.equals(RFC3280CertPathUtilities.CRL_DISTRIBUTION_POINTS)
              || oidId.equals(RFC3280CertPathUtilities.ISSUING_DISTRIBUTION_POINT)
              || oidId.equals(RFC3280CertPathUtilities.DELTA_CRL_INDICATOR)
              || oidId.equals(RFC3280CertPathUtilities.POLICY_CONSTRAINTS)
              || oidId.equals(RFC3280CertPathUtilities.BASIC_CONSTRAINTS)
              || oidId.equals(RFC3280CertPathUtilities.SUBJECT_ALTERNATIVE_NAME)
              || oidId.equals(RFC3280CertPathUtilities.NAME_CONSTRAINTS)) {
            continue;
          }

          Extension ext = extensions.getExtension(oid);

          if (ext.isCritical()) {
            return true;
          }
        }
      }
    }

    return false;
  }
 public Date getNotBefore() {
   return c.getStartDate().getDate();
 }
 /** return the object identifier for the signature. */
 public String getSigAlgOID() {
   return c.getSignatureAlgorithm().getAlgorithm().getId();
 }
 public byte[] getSignature() {
   return c.getSignature().getBytes();
 }
 public Principal getSubjectDN() {
   return new X509Principal(X500Name.getInstance(c.getSubject().toASN1Primitive()));
 }
 public Date getNotAfter() {
   return c.getEndDate().getDate();
 }
  public String toString() {
    StringBuffer buf = new StringBuffer();
    String nl = Strings.lineSeparator();

    buf.append("  [0]         Version: ").append(this.getVersion()).append(nl);
    buf.append("         SerialNumber: ").append(this.getSerialNumber()).append(nl);
    buf.append("             IssuerDN: ").append(this.getIssuerDN()).append(nl);
    buf.append("           Start Date: ").append(this.getNotBefore()).append(nl);
    buf.append("           Final Date: ").append(this.getNotAfter()).append(nl);
    buf.append("            SubjectDN: ").append(this.getSubjectDN()).append(nl);
    buf.append("           Public Key: ").append(this.getPublicKey()).append(nl);
    buf.append("  Signature Algorithm: ").append(this.getSigAlgName()).append(nl);

    byte[] sig = this.getSignature();

    buf.append("            Signature: ").append(new String(Hex.encode(sig, 0, 20))).append(nl);
    for (int i = 20; i < sig.length; i += 20) {
      if (i < sig.length - 20) {
        buf.append("                       ").append(new String(Hex.encode(sig, i, 20))).append(nl);
      } else {
        buf.append("                       ")
            .append(new String(Hex.encode(sig, i, sig.length - i)))
            .append(nl);
      }
    }

    Extensions extensions = c.getTBSCertificate().getExtensions();

    if (extensions != null) {
      Enumeration e = extensions.oids();

      if (e.hasMoreElements()) {
        buf.append("       Extensions: \n");
      }

      while (e.hasMoreElements()) {
        ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
        Extension ext = extensions.getExtension(oid);

        if (ext.getExtnValue() != null) {
          byte[] octs = ext.getExtnValue().getOctets();
          ASN1InputStream dIn = new ASN1InputStream(octs);
          buf.append("                       critical(").append(ext.isCritical()).append(") ");
          try {
            if (oid.equals(Extension.basicConstraints)) {
              buf.append(BasicConstraints.getInstance(dIn.readObject())).append(nl);
            } else if (oid.equals(Extension.keyUsage)) {
              buf.append(KeyUsage.getInstance(dIn.readObject())).append(nl);
            } else if (oid.equals(MiscObjectIdentifiers.netscapeCertType)) {
              buf.append(new NetscapeCertType((DERBitString) dIn.readObject())).append(nl);
            } else if (oid.equals(MiscObjectIdentifiers.netscapeRevocationURL)) {
              buf.append(new NetscapeRevocationURL((DERIA5String) dIn.readObject())).append(nl);
            } else if (oid.equals(MiscObjectIdentifiers.verisignCzagExtension)) {
              buf.append(new VerisignCzagExtension((DERIA5String) dIn.readObject())).append(nl);
            } else {
              buf.append(oid.getId());
              buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl);
              // buf.append(" value = ").append("*****").append(nl);
            }
          } catch (Exception ex) {
            buf.append(oid.getId());
            //     buf.append(" value = ").append(new
            // String(Hex.encode(ext.getExtnValue().getOctets()))).append(nl);
            buf.append(" value = ").append("*****").append(nl);
          }
        } else {
          buf.append(nl);
        }
      }
    }

    return buf.toString();
  }
 public int getVersion() {
   return c.getVersionNumber();
 }
 public BigInteger getSerialNumber() {
   return c.getSerialNumber().getValue();
 }