示例#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();
    }
  }
  /*
   * Check for a valid certificate pair
   */
  private void checkPair() throws CertificateException {

    /* if either of pair is missing, return w/o error */
    if (forward == null || reverse == null) {
      return;
    }
    /*
     * If both elements of the pair are present, check that they
     * are a valid pair.
     */
    X500Principal fwSubject = forward.getSubjectX500Principal();
    X500Principal fwIssuer = forward.getIssuerX500Principal();
    X500Principal rvSubject = reverse.getSubjectX500Principal();
    X500Principal rvIssuer = reverse.getIssuerX500Principal();
    if (!fwIssuer.equals(rvSubject) || !rvIssuer.equals(fwSubject)) {
      throw new CertificateException(
          "subject and issuer names in " + "forward and reverse certificates do not match");
    }

    /* check signatures unless key parameters are missing */
    try {
      PublicKey pk = reverse.getPublicKey();
      if (!(pk instanceof DSAPublicKey) || ((DSAPublicKey) pk).getParams() != null) {
        forward.verify(pk);
      }
      pk = forward.getPublicKey();
      if (!(pk instanceof DSAPublicKey) || ((DSAPublicKey) pk).getParams() != null) {
        reverse.verify(pk);
      }
    } catch (GeneralSecurityException e) {
      throw new CertificateException("invalid signature: " + e.getMessage());
    }
  }
 public static boolean isPre2011IdCard(X509Certificate cert) {
   return ((cert != null)
       && (cert.getPublicKey() instanceof RSAPublicKey)
       && (((RSAPublicKey) cert.getPublicKey()).getModulus().bitLength() == 1024)
       &&
       // cert.getPublicKey().getEncoded().length <= PRE2011_KEYLEN);
       !certHasPolicy(cert, DIGI_OID_LIVE_TEST)
       && !certHasPolicy(cert, DIGI_OID_TEST_TEST));
 }
  public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
    calledCheckServerTrusted = true;
    if (!authType.equals("RSA") && !authType.equals("DHE_RSA"))
      throw new CertificateException("Only RSA and DHE_RSA supported, not " + authType);

    if (chain.length != 3) throw new CertificateException("Need three certificates");

    X509Certificate cert0 = chain[0];
    X509Certificate cert1 = chain[1];
    X509Certificate cert2 = chain[2];
    int failedCert = 0;
    try {
      // NOTE: cert0 is a self-signed key used only for SSL
      failedCert = 0;
      cert0.verify(cert0.getPublicKey());
      // NOTE: cert1 is the SSL key signed by the server's Martus key
      failedCert = 1;
      cert1.verify(cert2.getPublicKey());
      // NOTE: cert2 is a self-signed key of and by the server's Martus key
      failedCert = 2;
      cert2.verify(cert2.getPublicKey());
      failedCert = -1;

      PublicKey tryPublicKey = expectedPublicKey;
      if (tryPublicKey == null) {
        if (expectedPublicCode == null) throw new CertificateException("No key or code is trusted");
        String certPublicKeyString = SimpleX509TrustManager.getKeyString(cert2.getPublicKey());
        String certPublicCode = MartusCrypto.computePublicCode(certPublicKeyString);
        if (expectedPublicCode.equals(certPublicCode)) {
          tryPublicKey = cert2.getPublicKey();
        }
      }

      if (tryPublicKey == null) throw new CertificateException("Key is not trusted");
      cert1.verify(tryPublicKey);
      String keyString = SimpleX509TrustManager.getKeyString(tryPublicKey);
      setExpectedPublicKey(keyString);
    } catch (SignatureException e) {
      MartusLogger.logException(e);
      MartusLogger.log("Failed cert: " + failedCert);
      String key0 = SimpleX509TrustManager.getKeyString(cert0.getPublicKey());
      String key1 = SimpleX509TrustManager.getKeyString(cert1.getPublicKey());
      String key2 = SimpleX509TrustManager.getKeyString(cert2.getPublicKey());
      MartusLogger.log("Cert0 public: " + key0);
      if (!key0.equals(key1)) MartusLogger.log("Cert1 public: " + key1);
      MartusLogger.log("Cert2 public: " + key2);
      MartusLogger.log("Cert2 public code: " + MartusCrypto.formatAccountIdForLog(key2));
      String expectedKeyString = SimpleX509TrustManager.getKeyString(expectedPublicKey);
      MartusLogger.log(
          "Expected public code: " + MartusCrypto.formatAccountIdForLog(expectedKeyString));

      throw new CertificateException(e.toString());
    } catch (Exception e) {
      // Tests will cause this to fire
      MartusLogger.logException(e);
      throw new CertificateException(e.toString());
    }
  }
  public void testSubKeyId() throws Exception {
    MimeBodyPart msg = SMIMETestUtil.makeMimeBodyPart("WallaWallaWashington");

    SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();

    //
    // create a subject key id - this has to be done the same way as
    // it is done in the certificate associated with the private key
    //
    MessageDigest dig = MessageDigest.getInstance("SHA1", BC);
    dig.update(
        SubjectPublicKeyInfo.getInstance(_reciCert.getPublicKey().getEncoded())
            .getPublicKeyData()
            .getBytes());

    gen.addRecipientInfoGenerator(
        new JceKeyTransRecipientInfoGenerator(dig.digest(), _reciCert.getPublicKey())
            .setProvider(BC));

    //
    // generate a MimeBodyPart object which encapsulates the content
    // we want encrypted.
    //

    MimeBodyPart mp =
        gen.generate(
            msg,
            new JceCMSContentEncryptorBuilder(CMSAlgorithm.DES_EDE3_CBC).setProvider(BC).build());

    SMIMEEnveloped m = new SMIMEEnveloped(mp);

    dig.update(
        SubjectPublicKeyInfo.getInstance(_reciCert.getPublicKey().getEncoded())
            .getPublicKeyData()
            .getBytes());

    RecipientId recId = new KeyTransRecipientId(dig.digest());

    RecipientInformationStore recipients = m.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    MimeBodyPart res =
        SMIMEUtil.toMimeBodyPart(
            recipient.getContent(
                new JceKeyTransEnvelopedRecipient(_reciKP.getPrivate()).setProvider(BC)));

    verifyMessageBytes(msg, res);
  }
