Example usage for org.bouncycastle.cms SignerInformation getSID

List of usage examples for org.bouncycastle.cms SignerInformation getSID

Introduction

In this page you can find the example usage for org.bouncycastle.cms SignerInformation getSID.

Prototype

public SignerId getSID() 

Source Link

Usage

From source file:net.jsign.pe.PEFile.java

License:Apache License

/**
 * Print detailed informations about the PE file.
 *///from  w w w. ja v a  2  s.  co m
public void printInfo(PrintWriter out) {
    out.println("PE File");
    out.println("  Name:          " + raf.getName());
    out.println("  Size:          " + raf.length());
    out.println("  Last Modified: " + new Date(raf.lastModified()));
    out.println();

    out.println("PE Header");
    out.println("  Machine:                    " + getMachineType());
    out.println("  Number of sections:         " + getNumberOfSections());
    out.println("  Timestamp:                  " + getTimeDateStamp());
    out.println("  Pointer to symbol table:    0x" + Long.toHexString(getPointerToSymbolTable()));
    out.println("  Number of symbols:          " + getNumberOfSymbols());
    out.println("  Size of optional header:    " + getSizeOfOptionalHeader());
    out.println("  Characteristics:            0x" + Long.toBinaryString(getCharacteristics()));
    out.println();

    out.println("Optional Header");
    PEFormat format = getFormat();
    out.println(
            "  PE Format:                  0x" + Integer.toHexString(format.value) + " (" + format.label + ")");
    out.println("  Linker version:             " + getMajorLinkerVersion() + "." + getMinorLinkerVersion());
    out.println("  Size of code:               " + getSizeOfCode());
    out.println("  Size of initialized data:   " + getSizeOfInitializedData());
    out.println("  Size of uninitialized data: " + getSizeOfUninitializedData());
    out.println("  Address of entry point:     0x" + Long.toHexString(getAddressOfEntryPoint()));
    out.println("  Base of code:               0x" + Long.toHexString(getBaseOfCode()));
    if (PEFormat.PE32.equals(getFormat())) {
        out.println("  Base of data:               0x" + Long.toHexString(getBaseOfData()));
    }
    out.println("  Image base:                 0x" + Long.toHexString(getImageBase()));
    out.println("  Section alignment:          " + getSectionAlignment());
    out.println("  File alignment:             " + getFileAlignment());
    out.println("  Operating system version:   " + getMajorOperatingSystemVersion() + "."
            + getMinorOperatingSystemVersion());
    out.println("  Image version:              " + getMajorImageVersion() + "." + getMinorImageVersion());
    out.println(
            "  Subsystem version:          " + getMajorSubsystemVersion() + "." + getMinorSubsystemVersion());
    out.println("  Size of image:              " + getSizeOfImage());
    out.println("  Size of headers:            " + getSizeOfHeaders());
    out.println("  Checksum:                   0x" + Long.toHexString(getCheckSum()));
    out.println("  Checksum (computed):        0x" + Long.toHexString(computeChecksum()));
    out.println("  Subsystem:                  " + getSubsystem());
    out.println("  DLL characteristics:        0x" + Long.toBinaryString(getDllCharacteristics()));
    out.println("  Size of stack reserve:      " + getSizeOfStackReserve());
    out.println("  Size of stack commit:       " + getSizeOfStackCommit());
    out.println("  Size of heap reserve:       " + getSizeOfHeapReserve());
    out.println("  Size of heap commit:        " + getSizeOfHeapCommit());
    out.println("  Number of RVA and sizes:    " + getNumberOfRvaAndSizes());
    out.println();

    out.println("Data Directory");
    for (DataDirectoryType type : DataDirectoryType.values()) {
        DataDirectory entry = getDataDirectory(type);
        if (entry != null && entry.getVirtualAddress() != 0) {
            out.printf("  %-30s 0x%08x %8d bytes\n", type, entry.getVirtualAddress(), entry.getSize());
        }
    }
    out.println();

    int sectionTableOffset = getDataDirectoryOffset() + 8 * getNumberOfRvaAndSizes();
    out.println("Sections");
    out.println("      Name     Virtual Size  Virtual Address  Raw Data Size  Raw Data Ptr  Characteristics");
    for (int i = 0; i < getNumberOfSections(); i++) {
        Section section = new Section(this, sectionTableOffset + 40 * i);
        out.printf("  #%d  %-8s     %8d       0x%08x       %8d    0x%08x  %s\n", i + 1, section.getName(),
                section.getVirtualSize(), section.getVirtualAddress(), section.getSizeOfRawData(),
                section.getPointerToRawData(), section.getCharacteristics());
    }
    out.println();

    List<CMSSignedData> signatures = getSignatures();
    if (!signatures.isEmpty()) {
        out.println("Signatures");
        for (CMSSignedData signedData : signatures) {
            SignerInformation signerInformation = signedData.getSignerInfos().getSigners().iterator().next();
            X509CertificateHolder certificate = (X509CertificateHolder) signedData.getCertificates()
                    .getMatches(signerInformation.getSID()).iterator().next();

            String commonName = certificate.getSubject().getRDNs(X509ObjectIdentifiers.commonName)[0].getFirst()
                    .getValue().toString();

            AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
            boolean timestamped = unsignedAttributes != null
                    && (unsignedAttributes.get(PKCSObjectIdentifiers.pkcs_9_at_counterSignature) != null
                            || unsignedAttributes.get(AuthenticodeObjectIdentifiers.SPC_RFC3161_OBJID) != null);
            DigestAlgorithm algorithm = DigestAlgorithm
                    .of(signerInformation.getDigestAlgorithmID().getAlgorithm());
            out.println("  " + commonName + "  " + (algorithm != null ? "[" + algorithm.id + "]  " : "")
                    + (timestamped ? "(timestamped)" : ""));
        }
    }
}

