Example usage for org.bouncycastle.asn1.x509 Time getInstance

List of usage examples for org.bouncycastle.asn1.x509 Time getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Time getInstance.

Prototype

public static Time getInstance(Object obj) 

Source Link

Usage

From source file:it.trento.comune.j4sign.cms.utils.CMSBuilder.java

License:Open Source License

private Date parseSigningTime(byte[] bytes, PrintWriter pw) {

    Date parsedSigningTime = null;

    try {//from  w  ww  .j av a 2 s.c  o m

        ASN1InputStream aIn = new ASN1InputStream(bytes);
        ASN1Set signedAttributes = (ASN1Set) aIn.readObject();

        AttributeTable attr = new AttributeTable(signedAttributes);

        Iterator iter = attr.toHashtable().values().iterator();

        pw.println("Listing authenticated attributes:");
        int count = 1;
        while (iter.hasNext()) {
            Attribute a = (Attribute) iter.next();

            pw.println("Attribute " + count + ":");
            if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) {
                Time time = Time.getInstance(a.getAttrValues().getObjectAt(0));
                pw.println("Authenticated time (SERVER local time): " + time.getDate());

                parsedSigningTime = time.getDate();

            }
            if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) {
                if (CMSObjectIdentifiers.data.getId()
                        .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId()))
                    pw.println("Content Type: PKCS7_DATA");
            }
            if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) {
                byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets();
                pw.println("Message Digest (hash of data content): " + formatAsString(md, " ", 16));
            }
            pw.println("\nAttribute dump follows:");
            pw.println(ASN1Dump.dumpAsString(a) + "\n");

            count++;
        }
    } catch (Exception e) {
        pw.println(e);
        return null;
    }
    pw.flush();

    return parsedSigningTime;

}

From source file:it.trento.comune.j4sign.cms.utils.CMSVerifier.java

License:Open Source License

private void parseAuthenticatedAttributes(SignerInformation signer) {
    AttributeTable attr = signer.getSignedAttributes();

    Iterator<Attribute> iter = attr.toHashtable().values().iterator();

    if (debug)//from ww w  .  ja  v  a  2 s  .c  o  m
        System.out.println("Listing authenticated attributes:");
    int count = 1;
    while (iter.hasNext()) {
        Attribute a = iter.next();

        if (debug)
            System.out.println("Attribute " + count + ":");
        if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) {
            Time time = Time.getInstance(a.getAttrValues().getObjectAt(0));
            if (debug)
                System.out.println("Authenticated time: " + time.getDate());

            this.signingTime = time.getDate();
        }
        if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) {
            if (CMSObjectIdentifiers.data.getId()
                    .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId()))
                if (debug)
                    System.out.println("Content Type: PKCS7_DATA");
        }
        if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) {
            byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets();
            if (debug)
                System.out.println(
                        "Message Digest (hash of data content):\n" + CMSBuilder.formatAsString(md, " ", 16));
        }
        if (debug)
            System.out.println("\nAttribute dump follows:");
        if (debug)
            System.out.println(ASN1Dump.dumpAsString(a) + "\n");

        count++;
    }

}

From source file:it.trento.comune.j4sign.examples.CMSServlet.java

License:Open Source License

/**
 * A text message resulting from a dump of provided authenticated attributes
 * data. Shows, among other things, the embedded timestamp attribute.
 * // w w  w.j  ava  2s  . c  o  m
 * @param bytes
 *            the ASN.1 DER set of authenticated attributes.
 * @return the attributes textual dump.
 */
private String getAuthenticatedAttributesPrintout(byte[] bytes) {
    StringWriter printout = new StringWriter();
    PrintWriter pw = new PrintWriter(printout);
    try {

        ASN1StreamParser a1p = new ASN1StreamParser(bytes);

        System.out.println("ASN1 parser built: " + a1p);

        DERSetParser signedAttributesParser = (DERSetParser) a1p.readObject();

        System.out.println("DERSetParser object read: " + signedAttributesParser);

        ASN1Set set = ASN1Set.getInstance(signedAttributesParser.getDERObject());

        AttributeTable attr = new AttributeTable(set);

        System.out.println("Attribute table created: " + attr);

        Iterator iter = attr.toHashtable().values().iterator();

        pw.println("Listing authenticated attributes:");
        int count = 1;
        while (iter.hasNext()) {
            Attribute a = (Attribute) iter.next();

            pw.println("Attribute " + count + ":");
            if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) {
                Time time = Time.getInstance(a.getAttrValues().getObjectAt(0));
                pw.println("Authenticated time (SERVER local time): " + time.getDate());
            }
            if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) {
                if (CMSObjectIdentifiers.data.getId()
                        .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId()))
                    pw.println("Content Type: PKCS7_DATA");
            }
            if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) {
                byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets();
                pw.println("Message Digest (SHA-256 hash of data content): " + formatAsString(md, " "));
            }
            if (a.getAttrType().getId().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2.getId())) {
                pw.println("Signing Certificate V2");
            }

            pw.println("\nAttribute dump follows:");
            pw.println(ASN1Dump.dumpAsString(a) + "\n");

            count++;
        }
    } catch (Exception e) {
        System.out.println(e);
        pw.println(e);
        return null;
    }
    pw.flush();

    return printout.toString();

}