示例#6
0
  /**
   * create from an issuer certificate and the serial number of the certificate it signed.
   *
   * @exception OCSPException if any problems occur creating the id fields.
   */
  public CertificateID(
      String hashAlgorithm, X509Certificate issuerCert, BigInteger number, String provider)
      throws OCSPException {
    try {
      MessageDigest digest = MessageDigest.getInstance(hashAlgorithm, provider);
      AlgorithmIdentifier hashAlg =
          new AlgorithmIdentifier(new DERObjectIdentifier(hashAlgorithm), new DERNull());

      X509Principal issuerName = PrincipalUtil.getSubjectX509Principal(issuerCert);

      digest.update(issuerName.getEncoded());

      ASN1OctetString issuerNameHash = new DEROctetString(digest.digest());
      PublicKey issuerKey = issuerCert.getPublicKey();

      ASN1InputStream aIn = new ASN1InputStream(issuerKey.getEncoded());
      SubjectPublicKeyInfo info = SubjectPublicKeyInfo.getInstance(aIn.readObject());

      digest.update(info.getPublicKeyData().getBytes());

      ASN1OctetString issuerKeyHash = new DEROctetString(digest.digest());

      DERInteger serialNumber = new DERInteger(number);

      this.id = new CertID(hashAlg, issuerNameHash, issuerKeyHash, serialNumber);
    } catch (Exception e) {
      throw new OCSPException("problem creating ID: " + e, e);
    }
  }