From source file:net.markenwerk.utils.mail.smime.SmimeUtil.java

License:Open Source License

/**
 * Checks a SMIMESigned to make sure that the signature matches.
 *//*from w  w  w . jav  a2  s  . co m*/
private static boolean checkSignature(SMIMESigned smimeSigned)
        throws MessagingException, IOException, GeneralSecurityException {
    try {
        boolean returnValue = true;

        @SuppressWarnings("rawtypes")
        Store certificates = smimeSigned.getCertificates();
        Iterator<SignerInformation> signerInformations = smimeSigned.getSignerInfos().getSigners().iterator();

        while (returnValue && signerInformations.hasNext()) {
            SignerInformation signerInformation = signerInformations.next();
            X509Certificate certificate = getCertificate(certificates, signerInformation.getSID());
            SignerInformationVerifier verifier = getVerifier(certificate);
            if (!signerInformation.verify(verifier)) {
                returnValue = false;
            }
        }
        return returnValue;

    } catch (Exception e) {
        throw handledException(e);
    }
}

From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectParser.java

License:BSD License

private boolean verifySigner(SignerInformation signer, X509Certificate certificate) {
    validationResult.rejectIfFalse(DIGEST_ALGORITHM_OID.equals(signer.getDigestAlgOID()),
            CMS_SIGNER_INFO_DIGEST_ALGORITHM);
    validationResult.rejectIfFalse(RSA_ENCRYPTION_OID.equals(signer.getEncryptionAlgOID())
            || SHA256WITHRSA_ENCRYPTION_OID.equals(signer.getEncryptionAlgOID()), ENCRYPTION_ALGORITHM);
    if (!validationResult.rejectIfNull(signer.getSignedAttributes(), SIGNED_ATTRS_PRESENT)) {
        return false;
    }/*www.  ja va 2s.com*/
    validationResult.rejectIfNull(signer.getSignedAttributes().get(CMSAttributes.contentType),
            CONTENT_TYPE_ATTR_PRESENT);
    validationResult.rejectIfNull(signer.getSignedAttributes().get(CMSAttributes.messageDigest),
            MSG_DIGEST_ATTR_PRESENT);

    //http://tools.ietf.org/html/rfc6488#section-2.1.6.4
    //MUST include contentType and messageDigest
    //MAY include signingTime, binary-signing-time, or both
    //Other attributes MUST NOT be included

    //Check if the signedAttributes are allowed
    verifyOptionalSignedAttributes(signer);

    SignerId signerId = signer.getSID();
    try {
        validationResult.rejectIfFalse(signerId.match(new JcaX509CertificateHolder(certificate)),
                SIGNER_ID_MATCH);
    } catch (CertificateEncodingException e) {
        throw new AbstractX509CertificateWrapperException(e);
    }

    return true;
}

From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilderTest.java

License:BSD License

/**
 * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.6.2
 *//*  ww  w. j av  a 2  s .c o m*/
