public int compare(Object o1, Object o2) {
   X509Certificate c1 = (X509Certificate) o1;
   X509Certificate c2 = (X509Certificate) o2;
   if (c1 == c2) // this deals with case where both are null
   {
     return 0;
   }
   if (c1 == null) // non-null is always bigger than null
   {
     return -1;
   }
   if (c2 == null) {
     return 1;
   }
   if (c1.equals(c2)) {
     return 0;
   }
   Date d1 = c1.getNotAfter();
   Date d2 = c2.getNotAfter();
   int c = d1.compareTo(d2);
   if (c == 0) {
     String s1 = JavaImpl.getSubjectX500(c1);
     String s2 = JavaImpl.getSubjectX500(c2);
     c = s1.compareTo(s2);
     if (c == 0) {
       s1 = JavaImpl.getIssuerX500(c1);
       s2 = JavaImpl.getIssuerX500(c2);
       c = s1.compareTo(s2);
       if (c == 0) {
         BigInteger big1 = c1.getSerialNumber();
         BigInteger big2 = c2.getSerialNumber();
         c = big1.compareTo(big2);
         if (c == 0) {
           try {
             byte[] b1 = c1.getEncoded();
             byte[] b2 = c2.getEncoded();
             int len1 = b1.length;
             int len2 = b2.length;
             int i = 0;
             for (; i < len1 && i < len2; i++) {
               c = ((int) b1[i]) - ((int) b2[i]);
               if (c != 0) {
                 break;
               }
             }
             if (c == 0) {
               c = b1.length - b2.length;
             }
           } catch (CertificateEncodingException cee) {
             // I give up.  They can be equal if they
             // really want to be this badly.
             c = 0;
           }
         }
       }
     }
   }
   return c;
 }
Ejemplo n.º 2
0
 /**
  * Creates a new certificate ID instance (using SHA-1 digest calculator) for the specified subject
  * certificate serial number and issuer certificate.
  *
  * @param subjectSerialNumber the subject certificate serial number
  * @param issuer the issuer certificate
  * @return the certificate id
  * @throws Exception if the certificate if cannot be created
  */
 public static CertificateID createCertId(BigInteger subjectSerialNumber, X509Certificate issuer)
     throws Exception {
   return new CertificateID(
       createDigestCalculator(SHA1_ID),
       new X509CertificateHolder(issuer.getEncoded()),
       subjectSerialNumber);
 }