示例#7
0
  private int getAsymmetricKeyLength(X509Certificate certificate) {
    PublicKey publicKey = certificate != null ? certificate.getPublicKey() : null;

    return (publicKey instanceof RSAPublicKey)
        ? ((RSAPublicKey) publicKey).getModulus().bitLength()
        : 0;
  }
 @Test(expected = IllegalArgumentException.class)
 public void testWithNullForPrivateKey()
     throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
         NoSuchProviderException, UnrecoverableEntryException, IOException {
   HybridCrypto hybridCrypto =
       new HybridCrypto(SecurityProviderConnectorFactory.getSecurityProviderConnector());
   Certificates certificates =
       new Certificates(SecurityProviderConnectorFactory.getSecurityProviderConnector());
   StringWriter stringWriter = new StringWriter();
   ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
   String id = "test";
   char[] password = "******".toCharArray();
   X509Certificate cert = certificates.create(id, password, stringWriter, byteArrayOutputStream);
   hybridCrypto.addRecipient("test", cert);
   String message = "I am hybrid encrypted!";
   HybridEncrypted hybridEncrypted =
       hybridCrypto.build(
           message.getBytes(),
           new PrivateKeyExtractor()
               .extractPrivateKey(
                   password, new ByteArrayInputStream(byteArrayOutputStream.toByteArray())));
   HybridCrypto freshHybridCrypto =
       new HybridCrypto(SecurityProviderConnectorFactory.getSecurityProviderConnector());
   byte[] decryptedMessage = freshHybridCrypto.decrypt(hybridEncrypted, id, null);
   Assert.assertArrayEquals(message.getBytes(), decryptedMessage);
   Signature signature =
       new Signature(SecurityProviderConnectorFactory.getSecurityProviderConnector());
   Assert.assertTrue(
       signature.verify(
           hybridEncrypted.getEncryptedBody(),
           hybridEncrypted.getSignature(),
           cert.getPublicKey()));
 }
  /**
   * Method engineResolvePublicKey
   *
   * @inheritDoc
   * @param element
   * @param BaseURI
   * @param storage
   */
  public PublicKey engineLookupAndResolvePublicKey(
      Element element, String BaseURI, StorageResolver storage) {
    if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) {
      return null;
    }

    try {
      // Create a retrieval method over the given element
      RetrievalMethod rm = new RetrievalMethod(element, BaseURI);
      String type = rm.getType();
      XMLSignatureInput resource = resolveInput(rm, BaseURI);
      if (RetrievalMethod.TYPE_RAWX509.equals(type)) {
        // a raw certificate, direct parsing is done!
        X509Certificate cert = getRawCertificate(resource);
        if (cert != null) {
          return cert.getPublicKey();
        }
        return null;
      }
      ;
      Element e = obtainRefrenceElement(resource);
      return resolveKey(e, BaseURI, storage);
    } catch (XMLSecurityException ex) {
      log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex);
    } catch (CertificateException ex) {
      log.log(java.util.logging.Level.FINE, "CertificateException", ex);
    } catch (IOException ex) {
      log.log(java.util.logging.Level.FINE, "IOException", ex);
    } catch (ParserConfigurationException e) {
      log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e);
    } catch (SAXException e) {
      log.log(java.util.logging.Level.FINE, "SAXException", e);
    }
    return null;
  }
示例#10
0
  private X509CRL checkAndExtractCRL(TrustedAuthority ta, X509Certificate signer)
      throws IllegalTrustedAuthorityFault {
    X509CRL crl = null;
    if (ta.getCRL() != null) {

      if (ta.getCRL().getCrlEncodedString() != null) {
        try {
          crl = CertUtil.loadCRL(ta.getCRL().getCrlEncodedString());
        } catch (Exception ex) {
          IllegalTrustedAuthorityFault fault = new IllegalTrustedAuthorityFault();
          fault.setFaultString("Invalid CRL provided!!!");
          throw fault;
        }
        try {
          crl.verify(signer.getPublicKey());
        } catch (Exception e) {
          IllegalTrustedAuthorityFault fault = new IllegalTrustedAuthorityFault();
          fault.setFaultString("The CRL provided is not signed by the Trusted Authority!!!");
          throw fault;
        }
      }
    }

    return crl;
  }