From source file:it.trento.comune.j4sign.verification.VerifyResult.java

License:Open Source License

/**
 * Main signature verification and signature attributes correctness<br>
 * <br>/*from  ww  w . j  ava2  s.  co m*/
 * Verifica principale della firma e di correttezza degli attributi.
 * 
 * @return boolean
 */
public boolean checkIntegrity() {

    this.integrityChecked = this.messageDigestPresent = this.contentTypeDataPresent = false;

    if (signer == null) {
        log.info("No signers");
        return integrityChecked;
    }

    log.info("\nSigner DN: " + cert.getSubjectDN() + "\nSigner SID: " + signer.getSID().toString() + "\n");

    // ===== List authenticated attributes =========
    AttributeTable attrs = signer.getSignedAttributes();

    if (attrs == null) {
        log.info("No authenticated attributes!");
        return false;
    }

    Iterator<Attribute> iter = attrs.toHashtable().values().iterator();

    log.info("Listing authenticated attributes:");

    int count = 1;
    while (iter.hasNext()) {
        Attribute a = iter.next();

        log.info("Attribute " + count + ")");

        if (a.getAttrType().getId().equals(CMSAttributes.contentType.getId())) {
            if (CMSObjectIdentifiers.data.getId()
                    .equals(DERObjectIdentifier.getInstance(a.getAttrValues().getObjectAt(0)).getId()))

                this.contentTypeDataPresent = true;

            log.info("Content Type: PKCS7_DATA");
        }

        if (a.getAttrType().getId().equals(CMSAttributes.messageDigest.getId())) {
            byte[] md = DEROctetString.getInstance(a.getAttrValues().getObjectAt(0)).getOctets();

            this.messageDigestPresent = true;

            log.info("Message Digest:\n" + CertUtils.formatAsHexString(md));
        }

        if (a.getAttrType().getId().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2.getId()))

            log.info("Reference to signing certificate (CAdES): signingCertificateV2");

        if (a.getAttrType().getId().equals(CMSAttributes.signingTime.getId())) {
            Time time = Time.getInstance(a.getAttrValues().getObjectAt(0));

            log.info("Signing time: " + time.getDate());

            this.signingTime = time.getDate();
        }

        log.info("\nAttribute dump follows:");
        log.info(ASN1Dump.dumpAsString(a) + "\n");

        count++;
    }

    signingAlgorithmName = new DefaultCMSSignatureAlgorithmNameGenerator().getSignatureName(
            AlgorithmIdentifier.getInstance(signer.getDigestAlgOID()),
            AlgorithmIdentifier.getInstance(signer.getEncryptionAlgOID()));

    log.info("\nSigning algorithm is : " + signingAlgorithmName + "\n");

    try {

        // BC API version 2
        /*
         * Note: we should test for EncryptionAlg = RSA before doing
         * this!!!! integrityChecked = signer .verify(new
         * BcRSASignerInfoVerifierBuilder( new
         * DefaultDigestAlgorithmIdentifierFinder(), new
         * BcDigestCalculatorProvider()) .build(new
         * X509CertificateHolder(cert.getEncoded())));
         */

        integrityChecked = signer.verify(
                new JcaSimpleSignerInfoVerifierBuilder().build(new X509CertificateHolder(cert.getEncoded())));

        // Now deprecated
        // integrityChecked = signer.verify(cert, "BC");

    } catch (CMSException ex) {
        System.out.println(ex.getMessage());
    } catch (CertificateNotYetValidException ex) {
        System.out.println(ex.getMessage());
    } catch (CertificateExpiredException ex) {
        System.out.println(ex.getMessage());
    } catch (CertificateException e) {
        System.out.println(e.getMessage());
    } catch (OperatorCreationException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }

    return integrityChecked;
}

From source file:org.signserver.module.tsa.MSAuthCodeTimeStampSignerTest.java

License:Open Source License