Ejemplo n.º 3
0
  public void ready(String name, PrivateKey unusedPrivateKey, X509Certificate certificate) {
    String status;
    try {
      vaadin.updateVariable("cert", printBase64Binary(certificate.getEncoded()));
      status = "Готово.";
    } catch (CertificateEncodingException e) {
      status = "Ошибка.";
    }

    ui.removeAll();
    ui.add(new Label(name), BorderLayout.PAGE_START);
    ui.add(new Label(status), BorderLayout.CENTER);

    Button cancel = new Button("Отменить");
    cancel.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            loading();
          }
        });
    Panel buttons = new Panel(new BorderLayout(2, 2));
    buttons.add(cancel, BorderLayout.LINE_START);
    ui.add(buttons, BorderLayout.PAGE_END);
    refresh();
  }
  public void checkRequestResponseIntegrity(
      SignatureRequestEncoder sreqenc, X509Certificate server_certificate) throws IOException {
    // The DocumentData object
    if (sreqenc.copy_data) {
      if (doc_data == null) bad("Missing DocumentData");
      if (!sreqenc.document_data.equals(doc_data)) bad("DocumentData mismatch");
    } else if (doc_data != null) bad("Unexpected DocumentData");
    byte[] expected_fingerprint = null;
    if (server_certificate != null) {
      try {
        expected_fingerprint = HashAlgorithms.SHA256.digest(server_certificate.getEncoded());
      } catch (GeneralSecurityException e) {
        throw new IOException(e);
      }
    }

    // For each candidate profile do a match try
    for (SignatureProfileEncoder spe : sreqenc.signature_profiles) {
      if (sign_prof_data.match(
          spe,
          sreqenc.document_data,
          sreqenc.document_references,
          sreqenc.certificate_filters,
          sreqenc.id,
          expected_fingerprint)) {
        return;
      }
    }
    throw new IOException("Mismatch between signature request and response");
  }
  public DEPExportFormat exportDEP() {
    try {
      // prepare data structures for DEP export
      // DEP exports are grouped according to the used signature certificate (CURRENTLY NOT USED IN
      // THE DEMO)
      HashMap<String, List<ReceiptPackage>> certificateToReceiptMap = new HashMap<>();

      for (ReceiptPackage receiptPackage : receiptPackages) {
        X509Certificate signingCertificate = receiptPackage.getSigningCertificate();
        List<ReceiptPackage> receiptPackagesForSignatureCertificate =
            certificateToReceiptMap.get(signingCertificate.getSerialNumber() + "");
        if (receiptPackagesForSignatureCertificate == null) {
          receiptPackagesForSignatureCertificate = new ArrayList<>();
          certificateToReceiptMap.put(
              signingCertificate.getSerialNumber() + "", receiptPackagesForSignatureCertificate);
        }
        receiptPackagesForSignatureCertificate.add(receiptPackage);
      }

      // create data structure for export format
      DEPExportFormat depExportFormat = new DEPExportFormat();
      DEPBelegDump[] belegDump = new DEPBelegDump[certificateToReceiptMap.keySet().size()];

      // store receipts in export format
      int dumpIndex = 0;
      for (List<ReceiptPackage> signedReceipts : certificateToReceiptMap.values()) {
        belegDump[dumpIndex] = new DEPBelegDump();
        depExportFormat.setBelegPackage(belegDump);

        List<String> receiptsInJWSCompactRepresentation = new ArrayList<>();
        for (ReceiptPackage receiptPackage : signedReceipts) {
          receiptsInJWSCompactRepresentation.add(receiptPackage.getJwsCompactRepresentation());
        }
        belegDump[dumpIndex].setBelegeDaten(
            receiptsInJWSCompactRepresentation.toArray(
                new String[receiptsInJWSCompactRepresentation.size()]));

        String base64EncodedSignatureCertificate =
            CashBoxUtils.base64Encode(
                signedReceipts.get(0).getSigningCertificate().getEncoded(), false);
        belegDump[dumpIndex].setSignatureCertificate(base64EncodedSignatureCertificate);

        List<X509Certificate> base64EncodedCertificateChain =
            signedReceipts.get(0).getCertificateChain();
        String[] certificateChain = new String[base64EncodedCertificateChain.size()];
        for (int i = 0; i < base64EncodedCertificateChain.size(); i++) {
          X509Certificate base64EncodedChainCertificate = base64EncodedCertificateChain.get(i);
          certificateChain[i] =
              CashBoxUtils.base64Encode(base64EncodedChainCertificate.getEncoded(), false);
        }
        belegDump[dumpIndex].setCertificateChain(certificateChain);

        dumpIndex++;
      }
      return depExportFormat;
    } catch (CertificateEncodingException e) {
      e.printStackTrace();
    }
    return null;
  }
Ejemplo n.º 6
0
  protected PropertyDataObject generate(
      Collection<X509Certificate> certs, BaseCertRefsData certRefsData, QualifyingProperty prop)
      throws PropertyDataGenerationException {
    if (null == certs) {
      throw new PropertyDataGenerationException(prop, "certificates not provided");
    }

    try {
      String digestAlgUri = this.algorithmsProvider.getDigestAlgorithmForReferenceProperties();
      MessageDigest messageDigest = this.messageDigestProvider.getEngine(digestAlgUri);

      for (X509Certificate cert : certs) {
        // "DigestValue contains the base-64 encoded value of the digest
        // computed on the DER-encoded certificate."
        // The base-64 encoding is done by JAXB with the configured
        // adapter (Base64XmlAdapter).
        // For X509 certificates the encoded form return by getEncoded is DER.
        byte[] digestValue = messageDigest.digest(cert.getEncoded());

        certRefsData.addCertRef(
            new CertRef(
                cert.getIssuerX500Principal().getName(),
                cert.getSerialNumber(),
                digestAlgUri,
                digestValue));
      }
      return certRefsData;

    } catch (UnsupportedAlgorithmException ex) {
      throw new PropertyDataGenerationException(prop, ex.getMessage(), ex);
    } catch (CertificateEncodingException ex) {
      throw new PropertyDataGenerationException(prop, "cannot get encoded certificate", ex);
    }
  }