示例#11
0
  public void testProtectedMessage() throws Exception {
    KeyPairGenerator kGen = KeyPairGenerator.getInstance("RSA", BC);

    kGen.initialize(512);

    KeyPair kp = kGen.generateKeyPair();
    X509CertificateHolder cert = makeV3Certificate(kp, "CN=Test", kp, "CN=Test");

    GeneralName sender = new GeneralName(new X500Name("CN=Sender"));
    GeneralName recipient = new GeneralName(new X500Name("CN=Recip"));

    ContentSigner signer =
        new JcaContentSignerBuilder("MD5WithRSAEncryption").setProvider(BC).build(kp.getPrivate());
    ProtectedPKIMessage message =
        new ProtectedPKIMessageBuilder(sender, recipient)
            .setBody(
                new PKIBody(
                    PKIBody.TYPE_INIT_REP,
                    CertRepMessage.getInstance(new DERSequence(new DERSequence()))))
            .addCMPCertificate(cert)
            .build(signer);

    X509Certificate jcaCert =
        new JcaX509CertificateConverter()
            .setProvider(BC)
            .getCertificate(message.getCertificates()[0]);
    ContentVerifierProvider verifierProvider =
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(jcaCert.getPublicKey());

    assertTrue(message.verify(verifierProvider));

    assertEquals(sender, message.getHeader().getSender());
    assertEquals(recipient, message.getHeader().getRecipient());
  }
示例#12
0
 public String encryptRSA(String toEncrypt) throws Exception {
   Cipher cipher = Cipher.getInstance("RSA");
   PublicKey pubKey = x509.getPublicKey();
   cipher.init(Cipher.ENCRYPT_MODE, pubKey);
   byte[] encryptedBytes = cipher.doFinal(toEncrypt.getBytes("UTF-8"));
   return Base64.encodeBase64String(encryptedBytes);
 }
  /**
   * java.security.KeyStore#setCertificateEntry(java.lang.String, java.security.cert.Certificate)
   */
  public void test_setCertificateEntryLjava_lang_StringLjava_security_cert_Certificate()
      throws Exception {
    // Test for method void
    // java.security.KeyStore.setCertificateEntry(java.lang.String,
    // java.security.cert.Certificate)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(certArray);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.setCertificateEntry("alias", cert);
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, null);

    PublicKey pub = cert.getPublicKey();
    keyTest.setCertificateEntry("alias1", cert);
    assertTrue(
        "the entry specified by the alias alias1 is not a certificate",
        keyTest.isCertificateEntry("alias1"));
    Certificate resultCert = keyTest.getCertificate("alias1");
    assertEquals(
        "the public key of the certificate from getCertificate() "
            + "did not equal the original certificate",
        pub,
        resultCert.getPublicKey());
  }
  /**
   * Add a recipient based on the passed in certificate's public key and its issuer and serial
   * number.
   *
   * @param recipientCert recipient's certificate
   * @return the current instance.
   * @throws CertificateEncodingException if the necessary data cannot be extracted from the
   *     certificate.
   */
  public JceKeyAgreeRecipientInfoGenerator addRecipient(X509Certificate recipientCert)
      throws CertificateEncodingException {
    recipientIDs.add(
        new KeyAgreeRecipientIdentifier(CMSUtils.getIssuerAndSerialNumber(recipientCert)));
    recipientKeys.add(recipientCert.getPublicKey());

    return this;
  }
  /**
   * Extracts the presenter's key and/or certificate from the validation context.
   *
   * @param context current validation context
   * @return the presenter's key/cert pair, information not available in the context is null
   * @throws AssertionValidationException thrown if there is a problem obtaining the data
   */
  @Nonnull
  protected Pair<PublicKey, X509Certificate> getKeyAndCertificate(
      @Nonnull final ValidationContext context) throws AssertionValidationException {
    PublicKey presenterKey = null;
    try {
      presenterKey =
          (PublicKey)
              context
                  .getStaticParameters()
                  .get(SAML2AssertionValidationParameters.SC_HOK_PRESENTER_KEY);
    } catch (ClassCastException e) {
      throw new IllegalArgumentException(
          String.format(
              "The value of the static validation parameter '%s' was not of the required type '%s'",
              SAML2AssertionValidationParameters.SC_HOK_PRESENTER_KEY, PublicKey.class.getName()));
    }

    X509Certificate presenterCert = null;
    try {
      presenterCert =
          (X509Certificate)
              context
                  .getStaticParameters()
                  .get(SAML2AssertionValidationParameters.SC_HOK_PRESENTER_CERT);
      if (presenterCert != null) {
        if (presenterKey != null) {
          if (!presenterKey.equals(presenterCert.getPublicKey())) {
            throw new IllegalArgumentException(
                "Presenter's certificate contains a different public key "
                    + "than the one explicitly given");
          }
        } else {
          presenterKey = presenterCert.getPublicKey();
        }
      }
    } catch (ClassCastException e) {
      throw new IllegalArgumentException(
          String.format(
              "The value of the static validation parameter '%s' was not of the required type '%s'",
              SAML2AssertionValidationParameters.SC_HOK_PRESENTER_CERT,
              X509Certificate.class.getName()));
    }

    return new Pair<>(presenterKey, presenterCert);
  }
