Esempio n. 1
0
  private static X509CertificateHolder makeV3Certificate(
      KeyPair subKP, String _subDN, KeyPair issKP, String _issDN)
      throws GeneralSecurityException, IOException, OperatorCreationException, CertException {

    PublicKey subPub = subKP.getPublic();
    PrivateKey issPriv = issKP.getPrivate();
    PublicKey issPub = issKP.getPublic();

    X509v3CertificateBuilder v1CertGen =
        new JcaX509v3CertificateBuilder(
            new X500Name(_issDN),
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 100)),
            new X500Name(_subDN),
            subPub);

    ContentSigner signer =
        new JcaContentSignerBuilder("SHA1WithRSA").setProvider(BC).build(issPriv);

    X509CertificateHolder certHolder = v1CertGen.build(signer);

    ContentVerifierProvider verifier =
        new JcaContentVerifierProviderBuilder().setProvider(BC).build(issPub);

    assertTrue(certHolder.isSignatureValid(verifier));

    return certHolder;
  }
  private SignatureData getFromCmsSignature(
      SignatureVerificationRequest signatureVerificationRequest,
      SignatureVerificationResponse response)
      throws CMSException {
    String signature = signatureVerificationRequest.getSignature();
    byte[] decoded = Base64.decode(signature);
    CMSSignedData cmsSignedData = new CMSSignedData(decoded);
    String encodedSignedData = new String((byte[]) cmsSignedData.getSignedContent().getContent());

    // Fetch information about the issuers
    List<String> certInfos = new ArrayList<String>();
    Collection certificates = cmsSignedData.getCertificates().getMatches(null);
    for (Object certificate : certificates) {
      X509CertificateHolder holder = (X509CertificateHolder) certificate;
      certInfos.add(holder.getSubject().toString());
      CertificateInfo ci = new CertificateInfo();
      ci.setSubjectDn(holder.getSubject().toString());
      ci.setValidTo(simpleDateFormat.format(holder.getNotAfter()));
      response.getCertificateInfos().getCertificateInfo().add(ci);
    }

    // Fetch timestamp
    Date signingDate = findTimestamp(cmsSignedData);
    String dateString = simpleDateFormat.format(signingDate);
    response.setSignatureDate(dateString);

    // Create the SignatureData to be verified
    SignatureData signData = new SignatureData();
    signData.setEncodedTbs(encodedSignedData);
    signData.setSignature(signature);
    ELegType clientType = new ELegType("test", "test", PkiClient.NETMAKER_NETID_4);
    signData.setClientType(clientType);
    return signData;
  }
 @Before
 public void setup()
     throws JAXBException, IOException, ProfileException, CertificateEncodingException,
         NoSuchAlgorithmException {
   X509CertificateHolder x509CertificateHolder =
       new JcaX509CertificateHolder(generatePKI.getCaCert());
   if (profiles == null)
     profiles =
         new ProfilesJAXB(
             getClass().getResourceAsStream("/PrivateKey.xml"),
             x509CertificateHolder.toASN1Structure());
 }
 public Certificate getSignerCertificate() {
   try {
     Collection certificateCollection =
         cmsSignedData.getCertificates().getMatches(firstSignerInfo.getSID());
     Iterator iterator = certificateCollection.iterator();
     X509CertificateHolder certHolder = (X509CertificateHolder) iterator.next();
     return CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME)
         .generateCertificate(new ByteArrayInputStream(certHolder.getEncoded()));
   } catch (Exception e) {
     log.error(Channel.TECH, "Could not extract signer certificate from CMS signature : %1$s", e);
   }
   return null;
 }
Esempio n. 5
0
  @Override
  protected Object _doExecute() throws Exception {
    EnrollCertRequestType request = new EnrollCertRequestType(EnrollCertRequestType.Type.CERT_REQ);

    CertTemplateBuilder certTemplateBuilder = new CertTemplateBuilder();
    ConcurrentContentSigner signer =
        getSigner(hashAlgo, new SignatureAlgoControl(rsaMgf1, dsaPlain));
    X509CertificateHolder ssCert = signer.getCertificateAsBCObject();

    X500Name x500Subject = subject == null ? ssCert.getSubject() : new X500Name(subject);
    certTemplateBuilder.setSubject(x500Subject);
    certTemplateBuilder.setPublicKey(ssCert.getSubjectPublicKeyInfo());
    CertRequest certReq = new CertRequest(1, certTemplateBuilder.build(), null);

    ProofOfPossessionSigningKeyBuilder popoBuilder =
        new ProofOfPossessionSigningKeyBuilder(certReq);
    ContentSigner contentSigner = signer.borrowContentSigner();
    POPOSigningKey popoSk;
    try {
      popoSk = popoBuilder.build(contentSigner);
    } finally {
      signer.returnContentSigner(contentSigner);
    }

    ProofOfPossession popo = new ProofOfPossession(popoSk);

    EnrollCertRequestEntryType reqEntry =
        new EnrollCertRequestEntryType("id-1", profile, certReq, popo);
    request.addRequestEntry(reqEntry);

    EnrollCertResult result;
    RequestResponseDebug debug = getRequestResponseDebug();
    try {
      result = caClient.requestCerts(request, caName, user, debug);
    } finally {
      saveRequestResponse(debug);
    }

    X509Certificate cert = null;
    if (result != null) {
      String id = result.getAllIds().iterator().next();
      CertOrError certOrError = result.getCertificateOrError(id);
      cert = (X509Certificate) certOrError.getCertificate();
    }

    if (cert != null) {
      throw new CmdFailure("no certificate is excepted, but received one");
    }

    return null;
  }