Ejemplo n.º 7
0
  /**
   * Encode the CertPath using PKIPATH format.
   *
   * @return a byte array containing the binary encoding of the PkiPath object
   * @exception CertificateEncodingException if an exception occurs
   */
  private byte[] encodePKIPATH() throws CertificateEncodingException {

    ListIterator<X509Certificate> li = certs.listIterator(certs.size());
    try {
      DerOutputStream bytes = new DerOutputStream();
      // encode certs in reverse order (trust anchor to target)
      // according to PkiPath format
      while (li.hasPrevious()) {
        X509Certificate cert = li.previous();
        // check for duplicate cert
        if (certs.lastIndexOf(cert) != certs.indexOf(cert)) {
          throw new CertificateEncodingException("Duplicate Certificate");
        }
        // get encoded certificates
        byte[] encoded = cert.getEncoded();
        bytes.write(encoded);
      }

      // Wrap the data in a SEQUENCE
      DerOutputStream derout = new DerOutputStream();
      derout.write(DerValue.tag_SequenceOf, bytes);
      return derout.toByteArray();

    } catch (IOException ioe) {
      throw new CertificateEncodingException("IOException encoding " + "PkiPath data: " + ioe, ioe);
    }
  }
Ejemplo n.º 8
0
 /**
  * Return a DERObject containing the encoded certificate.
  *
  * @param cert the X509Certificate object to be encoded
  * @return the DERObject
  */
 private ASN1Primitive toASN1Object(X509Certificate cert) throws CertificateEncodingException {
   try {
     return new ASN1InputStream(cert.getEncoded()).readObject();
   } catch (Exception e) {
     throw new CertificateEncodingException(
         "Exception while encoding certificate: " + e.toString());
   }
 }
 public static void testcaV3() throws Exception {
   KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
   kpg.initialize(2048);
   KeyPair keyPair = kpg.generateKeyPair();
   X509Certificate cer = buildCARootCertV3(keyPair);
   FileUtils.writeByteArrayToFile(new File("d:\\caV3.cer"), cer.getEncoded());
   System.out.println(cer);
 }
Ejemplo n.º 10
0
  /* Translate to encoded bytes */
  private void emit(DerOutputStream out) throws IOException, CertificateEncodingException {
    DerOutputStream tagged = new DerOutputStream();

    if (forward != null) {
      DerOutputStream tmp = new DerOutputStream();
      tmp.putDerValue(new DerValue(forward.getEncoded()));
      tagged.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, TAG_FORWARD), tmp);
    }

    if (reverse != null) {
      DerOutputStream tmp = new DerOutputStream();
      tmp.putDerValue(new DerValue(reverse.getEncoded()));
      tagged.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, TAG_REVERSE), tmp);
    }

    out.write(DerValue.tag_Sequence, tagged);
  }
 @Override
 public String toConfigNode(X509Certificate object, ConfigProperty property, SavingContext ctx)
     throws ConfigurationException {
   try {
     return Base64.toBase64(object.getEncoded());
   } catch (CertificateEncodingException e) {
     throw new ConfigurationException("Cannot encode X509 certificate", e);
   }
 }
Ejemplo n.º 12
0
  public void testSHA1WithRSAStream() throws Exception {
    List certList = new ArrayList();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    certList.add(new X509CertificateHolder(keyCert.getEncoded()));

    DigestCalculatorProvider digCalcProv = new JcaDigestCalculatorProviderBuilder().build();

    CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator();

    gen.addSignerInfoGenerator(
        new JcaSignerInfoGeneratorBuilder(digCalcProv)
            .build(
                new JcaContentSignerBuilder("SHA1withRSA").build(keyPair.getPrivate()), keyCert));

    gen.addCertificates(new CollectionStore(certList));

    OutputStream sigOut = gen.open(bOut);

    sigOut.write(TEST_MESSAGE.getBytes());

    sigOut.close();

    CMSSignedDataParser sp =
        new CMSSignedDataParser(
            digCalcProv,
            new CMSTypedStream(new ByteArrayInputStream(TEST_MESSAGE.getBytes())),
            bOut.toByteArray());

    sp.getSignedContent().drain();

    //
    // compute expected content digest
    //
    MessageDigest md = MessageDigest.getInstance("SHA1");

    byte[] contentDigest = md.digest(TEST_MESSAGE.getBytes());
    Store certStore = sp.getCertificates();
    SignerInformationStore signers = sp.getSignerInfos();

    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    while (it.hasNext()) {
      SignerInformation signer = (SignerInformation) it.next();
      Collection certCollection = certStore.getMatches(signer.getSID());

      Iterator certIt = certCollection.iterator();
      X509CertificateHolder cert = (X509CertificateHolder) certIt.next();

      assertEquals(true, signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert)));

      if (contentDigest != null) {
        assertTrue(MessageDigest.isEqual(contentDigest, signer.getContentDigest()));
      }
    }
  }