示例#16
0
 @Override
 public PublicKey getUserPublicKey() {
   X509Certificate x509Certificate = getUserX509Certificate();
   if (x509Certificate == null) {
     return null;
   } else {
     return x509Certificate.getPublicKey();
   }
 }
示例#17
0
 public static PublicKey getEncryptCertPublicKey() {
   try {
     if (null == encryptCert) initEncryptCert();
     return encryptCert.getPublicKey();
   } catch (Exception e) {
     logger.error(e.getMessage());
   }
   return null;
 }
  /**
   * Method getPublicKey
   *
   * @return the publickey
   * @throws XMLSecurityException
   */
  public PublicKey getPublicKey() throws XMLSecurityException {
    X509Certificate cert = this.getX509Certificate();

    if (cert != null) {
      return cert.getPublicKey();
    }

    return null;
  }
 private static String getFingerprint(X509Certificate cert) {
   try {
     MessageDigest dgst = MessageDigest.getInstance("SHA512");
     byte[] encoded = cert.getPublicKey().getEncoded();
     byte[] fingerprint = dgst.digest(encoded);
     return IntegralToString.bytesToHexString(fingerprint, false);
   } catch (NoSuchAlgorithmException e) {
     throw new AssertionError(e);
   }
 }
 public void testSignatureVerificationRoundtrip() throws Exception {
   String signatureBaseString =
       "GET&https%3A%2F%2Fcheetah.dhcp.pgdev.sap.corp%2Foauth%2Ftest_consumer_request&oauth_consumer_key%3D1VMzOctCAidMaahS9yJU%26oauth_nonce%3DNtX9Gah3Bw%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1307748357%26oauth_token%3D%26oauth_version%3D1.0";
   String signature =
       OAuthUtils.calculateRsaSha1Signature(signatureBaseString, TEST_CONSUMER_PRIVATE_KEY);
   boolean valid =
       OAuthUtils.verifyRsaSha1Signature(
           TEST_CONSUMER_CERTIFICATE.getPublicKey(), signature, signatureBaseString);
   assertTrue(valid);
 }
  private static ASN1Sequence fromCertificate(X509Certificate certificate)
      throws CertificateParsingException {
    try {
      if (certificate.getVersion() != 3) {
        GeneralName genName = new GeneralName(PrincipalUtil.getIssuerX509Principal(certificate));
        SubjectPublicKeyInfo info =
            new SubjectPublicKeyInfo(
                (ASN1Sequence)
                    new ASN1InputStream(certificate.getPublicKey().getEncoded()).readObject());

        return (ASN1Sequence)
            new AuthorityKeyIdentifier(
                    info, new GeneralNames(genName), certificate.getSerialNumber())
                .toASN1Object();
      } else {
        GeneralName genName = new GeneralName(PrincipalUtil.getIssuerX509Principal(certificate));

        byte[] ext = certificate.getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId());

        if (ext != null) {
          ASN1OctetString str = (ASN1OctetString) X509ExtensionUtil.fromExtensionValue(ext);

          return (ASN1Sequence)
              new AuthorityKeyIdentifier(
                      str.getOctets(), new GeneralNames(genName), certificate.getSerialNumber())
                  .toASN1Object();
        } else {
          SubjectPublicKeyInfo info =
              new SubjectPublicKeyInfo(
                  (ASN1Sequence)
                      new ASN1InputStream(certificate.getPublicKey().getEncoded()).readObject());

          return (ASN1Sequence)
              new AuthorityKeyIdentifier(
                      info, new GeneralNames(genName), certificate.getSerialNumber())
                  .toASN1Object();
        }
      }
    } catch (Exception e) {
      throw new CertificateParsingException(
          "Exception extracting certificate details: " + e.toString());
    }
  }