Esempio n. 6
0
 public static void checkOrCreateKeyStore(
     final String file, final String password, final String domainName)
     throws IllegalArgumentException, OperatorCreationException {
   final String hostname;
   if ("0.0.0.0".equals(domainName)) {
     hostname = "localhost";
   } else {
     hostname = domainName;
   }
   try {
     KeyStore ks = KeyStore.getInstance("JKS");
     File keyStoreFile = new File(file);
     if (!keyStoreFile.exists()) {
       keyStoreFile.createNewFile();
       ks.load(null, null);
       KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
       keyPairGenerator.initialize(1024);
       KeyPair KPair = keyPairGenerator.generateKeyPair();
       X509v3CertificateBuilder v3CertGen =
           new X509v3CertificateBuilder(
               new X500Name("CN=" + hostname + ", OU=None, O=None L=None, C=None"),
               BigInteger.valueOf(System.currentTimeMillis()),
               new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
               new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)),
               new X500Name("CN=" + hostname + ", OU=None, O=None L=None, C=None"),
               SubjectPublicKeyInfo.getInstance(KPair.getPublic().getEncoded()));
       AlgorithmIdentifier sigAlgId =
           new DefaultSignatureAlgorithmIdentifierFinder().find("SHA512withRSA");
       AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
       AsymmetricKeyParameter foo = PrivateKeyFactory.createKey(KPair.getPrivate().getEncoded());
       ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(foo);
       X509CertificateHolder PKCertificateHolder = v3CertGen.build(sigGen);
       X509CertificateStructure eeX509CertificateStructure = PKCertificateHolder.toASN1Structure();
       CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
       X509Certificate cert;
       try (InputStream is1 = new ByteArrayInputStream(eeX509CertificateStructure.getEncoded())) {
         cert = (X509Certificate) cf.generateCertificate(is1);
       }
       ks.setKeyEntry(
           "siesta",
           KPair.getPrivate(),
           password.toCharArray(),
           new java.security.cert.Certificate[] {cert});
       ks.store(new FileOutputStream(file), password.toCharArray());
     }
   } catch (GeneralSecurityException | IOException | IllegalStateException ex) {
     throw new IllegalArgumentException("Error creating keystore, please manually create one", ex);
   }
 }
  /**
   * Verify that the given verifier can successfully verify the signature on this SignerInformation
   * object.
   *
   * @param verifier a suitably configured SignerInformationVerifier.
   * @return true if the signer information is verified, false otherwise.
   * @throws org.bouncycastle.cms.CMSVerifierCertificateNotValidException if the provider has an
   *     associated certificate and the certificate is not valid at the time given as the
   *     SignerInfo's signing time.
   * @throws org.bouncycastle.cms.CMSException if the verifier is unable to create a
   *     ContentVerifiers or DigestCalculators.
   */
  public boolean verify(SignerInformationVerifier verifier) throws CMSException {
    Time signingTime = getSigningTime(); // has to be validated if present.

    if (verifier.hasAssociatedCertificate()) {
      if (signingTime != null) {
        X509CertificateHolder dcv = verifier.getAssociatedCertificate();

        if (!dcv.isValidOn(signingTime.getDate())) {
          throw new CMSVerifierCertificateNotValidException("verifier not valid at signingTime");
        }
      }
    }

    return doVerify(verifier);
  }
 // controlla che nel firmatario sia presente l'attributo ESSCertIDv2 e che esso sia valido
 // in questo caso la busta crittografica è espressa correttamente nel formato CADES-BES secondo
 // la  DELIBERAZIONE ministeriale del N . 45 DEL 21 MAGGIO 2009
 private boolean isLegallySigned(SignerInformation signer, X509CertificateHolder cert)
     throws FirmapiuException, NoSuchAlgorithmException, IOException {
   AttributeTable signAttr = signer.getSignedAttributes();
   if (signAttr == null) throw new FirmapiuException(VERIFY_SIGNER_SIGNINGATTRIBUTE_NOTFOUND);
   Attribute attr = signAttr.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
   if (attr == null) throw new FirmapiuException(VERIFY_SIGNER_SIGNINGATTRIBUTE_NOTFOUND);
   ASN1Sequence sequence = ASN1Sequence.getInstance(attr.getAttrValues().getObjectAt(0));
   SigningCertificateV2 scv2 = SigningCertificateV2.getInstance(sequence);
   ESSCertIDv2[] essCert = scv2.getCerts();
   if (essCert == null || essCert.length < 1)
     throw new FirmapiuException(VERIFY_SIGNER_SIGNINGATTRIBUTE_NOTFOUND);
   // controlla l'hash del certificato se si restituisce true se no restituisce no
   // aggiungere hash del certificato di sottoscrizione
   String digestAlgorithm = "SHA-256";
   MessageDigest sha = null;
   sha = MessageDigest.getInstance(digestAlgorithm);
   byte[] digestedCert = sha.digest(cert.getEncoded());
   byte[] essCertHash = essCert[0].getCertHash();
   // affinché la firma sia valida digestCert e essCertHash devono essere uguali
   if (digestedCert.length != essCertHash.length) return false;
   else {
     for (int i = 0; i < digestedCert.length; i++)
       if (digestedCert[i] != essCertHash[i]) {
         return false;
       }
     return true;
   } // fine if
 } // fine metodo
 public List<Certificate> getSignatureCertificateInfo() {
   try {
     Store certificateStore = cmsSignedData.getCertificates();
     Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(null);
     List<Certificate> x509CertsCollection =
         new ArrayList<Certificate>(certificateCollection.size());
     for (X509CertificateHolder certHolder : certificateCollection) {
       x509CertsCollection.add(
           CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME)
               .generateCertificate(new ByteArrayInputStream(certHolder.getEncoded())));
     }
     return x509CertsCollection;
   } catch (Exception e) {
     ExceptionHandlerTyped.<SPISignatureException>handle(SPISignatureException.class, e);
   }
   return null;
 }