/**
 * Performs test using specified signature algorithm, digest algorithm and with the optional SigningCertificate attribute included or not included.
 * //w  ww. j ava2  s . c  om
 * The SigningCertificate attribute is specified in RFC 2634.
 * 
 * SigningCertificate ::=  SEQUENCE {
 *  certs        SEQUENCE OF ESSCertID,
 *  policies     SEQUENCE OF PolicyInformation OPTIONAL
 * }
 *
 * id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
 *  member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
 *  smime(16) id-aa(2) 12 }
 *
 * ESSCertID ::=  SEQUENCE {
 *   certHash                 Hash,
 *   issuerSerial             IssuerSerial OPTIONAL
 * }
 * Hash ::= OCTET STRING -- SHA1 hash of entire certificate
 *
 * IssuerSerial ::= SEQUENCE {
 *   issuer                   GeneralNames,
 *   serialNumber             CertificateSerialNumber
 * }
 * 
 * @param signingAlgo Signature algorithm to use
 * @param expectedDigestOID Expected digest OID
 * @param requestData Request data to test with
 * @param includeSigningCertAttr If true, include and test the SigningCertificate attribute
 * @throws Exception
 */
private void testProcessDataWithAlgo(final String signingAlgo, final String expectedDigestOID,
        final byte[] requestData, final boolean includeSigningCertAttr, final String includeCertificateLevels)
        throws Exception {
    SignServerUtil.installBCProvider();

    final String CRYPTOTOKEN_CLASSNAME = "org.signserver.server.cryptotokens.HardCodedCryptoToken";

    final ProcessRequest signRequest;

    final GlobalConfigurationSessionMock globalConfig = new GlobalConfigurationSessionMock();
    final WorkerSessionMock workerMock = new WorkerSessionMock(globalConfig);

    final WorkerConfig config = new WorkerConfig();
    config.setProperty("NAME", "TestMSAuthCodeTimeStampSigner");
    config.setProperty("AUTHTYPE", "NOAUTH");
    config.setProperty("TIMESOURCE", "org.signserver.server.ZeroTimeSource");
    config.setProperty("SIGNATUREALGORITHM", signingAlgo);
    config.setProperty("DEFAULTKEY", HardCodedCryptoTokenAliases.KEY_ALIAS_1);

    if (includeSigningCertAttr) {
        config.setProperty("INCLUDE_SIGNING_CERTIFICATE_ATTRIBUTE", "true");
    }

    if (includeCertificateLevels != null) {
        config.setProperty(WorkerConfig.PROPERTY_INCLUDE_CERTIFICATE_LEVELS, includeCertificateLevels);
    }

    final MSAuthCodeTimeStampSigner worker = new MSAuthCodeTimeStampSigner() {
        @Override
        protected IGlobalConfigurationSession.IRemote getGlobalConfigurationSession() {
            return globalConfig;
        }
    };

    workerMock.setupWorker(SIGNER_ID, CRYPTOTOKEN_CLASSNAME, config, worker);
    workerMock.reloadConfiguration(SIGNER_ID);

    // if the INCLUDE_CERTIFICATE_LEVELS property has been set,
    // check that it gives a not supported error
    if (includeCertificateLevels != null) {
        final List<String> errors = worker.getFatalErrors();

        assertTrue("Should contain config error",
                errors.contains(WorkerConfig.PROPERTY_INCLUDE_CERTIFICATE_LEVELS + " is not supported."));
        return;
    }

    // create sample hard-coded request
    signRequest = new GenericSignRequest(REQUEST_ID, requestData);

    final RequestContext requestContext = new RequestContext();
    GenericSignResponse resp = (GenericSignResponse) workerMock.process(SIGNER_ID, signRequest, requestContext);

    // check that the response contains the needed attributes
    byte[] buf = resp.getProcessedData();
    ASN1Sequence asn1seq = ASN1Sequence.getInstance(Base64.decode(buf));

    ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1seq.getObjectAt(0));
    ASN1TaggedObject ato = ASN1TaggedObject.getInstance(asn1seq.getObjectAt(1));

    assertEquals("Invalid OID in response", SIGNED_DATA_OID, oid.getId());

    ASN1Sequence asn1seq1 = ASN1Sequence.getInstance(ato.getObject());

    ASN1Set asn1set = ASN1Set.getInstance(asn1seq1.getObjectAt(4));
    ASN1Sequence asn1seq2 = ASN1Sequence.getInstance(asn1set.getObjectAt(0));
    ASN1TaggedObject ato1 = ASN1TaggedObject.getInstance(asn1seq2.getObjectAt(3));
    ASN1Sequence asn1seq3 = ASN1Sequence.getInstance(ato1.getObject());
    ASN1Sequence asn1seq4 = ASN1Sequence.getInstance(asn1seq3.getObjectAt(0));
    ASN1Sequence asn1seq5 = ASN1Sequence.getInstance(asn1seq3.getObjectAt(1));
    ASN1Sequence asn1seq6 = ASN1Sequence.getInstance(asn1seq3.getObjectAt(2));

    final X509Certificate cert = (X509Certificate) CertTools
            .getCertfromByteArray(HardCodedCryptoToken.certbytes1);
    // expected serial number
    final BigInteger sn = cert.getSerialNumber();

    // if INCLUDE_SIGNING_CERTIFICATE_ATTRIBUTE is set to false, the attribute should not be included
    if (!includeSigningCertAttr) {
        assertEquals("Number of attributes", 3, asn1seq3.size());
    } else {
        final ASN1Sequence scAttr = ASN1Sequence.getInstance(asn1seq3.getObjectAt(3));
        TestUtils.checkSigningCertificateAttribute(scAttr, cert);
    }

    ASN1ObjectIdentifier ctOID = ASN1ObjectIdentifier.getInstance(asn1seq4.getObjectAt(0));
    assertEquals("Invalid OID for content type", CONTENT_TYPE_OID, ctOID.getId());

    ASN1ObjectIdentifier stOID = ASN1ObjectIdentifier.getInstance(asn1seq5.getObjectAt(0));
    assertEquals("Invalid OID for signing time", SIGNING_TIME_OID, stOID.getId());

    ASN1ObjectIdentifier mdOID = ASN1ObjectIdentifier.getInstance(asn1seq6.getObjectAt(0));
    assertEquals("Invalid OID for content type", MESSAGE_DIGEST_OID, mdOID.getId());

    // get signing time from response
    ASN1Set set = ASN1Set.getInstance(asn1seq5.getObjectAt(1));
    ASN1Encodable t = set.getObjectAt(0);
    Time t2 = Time.getInstance(t);
    Date d = t2.getDate();

    // the expected time (the "starting point" of time according to java.util.Date, consistent with the behavior of ZeroTimeSource
    Date d0 = new Date(0);

    assertEquals("Unexpected signing time in response", d0, d);

    // check expected signing algo
    ASN1Set set1 = ASN1Set.getInstance(asn1seq1.getObjectAt(1));
    ASN1Sequence asn1seq7 = ASN1Sequence.getInstance(set1.getObjectAt(0));
    ASN1ObjectIdentifier algOid = ASN1ObjectIdentifier.getInstance(asn1seq7.getObjectAt(0));

    assertEquals("Unexpected digest OID in response", expectedDigestOID, algOid.getId());

    // check that the request is included
    final CMSSignedData signedData = new CMSSignedData(asn1seq.getEncoded());
    final byte[] content = (byte[]) signedData.getSignedContent().getContent();

    final ASN1Sequence seq = ASN1Sequence.getInstance(Base64.decode(requestData));
    final ASN1Sequence seq2 = ASN1Sequence.getInstance(seq.getObjectAt(1));
    final ASN1TaggedObject tag = ASN1TaggedObject.getInstance(seq2.getObjectAt(1));
    final ASN1OctetString data = ASN1OctetString.getInstance(tag.getObject());

    assertTrue("Contains request data", Arrays.equals(data.getOctets(), content));

    // check the signing certificate
    final X509Certificate signercert = (X509Certificate) resp.getSignerCertificate();
    assertEquals("Serial number", sn, signercert.getSerialNumber());
    assertEquals("Issuer", cert.getIssuerDN(), signercert.getIssuerDN());

    // check ContentInfo, according to the Microsoft specification, the contentInfo in the response is
    // identical to the contentInfo in the request
    final ContentInfo expCi = new ContentInfo(seq2);
    final ContentInfo ci = new ContentInfo(ASN1Sequence.getInstance(asn1seq1.getObjectAt(2)));

    assertEquals("Content info should match the request", expCi, ci);

    // Get signers
    final Collection signers = signedData.getSignerInfos().getSigners();
    final SignerInformation signer = (SignerInformation) signers.iterator().next();

    // Verify using the signer's certificate
    assertTrue("Verification using signer certificate", signer.verify(signercert.getPublicKey(), "BC"));

    // Check that the time source is being logged
    LogMap logMap = LogMap.getInstance(requestContext);
    assertEquals("timesource", ZeroTimeSource.class.getSimpleName(), logMap.get("TSA_TIMESOURCE"));

    assertNotNull("response", logMap.get(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED));
    assertEquals("log line doesn't contain newlines", -1,
            logMap.get(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED).lastIndexOf('\n'));
}