示例#22
0
  /**
   * verify that the given certificate successfully handles and confirms the signature associated
   * with this signer and, if a signingTime attribute is available, that the certificate was valid
   * at the time the signature was generated.
   *
   * @deprecated use verify(ContentVerifierProvider)
   */
  public boolean verify(X509Certificate cert, Provider sigProvider)
      throws NoSuchAlgorithmException, CertificateExpiredException, CertificateNotYetValidException,
          CMSException {
    Time signingTime = getSigningTime();
    if (signingTime != null) {
      cert.checkValidity(signingTime.getDate());
    }

    return doVerify(cert.getPublicKey(), sigProvider);
  }
  /**
   * Method engineResolvePublicKey
   *
   * @param element
   * @param BaseURI
   * @param storage
   * @return null if no {@link PublicKey} could be obtained
   * @throws KeyResolverException
   */
  public PublicKey engineLookupAndResolvePublicKey(
      Element element, String BaseURI, StorageResolver storage) throws KeyResolverException {

    X509Certificate cert = this.engineLookupResolveX509Certificate(element, BaseURI, storage);

    if (cert != null) {
      return cert.getPublicKey();
    }

    return null;
  }
 /**
  * Resets the PKCS7SignedData object to it's initial state, ready to sign or verify a new buffer.
  */
 public void reset() {
   try {
     if (privKey == null) {
       sig.initVerify(signCert.getPublicKey());
     } else {
       sig.initSign(privKey);
     }
   } catch (Exception e) {
     throw new RuntimeException(e.toString());
   }
 }
  protected void getClientPublicKey(byte[] clpubkey) throws Exception {
    DERObject obj = BouncyCastleUtil.toDERObject(clpubkey);
    byte[] pubkey = BouncyCastleUtil.toByteArray(obj);
    ByteArrayInputStream in = new ByteArrayInputStream(pubkey);
    X509Certificate cert = CertUtil.loadCertificate(in);

    SCUtil.pathValidation(cert, trustedCerts);
    logger.finest("path validated !!!");

    clPubkey = cert.getPublicKey();
  }
  private X509Certificate generateCertificate(
      PublicKey subjectPublicKey,
      String subjectDn,
      DateTime notBefore,
      DateTime notAfter,
      X509Certificate issuerCertificate,
      PrivateKey issuerPrivateKey)
      throws Exception {

    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    certificateGenerator.reset();
    certificateGenerator.setPublicKey(subjectPublicKey);
    certificateGenerator.setSignatureAlgorithm("SHA1WithRSAEncryption");
    certificateGenerator.setNotBefore(notBefore.toDate());
    certificateGenerator.setNotAfter(notAfter.toDate());

    X509Principal issuerDN;
    if (null != issuerCertificate) {
      issuerDN = new X509Principal(issuerCertificate.getSubjectX500Principal().toString());
    } else {
      issuerDN = new X509Principal(subjectDn);
    }
    certificateGenerator.setIssuerDN(issuerDN);
    certificateGenerator.setSubjectDN(new X509Principal(subjectDn));
    certificateGenerator.setSerialNumber(new BigInteger(128, new SecureRandom()));

    certificateGenerator.addExtension(
        X509Extensions.SubjectKeyIdentifier, false, createSubjectKeyId(subjectPublicKey));

    PublicKey issuerPublicKey;
    if (null != issuerCertificate) {
      issuerPublicKey = issuerCertificate.getPublicKey();
    } else {
      issuerPublicKey = subjectPublicKey;
    }
    certificateGenerator.addExtension(
        X509Extensions.AuthorityKeyIdentifier, false, createAuthorityKeyId(issuerPublicKey));

    X509Certificate certificate;
    certificate = certificateGenerator.generate(issuerPrivateKey);

    /*
     * Next certificate factory trick is needed to make sure that the
     * certificate delivered to the caller is provided by the default
     * security provider instead of BouncyCastle. If we don't do this trick
     * we might run into trouble when trying to use the CertPath validator.
     */
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    certificate =
        (X509Certificate)
            certificateFactory.generateCertificate(
                new ByteArrayInputStream(certificate.getEncoded()));
    return certificate;
  }