Ejemplo n.º 13
0
 private static byte[] getEncoded(X509Certificate cert) throws IOException {
   if (cert != null) {
     try {
       return cert.getEncoded();
     } catch (GeneralSecurityException gse) {
       throw new IOException("problem with encoding object in write_X509");
     }
   }
   return new byte[] {'0', 0};
 }
Ejemplo n.º 14
0
 public static void exportCert(X509Certificate cert, String name, String path) throws Exception {
   File dir = new File(path);
   if (!dir.exists()) {
     dir.mkdir();
   }
   File certFile = new File(path + File.separator + name + ".cer");
   FileOutputStream fos = new FileOutputStream(certFile);
   fos.write(cert.getEncoded());
   fos.close();
 }
  /**
   * Constructor XMLX509Certificate
   *
   * @param doc
   * @param x509certificate
   * @throws XMLSecurityException
   */
  public XMLX509Certificate(Document doc, X509Certificate x509certificate)
      throws XMLSecurityException {
    super(doc);

    try {
      this.addBase64Text(x509certificate.getEncoded());
    } catch (java.security.cert.CertificateEncodingException ex) {
      throw new XMLSecurityException("empty", ex);
    }
  }
 private String getFingerprint(X509Certificate certificate) {
   try {
     MessageDigest sha1 = MessageDigest.getInstance("SHA1");
     sha1.update(certificate.getEncoded());
     return toHexString(sha1.digest());
   } catch (NoSuchAlgorithmException e) {
     return "<Could not determine fingerprint>";
   } catch (CertificateEncodingException e) {
     return "<Could not determine fingerprint>";
   }
 }
  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;
  }
Ejemplo n.º 18
0
 // Converts to javax.security
 public static javax.security.cert.X509Certificate convert(
     java.security.cert.X509Certificate cert) {
   try {
     byte[] encoded = cert.getEncoded();
     return javax.security.cert.X509Certificate.getInstance(encoded);
   } catch (java.security.cert.CertificateEncodingException e) {
   } catch (javax.security.cert.CertificateEncodingException e) {
   } catch (javax.security.cert.CertificateException e) {
   }
   return null;
 }
 private static String certHash(final X509Certificate cert, String digest) {
   try {
     MessageDigest md = MessageDigest.getInstance(digest);
     md.update(cert.getEncoded());
     return hexString(md.digest());
   } catch (java.security.cert.CertificateEncodingException e) {
     return e.getMessage();
   } catch (java.security.NoSuchAlgorithmException e) {
     return e.getMessage();
   }
 }
Ejemplo n.º 20
0
 private static String getCertFingerprint(byte[] certData) {
   try {
     CertificateFactory x509CertFact = CertificateFactory.getInstance("X.509");
     X509Certificate cert =
         (X509Certificate) x509CertFact.generateCertificate(new ByteArrayInputStream(certData));
     MessageDigest md = MessageDigest.getInstance("SHA-1");
     return toHexString(md.digest(cert.getEncoded()));
   } catch (CertificateException e) {
     throw new RuntimeException(e);
   } catch (NoSuchAlgorithmException e) {
     throw new RuntimeException(e);
   }
 }