Esempio n. 10
0
  /**
   * This method returns DER encoded array of bytes representing {@code X509Certificate} for given
   * {@code X509CertificateHolder}. The {@code IOException} is transformed in {@code DSSException}.
   *
   * @param certificateHolder {@code X509CertificateHolder}
   * @return DER encoded array of bytes representing {@code X509Certificate}.
   * @throws DSSException
   */
  public static byte[] getCertificateDEREncoded(final X509CertificateHolder certificateHolder)
      throws DSSException {

    try {

      final byte[] bytes = certificateHolder.getEncoded();
      return bytes;
    } catch (IOException e) {
      throw new DSSException(e);
    }
  }
Esempio n. 11
0
  /**
   * This method return {@code X509Certificate} representing {@code X509CertificateHolder}. The
   * {@code CertificateParsingException} is transformed in {@code DSSException}.
   *
   * @param certificateHolder {@code X509CertificateHolder}
   * @return {@code X509Certificate}.
   * @throws DSSException
   */
  public static X509Certificate getCertificate(final X509CertificateHolder certificateHolder)
      throws DSSException {

    try {

      final X509Certificate certificate =
          new X509CertificateObject(certificateHolder.toASN1Structure());
      return certificate;
    } catch (CertificateParsingException e) {
      throw new DSSException(e);
    }
  }
Esempio n. 12
0
  public boolean isVerified(
      X509CertificateHolder certHolder, DigestCalculatorProvider digesterProvider)
      throws CMPException {
    AlgorithmIdentifier digAlg =
        digestAlgFinder.find(certHolder.toASN1Structure().getSignatureAlgorithm());
    if (digAlg == null) {
      throw new CMPException("cannot find algorithm for digest from signature");
    }

    DigestCalculator digester;

    try {
      digester = digesterProvider.get(digAlg);
    } catch (OperatorCreationException e) {
      throw new CMPException("unable to create digester: " + e.getMessage(), e);
    }

    CMPUtil.derEncodeToStream(certHolder.toASN1Structure(), digester.getOutputStream());

    return Arrays.areEqual(certStatus.getCertHash().getOctets(), digester.getDigest());
  }