@Test
public void shouldCmsObjectHaveCorrectSubjectKeyIdentifier() throws Exception {
    Collection<?> signers = signedDataParser.getSignerInfos().getSigners();
    SignerInformation signer = (SignerInformation) signers.iterator().next();

    assertArrayEquals(
            X509CertificateUtil.getSubjectKeyIdentifier(
                    ProvisioningCmsCertificateBuilderTest.TEST_CMS_CERT.getCertificate()),
            signer.getSID().getSubjectKeyIdentifier());
}

From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilderTest.java

License:BSD License

/**
 * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.6.2
 *//*  w  w  w. j  a  v  a  2 s.  c  o  m*/
@Test
public void shouldCmsObjectHaveSubjectKeyIdentifierOnly() throws Exception {
    Collection<?> signers = signedDataParser.getSignerInfos().getSigners();
    SignerInformation signer = (SignerInformation) signers.iterator().next();

    assertNull(signer.getSID().getIssuer());
    assertNull(signer.getSID().getSerialNumber());
}

From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectParser.java

License:BSD License

/**
 * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.6.2
 *///from ww  w.j  ava 2 s  . c o m
private void verifySubjectKeyIdentifier(SignerInformation signer) {
    SignerId sid = signer.getSID();
    validationResult.rejectIfFalse(Arrays.equals(X509CertificateUtil.getSubjectKeyIdentifier(cmsCertificate),
            sid.getSubjectKeyIdentifier()), CMS_SIGNER_INFO_SKI);
    validationResult.rejectIfFalse(sid.getIssuer() == null && sid.getSerialNumber() == null,
            CMS_SIGNER_INFO_SKI_ONLY);
}

From source file:net.sf.assinafacil.AssinaFacilApp.java

License:Open Source License