Ejemplo n.º 21
0
  public void testAES256CCM() throws Exception {
    byte[] data = "Eric H. Echidna".getBytes();
    ASN1ObjectIdentifier macAlg = CMSAlgorithm.AES256_CCM;
    AlgorithmParameters algParams = AlgorithmParameters.getInstance("CCM", BC);

    algParams.init(new CCMParameters(Hex.decode("000102030405060708090a0b"), 16).getEncoded());

    CMSAuthenticatedDataGenerator adGen = new CMSAuthenticatedDataGenerator();

    X509CertificateHolder origCert = new X509CertificateHolder(_origCert.getEncoded());

    adGen.setOriginatorInfo(new OriginatorInfoGenerator(origCert).generate());

    adGen.addRecipientInfoGenerator(
        new JceKeyTransRecipientInfoGenerator(_reciCert).setProvider(BC));

    CMSAuthenticatedData ad =
        adGen.generate(
            new CMSProcessableByteArray(data),
            new JceCMSMacCalculatorBuilder(macAlg)
                .setAlgorithmParameters(algParams)
                .setProvider(BC)
                .build());

    assertTrue(ad.getOriginatorInfo().getCertificates().getMatches(null).contains(origCert));

    RecipientInformationStore recipients = ad.getRecipientInfos();

    assertEquals(ad.getMacAlgOID(), macAlg.getId());

    Collection c = recipients.getRecipients();

    assertEquals(1, c.size());

    Iterator it = c.iterator();

    while (it.hasNext()) {
      RecipientInformation recipient = (RecipientInformation) it.next();

      assertEquals(recipient.getKeyEncryptionAlgOID(), PKCSObjectIdentifiers.rsaEncryption.getId());

      byte[] recData =
          recipient.getContent(
              new JceKeyTransAuthenticatedRecipient(_reciKP.getPrivate()).setProvider(BC));

      assertTrue(Arrays.equals(data, recData));
      assertEquals(16, ad.getMac().length);
      assertTrue(Arrays.equals(ad.getMac(), recipient.getMac()));
    }
  }
Ejemplo n.º 22
0
  public static byte[] parseSignature(byte[] signature) {
    byte[] buffer = null;
    try {
      CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
      X509Certificate cert =
          (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(signature));
      buffer = cert.getEncoded();

    } catch (Exception e) {
      e.printStackTrace();
    }

    return buffer;
  }
Ejemplo n.º 23
0
  private JAXBElement<BinarySecurityTokenType> createBinarySecurityToken(X509Certificate cert)
      throws Exception {
    BinarySecurityTokenType binarySecurityToken = new BinarySecurityTokenType();
    binarySecurityToken.setValue(Base64.getMimeEncoder().encodeToString(cert.getEncoded()));
    binarySecurityToken.setValueType(X509TokenValidator.X509_V3_TYPE);
    binarySecurityToken.setEncodingType(WSConstants.SOAPMESSAGE_NS + "#Base64Binary");
    JAXBElement<BinarySecurityTokenType> tokenType =
        new JAXBElement<BinarySecurityTokenType>(
            QNameConstants.BINARY_SECURITY_TOKEN,
            BinarySecurityTokenType.class,
            binarySecurityToken);

    return tokenType;
  }
 private static void appendThumbPrint(X509Certificate cert, String hash, StringBuilder sb) {
   try {
     MessageDigest md = MessageDigest.getInstance(hash);
     byte[] der = cert.getEncoded();
     md.update(der);
     byte[] digest = md.digest();
     char[] encode = Hex.encode(digest);
     appendHexSpace(encode, sb);
   } catch (NoSuchAlgorithmException e) {
     sb.append("Error calculating thumbprint: " + e.getMessage());
   } catch (CertificateEncodingException e) {
     sb.append("Error calculating thumbprint: " + e.getMessage());
   }
 }
  public static void testcaV1() throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(2048);
    KeyPair keyPair = kpg.generateKeyPair();
    X509Certificate cer = buildCARootCertV1(keyPair);
    System.out.println(cer);
    FileUtils.writeByteArrayToFile(new File("d:\\caV1cer.cer"), cer.getEncoded());
    // 生成CA证书
    byte[] publicBase64 =
        org.apache.commons.codec.binary.Base64.encodeBase64(cer.getEncoded(), true);
    String publicStr = new String(publicBase64, "UTF-8");
    publicStr = PUBLIC_PREFIX + publicStr + PUBLIC_SUFFIX;
    System.out.println(publicStr);
    FileUtils.writeByteArrayToFile(new File("d:\\caV1cer.pem"), publicStr.getBytes("UTF-8"));

    // 生成CA私钥
    byte[] privateBase64 =
        org.apache.commons.codec.binary.Base64.encodeBase64(
            keyPair.getPrivate().getEncoded(), true);
    String privateStr = new String(privateBase64, "UTF-8");
    privateStr = PRIVATE_PREFIX + privateStr + PRIVATE_SUFFIX;
    System.out.println(privateStr);
    FileUtils.writeByteArrayToFile(new File("d:\\caV1key.pem"), privateStr.getBytes("UTF-8"));
  }