Esempio n. 13
0
  public X509Certificate convertCertificate(X509CertificateHolder certHolder)
      throws CertificateException {

    try {
      CertificateFactory certFact = helper.createCertificateFactory("X.509");

      return (X509Certificate)
          certFact.generateCertificate(new ByteArrayInputStream(certHolder.getEncoded()));
    } catch (IOException e) {
      throw new OpCertificateException(
          "cannot get encoded form of certificate: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
      throw new OpCertificateException("cannot create certificate factory: " + e.getMessage(), e);
    } catch (NoSuchProviderException e) {
      throw new OpCertificateException("cannot find factory provider: " + e.getMessage(), e);
    }
  }
  /**
   * Basic Constructor - set up a calculator based on signerInfoGen with a ESSCertID calculated from
   * the signer's associated certificate using the sha1DigestCalculator. If alternate values are
   * required for id-aa-signingCertificate they should be added to the signerInfoGen object before
   * it is passed in, otherwise a standard digest based value will be added.
   *
   * @param signerInfoGen the generator for the signer we are using.
   * @param digestCalculator calculator for to use for digest of certificate.
   * @param tsaPolicy tasPolicy to send.
   * @param isIssuerSerialIncluded should issuerSerial be included in the ESSCertIDs, true if yes,
   *     by default false.
   * @throws IllegalArgumentException if calculator is not SHA-1 or there is no associated
   *     certificate for the signer,
   * @throws TSPException if the signer certificate cannot be processed.
   */
  public TimeStampTokenGenerator(
      final SignerInfoGenerator signerInfoGen,
      DigestCalculator digestCalculator,
      ASN1ObjectIdentifier tsaPolicy,
      boolean isIssuerSerialIncluded)
      throws IllegalArgumentException, TSPException {
    this.signerInfoGen = signerInfoGen;
    this.tsaPolicyOID = tsaPolicy;

    if (!signerInfoGen.hasAssociatedCertificate()) {
      throw new IllegalArgumentException("SignerInfoGenerator must have an associated certificate");
    }

    X509CertificateHolder assocCert = signerInfoGen.getAssociatedCertificate();
    TSPUtil.validateCertificate(assocCert);

    try {
      OutputStream dOut = digestCalculator.getOutputStream();

      dOut.write(assocCert.getEncoded());

      dOut.close();

      if (digestCalculator
          .getAlgorithmIdentifier()
          .getAlgorithm()
          .equals(OIWObjectIdentifiers.idSHA1)) {
        final ESSCertID essCertid =
            new ESSCertID(
                digestCalculator.getDigest(),
                isIssuerSerialIncluded
                    ? new IssuerSerial(
                        new GeneralNames(new GeneralName(assocCert.getIssuer())),
                        assocCert.getSerialNumber())
                    : null);

        this.signerInfoGen =
            new SignerInfoGenerator(
                signerInfoGen,
                new CMSAttributeTableGenerator() {
                  public AttributeTable getAttributes(Map parameters)
                      throws CMSAttributeTableGenerationException {
                    AttributeTable table =
                        signerInfoGen.getSignedAttributeTableGenerator().getAttributes(parameters);

                    if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) {
                      return table.add(
                          PKCSObjectIdentifiers.id_aa_signingCertificate,
                          new SigningCertificate(essCertid));
                    }

                    return table;
                  }
                },
                signerInfoGen.getUnsignedAttributeTableGenerator());
      } else {
        AlgorithmIdentifier digAlgID =
            new AlgorithmIdentifier(digestCalculator.getAlgorithmIdentifier().getAlgorithm());
        final ESSCertIDv2 essCertid =
            new ESSCertIDv2(
                digAlgID,
                digestCalculator.getDigest(),
                isIssuerSerialIncluded
                    ? new IssuerSerial(
                        new GeneralNames(new GeneralName(assocCert.getIssuer())),
                        new ASN1Integer(assocCert.getSerialNumber()))
                    : null);

        this.signerInfoGen =
            new SignerInfoGenerator(
                signerInfoGen,
                new CMSAttributeTableGenerator() {
                  public AttributeTable getAttributes(Map parameters)
                      throws CMSAttributeTableGenerationException {
                    AttributeTable table =
                        signerInfoGen.getSignedAttributeTableGenerator().getAttributes(parameters);

                    if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2) == null) {
                      return table.add(
                          PKCSObjectIdentifiers.id_aa_signingCertificateV2,
                          new SigningCertificateV2(essCertid));
                    }

                    return table;
                  }
                },
                signerInfoGen.getUnsignedAttributeTableGenerator());
      }
    } catch (IOException e) {
      throw new TSPException("Exception processing certificate.", e);
    }
  }
 public PKCS12SafeBagBuilder(X509CertificateHolder certificate) throws IOException {
   this(certificate.toASN1Structure());
 }