@Action
public void verifySignersAndShowInfo() {

    String selectedSignedFile = mainWindow.getSelectedFile();

    if ((selectedSignedFile == null) || (selectedSignedFile.startsWith("Selecione"))
            || (selectedSignedFile.equals(""))) {
        mainWindow.setStatusMessage("Selecione o arquivo para verificao...");
        return;//from   w  ww. jav a 2s .  c  o m
    }
    try {
        CertStore trustCertStore = this.buildTrustStore();

        CertStore crlCertStore = null;

        SignerInformationStore signerInformationStore = this.getSignatures(new File(selectedSignedFile));
        CertStore certificateStore = this.getCertificates(new File(selectedSignedFile));

        Collection<? extends Certificate> certificates = certificateStore.getCertificates(null);
        Collection colSign = signerInformationStore.getSigners();

        HashSet<X509CRL> crlCerts = new HashSet();

        HashSet<TrustAnchor> trustSet = new HashSet();

        // Pega os certificados sem repetio pois o CertBuilder erra na seleo...
        for (Certificate cert : certificates) {
            if (cert instanceof X509Certificate) {
                X509Certificate x509Cert = (X509Certificate) cert;

                // Pega s os root's CA para o trust e as outras CAs para o CRLStore
                if (x509Cert.getBasicConstraints() != -1) {
                    if ((x509Cert.getIssuerDN().getName().equals(x509Cert.getSubjectDN().getName())))
                        trustSet.add(new TrustAnchor(x509Cert, null));

                    X509CRL crl = UtiICPBrasill.getCRLFromDP(x509Cert);
                    crlCerts.add(crl);
                }
            }
        }
        // Cria um certstore com as CRLS da cadeia
        CollectionCertStoreParameters crlCertStoreParams = new CollectionCertStoreParameters(crlCerts);
        crlCertStore = CertStore.getInstance("Collection", crlCertStoreParams, "BC");

        Iterator iteradorSigners = colSign.iterator();

        Set<SignerData> signerTable = new HashSet();

        while (iteradorSigners.hasNext()) {
            Object signObject = iteradorSigners.next();
            if (signObject instanceof SignerInformation) {
                SignerInformation signerInfo = (SignerInformation) signObject;
                X509Certificate signerCertificate = null;
                if (!certificateStore.getCertificates(signerInfo.getSID()).isEmpty())
                    signerCertificate = (X509Certificate) certificateStore.getCertificates(signerInfo.getSID())
                            .toArray()[0];

                try {
                    PKIXBuilderParameters params = new PKIXBuilderParameters(trustSet, signerInfo.getSID());
                    params.addCertStore(certificateStore);
                    params.addCertStore(crlCertStore);

                    // TODO: Check CRL in validation process (do we have to include CRL in sign process?)
                    params.setRevocationEnabled(false);
                    // It's better check CRLs after path building process to be concluded

                    // Trata politica especifica da ICP
                    params.addCertPathChecker(new AssinaFacilExtPathChecker());

                    CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
                    PKIXCertPathBuilderResult certChainResult = (PKIXCertPathBuilderResult) builder
                            .build(params);
                    CertPath cp = certChainResult.getCertPath();

                    String revokeState = SignerData.OK;
                    // Valida se os certificados da cadeia ainda eso vlidos.

                    for (Certificate certTest : cp.getCertificates()) {
                        X509Certificate x509test = (X509Certificate) certTest;
                        revokeState = this.getRevokeState(x509test, crlCertStore, revokeState);
                    }
                    revokeState = this.getRevokeState(certChainResult.getTrustAnchor().getTrustedCert(),
                            crlCertStore, revokeState);
                    boolean isICP = this.checkKnowTrust(certChainResult.getTrustAnchor().getTrustedCert(),
                            trustCertStore);
                    String signatureState = this.signatureState(signerInfo, signerCertificate);
                    signerTable.add(
                            new SignerData(signerInfo, cp, certChainResult.getTrustAnchor().getTrustedCert(),
                                    isICP, signatureState, revokeState));

                } catch (CertPathBuilderException ex) {
                    Logger.getLogger(AssinaFacilApp.class.getName()).log(Level.SEVERE, "Nao Validado {0} {1}",
                            new Object[] { ex.getMessage(), ex });
                    String signatureState = this.signatureState(signerInfo, signerCertificate);
                    signerTable.add(new SignerData(signerInfo, signerCertificate, signatureState));

                } catch (InvalidAlgorithmParameterException ex) {

                } catch (Exception ex) {
                    Logger.getLogger(AssinaFacilApp.class.getName()).log(Level.SEVERE, "Nao Validado {0} {1}",
                            new Object[] { ex.getMessage(), ex });
                }
            }
        }

        AssinaFacilSignerDetail afsov = new AssinaFacilSignerDetail(mainWindow.getFrame(), true, signerTable);
        afsov.setVisible(true);

    } catch (InvalidAlgorithmParameterException ex) {
        Logger.getLogger(AssinaFacilApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(AssinaFacilApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchProviderException ex) {
        Logger.getLogger(AssinaFacilApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        mainWindow.setStatusMessage("No foi possvel extrair assinaturas do arquivo selecionado.");
        Logger.getLogger(AssinaFacilApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SignatureException ex) {
        mainWindow.setStatusMessage("No foi possvel extrair assinaturas do arquivo selecionado.");
        // Logger.getLogger(AssinaFacilApp.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CertStoreException ex) {
        mainWindow.setStatusMessage("Ocorreu um erro ao acessar os certificados armazenados.");
        Logger.getLogger(AssinaFacilApp.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:no.difi.oxalis.as2.util.MimeMessageHelperTest.java

License:EUPL

/**
 * verify the signature (assuming the cert is contained in the message)
 */// w  w w .ja  v  a 2s  .c  o m
private boolean verify(String resourceName, boolean debug) {

    System.out.println("Verifying resource " + resourceName + " (debug=" + debug + ")");
    String resourcePath = "real-mdn-examples/" + resourceName;

    try {
        // shortcuts lots of steps in the above test (parseLegalMimeMessageWithHeaders)
        MimeMultipart multipartSigned = (MimeMultipart) MimeMessageHelper
                .createMimeMessage(
                        MimeMessageHelperTest.class.getClassLoader().getResourceAsStream(resourcePath))
                .getContent();
        assertNotNull(multipartSigned);

        // verify signature

        SMIMESigned signedMessage = new SMIMESigned(multipartSigned);
        Store certs = signedMessage.getCertificates();

        SignerInformationStore signers = signedMessage.getSignerInfos();

        for (Object signerInformation : signers.getSigners()) {
            SignerInformation signer = (SignerInformation) signerInformation;
            Collection certCollection = certs.getMatches(signer.getSID());

            Iterator certIterator = certCollection.iterator();

            X509Certificate cert = new JcaX509CertificateConverter()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                    .getCertificate((X509CertificateHolder) certIterator.next());

            if (debug)
                System.out.println("Signing certificate : " + cert);

            SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(cert);
            if (signer.verify(signerInformationVerifier))
                return true;

        }

    } catch (Exception ex) {
        System.out.println("Verification failed with exception " + ex.getMessage());
    }

    return false;

}

From source file:no.difi.oxalis.as2.util.SignedMimeMessage.java

License:EUPL

void parseSignedMessage() {
    SMIMESignedParser smimeSignedParser;
    try {/*from  ww  w.  ja  va 2  s  .  co m*/
        // MimeMessageHelper.dumpMimePartToFile("/tmp/parseSignedMessage.txt", mimeMessage);
        smimeSignedParser = new SMIMESignedParser(new JcaDigestCalculatorProviderBuilder().build(),
                (MimeMultipart) mimeMessage.getContent());
    } catch (MessagingException | CMSException | IOException | OperatorCreationException e) {
        throw new IllegalStateException("Unable to create SMIMESignedParser: " + e.getMessage(), e);
    }

    Store certs;
    try {
        certs = smimeSignedParser.getCertificates();
    } catch (CMSException e) {
        throw new IllegalStateException("Unable to retrieve the certificates from signed message.");
    }

    //
    // SignerInfo blocks which contain the signatures
    //
    SignerInformationStore signerInfos;
    try {
        signerInfos = smimeSignedParser.getSignerInfos();
    } catch (CMSException e) {
        throw new IllegalStateException("Unable to get the Signer information from message. " + e.getMessage(),
                e);
    }

    Collection signers = signerInfos.getSigners();
    Iterator signersIterator = signers.iterator();

    //
    // Only a single signer, get the first and only certificate
    //
    if (signersIterator.hasNext()) {

        // Retrieves information on first and only signer
        SignerInformation signer = (SignerInformation) signersIterator.next();

        // Retrieves the collection of certificates for first and only signer
        @SuppressWarnings("unchecked")
        Collection certCollection = certs.getMatches(signer.getSID());

        // Retrieve the first certificate
        Iterator certIt = certCollection.iterator();
        if (certIt.hasNext()) {
            try {
                signersX509Certificate = new JcaX509CertificateConverter()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                        .getCertificate((X509CertificateHolder) certIt.next());
            } catch (CertificateException e) {
                throw new IllegalStateException("Unable to fetch certificate for signer. " + e.getMessage(), e);
            }
        } else {
            throw new IllegalStateException(
                    "Signers certificate was not found, unable to verify the signature");
        }

        // Verify that the signature is correct and that signersIterator was generated when the certificate was current
        /*
        try {
        if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(signersX509Certificate))) {
            throw new IllegalStateException("Verification of signer failed");
        }
        } catch (CMSException | OperatorCreationException e) {
        throw new IllegalStateException("Unable to verify the signer. " + e.getMessage(), e);
        }
        */

        String issuerDN = signersX509Certificate.getIssuerDN().toString();
        log.debug("Certificate issued by: " + issuerDN);

    } else {
        throw new IllegalStateException("There is no signer information available");
    }

}

From source file:no.difi.oxalis.as2.util.SMimeBC.java

License:EUPL

/**
 * http://stackoverflow.com/a/31557473/135001
 *//*from   w w w .j  a  va2  s.c o  m*/
public static X509Certificate verifySignature(Map hashes, byte[] signature)
        throws OxalisSecurityException, OxalisAs2InboundException {
    try {
        CMSSignedData signedData = new CMSSignedData(hashes, signature);

        Store store = signedData.getCertificates();
        SignerInformationStore signerInformationStore = signedData.getSignerInfos();

        for (SignerInformation signerInformation : signerInformationStore.getSigners()) {
            Collection<X509CertificateHolder> certCollection = store.getMatches(signerInformation.getSID());

            Iterator<X509CertificateHolder> certificateIterator = certCollection.iterator();

            if (!certificateIterator.hasNext())
                throw new OxalisAs2InboundException(Disposition.AUTHENTICATION_FAILED,
                        "Unable to find certificate in signature.", null);

            X509CertificateHolder certificateHolder = certificateIterator.next();
            X509Certificate certificate = x509CertificateConverter.getCertificate(certificateHolder);

            SignerInformationVerifier verifier = getSignerInfoVerifierBuilder().build(certificate);

            if (signerInformation.verify(verifier))
                return certificate;
        }

        throw new OxalisSecurityException("Unable to verify signature.");
    } catch (CMSSignerDigestMismatchException e) {
        throw new OxalisSecurityException("Invalid message digest.", e);
    } catch (CMSException | CertificateException | OperatorCreationException e) {
        throw new OxalisSecurityException(e.getMessage(), e);
    }
}