示例#27
0
 private void verify(X509Certificate[] certs, String authType) throws CertificateException {
   final int len = certs.length;
   for (int i = 0; i < len; i++) {
     final X509Certificate currentX509Cert = certs[i];
     try {
       if (i == len - 1) {
         if (currentX509Cert.getSubjectDN().equals(currentX509Cert.getIssuerDN()))
           currentX509Cert.verify(currentX509Cert.getPublicKey());
       } else {
         final X509Certificate nextX509Cert = certs[i + 1];
         currentX509Cert.verify(nextX509Cert.getPublicKey());
       }
     } catch (final Exception e) {
       final CertificateException ce =
           new ECFCertificateException(
               "Certificate chain is not valid", certs, authType); // $NON-NLS-1$
       ce.initCause(e);
       throw ce;
     }
   }
 }
  private static boolean isValidLink(X509Certificate parent, X509Certificate child) {
    if (!parent.getSubjectX500Principal().equals(child.getIssuerX500Principal())) {
      return false;
    }

    try {
      child.verify(parent.getPublicKey());
    } catch (GeneralSecurityException gse) {
      return false;
    }

    return true;
  }
示例#29
0
  public static void geneneratePublicKey() throws Exception {
    String file = "C:\\ca\\client\\test02.der";
    //    	String key = getPrivateKey("C:\\ca\\client\\test02.der");
    FileInputStream inpri = new FileInputStream(file);
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    X509Certificate c = (X509Certificate) cf.generateCertificate(inpri);
    System.out.println(c.getPublicKey());

    //        KeySpec keySpec = new X509EncodedKeySpec(key.getBytes());
    //        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    //        PublicKey pk = keyFactory.generatePublic(keySpec);
    //        System.out.println(pk);
  }
示例#30
0
 public static boolean isRootCA(X509Certificate cert) {
   boolean ret = false;
   try {
     cert.verify(cert.getPublicKey());
     ret = true;
   } catch (InvalidKeyException e) {
   } catch (CertificateException e) {
   } catch (NoSuchAlgorithmException e) {
   } catch (NoSuchProviderException e) {
   } catch (SignatureException e) {
   }
   return ret;
 }