Ejemplo n.º 26
0
  /**
   * Bounce the given {@link Signature} through a decode/encode cycle.
   *
   * @throws CertificateException if the before/after length differs substantially, usually a signal
   *     of something fishy going on.
   * @hide
   */
  public static Signature bounce(CertificateFactory cf, Signature s) throws CertificateException {
    final InputStream is = new ByteArrayInputStream(s.mSignature);
    final X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
    final Signature sPrime = new Signature(cert.getEncoded());

    if (Math.abs(sPrime.mSignature.length - s.mSignature.length) > 2) {
      throw new CertificateException(
          "Bounced cert length looks fishy; before "
              + s.mSignature.length
              + ", after "
              + sPrime.mSignature.length);
    }

    return sPrime;
  }
Ejemplo n.º 27
0
  /**
   * Create dummy public key certificate.
   *
   * @param keyId key id
   * @param cn common name
   * @throws Exception if an error occurs
   */
  @Command(description = "Create dummy public key certificate")
  public void dummyCert(
      @Param(name = "keyId", description = "Key ID") String keyId,
      @Param(name = "cn", description = "Common name") String cn)
      throws Exception {
    Calendar cal = GregorianCalendar.getInstance();
    cal.add(Calendar.YEAR, -1);
    Date notBefore = cal.getTime();
    cal.add(Calendar.YEAR, 2);
    Date notAfter = cal.getTime();

    ClientId memberId = ClientId.create("FOO", "BAR", "BAZ");

    GenerateSelfSignedCert request =
        new GenerateSelfSignedCert(keyId, cn, notBefore, notAfter, KeyUsageInfo.SIGNING, memberId);

    GenerateSelfSignedCertResponse response = SignerClient.execute(request);
    X509Certificate cert = readCertificate(response.getCertificateBytes());

    System.out.println("Certificate base64:");
    System.out.println(encodeBase64(cert.getEncoded()));
    bytesToFile(keyId + ".crt", cert.getEncoded());
    base64ToFile(keyId + ".crt.b64", cert.getEncoded());
  }
 /**
  * Calculates the hash of the certificate known as the "thumbprint" and returns it as a string
  * representation.
  *
  * @param cert The certificate to hash.
  * @param algorithm The hash algorithm to use.
  * @return The SHA-1 hash of the certificate.
  * @throws CertificateException
  */
 private static String getThumbprint(X509Certificate cert, String algorithm)
     throws CertificateException {
   MessageDigest digest;
   try {
     digest = MessageDigest.getInstance(algorithm);
   } catch (NoSuchAlgorithmException e) {
     throw new CertificateException(e);
   }
   byte[] encodedCert = cert.getEncoded();
   StringBuilder sb = new StringBuilder(encodedCert.length * 2);
   Formatter f = new Formatter(sb);
   try {
     for (byte b : digest.digest(encodedCert)) f.format("%02x", b);
   } finally {
     f.close();
   }
   return sb.toString();
 }
Ejemplo n.º 29
0
  private byte[] getCertFingerprint(X509Certificate cert) {
    MessageDigest md;
    byte[] fingerprint = null;
    try {

      md = MessageDigest.getInstance("SHA1");
      md.update(cert.getEncoded());

      fingerprint = md.digest();

    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } catch (CertificateException e) {
      e.printStackTrace();
    }

    return fingerprint;
  }
Ejemplo n.º 30
0
  @Override
  protected Object doExecute() throws Exception {
    String base64Cert = null;
    X509Certificate signerCert = null;
    if (certFile != null) {
      signerCert = X509Util.parseCert(certFile);
      base64Cert = IoUtil.base64Encode(signerCert.getEncoded(), false);
    }

    if ("PKCS12".equalsIgnoreCase(signerType) || "JKS".equalsIgnoreCase(signerType)) {
      signerConf = ShellUtil.canonicalizeSignerConf(signerType, signerConf, passwordResolver);
    }
    CmpResponderEntry entry = new CmpResponderEntry(name, signerType, signerConf, base64Cert);

    boolean b = caManager.addCmpResponder(entry);
    output(b, "added", "could not add", "CMP responder " + name);
    return null;
  }