Search in sources :

Example 71 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project signer by demoiselle.

the class CAdESSigner method check.

/**
 * Validation is done only on digital signatures with a single signer. Valid
 * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 =
 * OID Data 1.2.840.113549.1.7.1
 *
 * @params content Is only necessary to inform if the PKCS7 package is NOT
 *         ATTACHED type. If it is of type attached, this parameter will be
 *         replaced by the contents of the PKCS7 package.
 * @params signedData Value in bytes of the PKCS7 package, such as the
 *         contents of a ".p7s" file. It is not only signature as in the
 *         case of PKCS1.
 */
@SuppressWarnings("unchecked")
// TODO: Implementar validação de co-assinaturas
@Override
@Deprecated
public boolean check(byte[] content, byte[] signedData) throws SignerException {
    Security.addProvider(new BouncyCastleProvider());
    CMSSignedData cmsSignedData = null;
    try {
        if (content == null) {
            if (this.checkHash) {
                cmsSignedData = new CMSSignedData(this.hashes, signedData);
                this.checkHash = false;
            } else {
                cmsSignedData = new CMSSignedData(signedData);
            }
        } else {
            cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData);
        }
    } catch (CMSException ex) {
        throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex);
    }
    // Quantidade inicial de assinaturas validadas
    int verified = 0;
    Store<?> certStore = cmsSignedData.getCertificates();
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    Iterator<?> it = signers.getSigners().iterator();
    // Realização da verificação básica de todas as assinaturas
    while (it.hasNext()) {
        try {
            SignerInformation signer = (SignerInformation) it.next();
            SignerInformationStore s = signer.getCounterSignatures();
            SignatureInformations si = new SignatureInformations();
            logger.info("Foi(ram) encontrada(s) " + s.size() + " contra-assinatura(s).");
            Collection<?> certCollection = certStore.getMatches(signer.getSID());
            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();
            X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
            PeriodValidator pV = new PeriodValidator();
            try {
                pV.validate(varCert);
            } catch (CertificateValidatorException cve) {
                si.getValidatorErrors().add(cve.getMessage());
            }
            CRLValidator cV = new CRLValidator();
            try {
                cV.validate(varCert);
            } catch (CertificateValidatorCRLException cvce) {
                si.getValidatorErrors().add(cvce.getMessage());
            }
            if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) {
                verified++;
                logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified));
            }
            // Realiza a verificação dos atributos assinados
            logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
            AttributeTable signedAttributes = signer.getSignedAttributes();
            if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) {
                throw new SignerException(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
            }
            // Realiza a verificação dos atributos não assinados
            logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
            AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
            if ((unsignedAttributes == null) || (unsignedAttributes != null && unsignedAttributes.size() == 0)) {
                logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found"));
            }
            // Mostra data e  hora da assinatura, não é carimbo de tempo
            Attribute signingTime = signedAttributes.get(CMSAttributes.signingTime);
            Date dataHora = null;
            if (signingTime != null) {
                dataHora = (((ASN1UTCTime) signingTime.getAttrValues().getObjectAt(0)).getDate());
                logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora));
            } else {
                logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D"));
            }
            logger.info(cadesMessagesBundle.getString("info.attribute.validation"));
            // Valida o atributo ContentType
            Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType);
            if (attributeContentType == null) {
                throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
            }
            if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
                throw new SignerException(cadesMessagesBundle.getString("error.content.not.data"));
            }
            // Validando o atributo MessageDigest
            Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest);
            if (attributeMessageDigest == null) {
                throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest"));
            }
            // Validando o atributo MessageDigest
            Attribute idSigningPolicy = null;
            idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId()));
            if (idSigningPolicy == null) {
                throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "idSigningPolicy"));
            }
            // Verificando timeStamp
            try {
                Attribute attributeTimeStamp = null;
                attributeTimeStamp = unsignedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
                if (attributeTimeStamp != null) {
                    byte[] varSignature = signer.getSignature();
                    Timestamp varTimeStampSigner = validateTimestamp(attributeTimeStamp, varSignature);
                    si.setTimeStampSigner(varTimeStampSigner);
                }
            } catch (Exception ex) {
            // nas assinaturas feitas na applet o unsignedAttributes.get gera exceção.
            }
            LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance().getCertificateChain(varCert);
            si.setSignDate(dataHora);
            si.setChain(varChain);
            si.setSignaturePolicy(signaturePolicy);
            this.getSignatureInfo().add(si);
        } catch (OperatorCreationException | java.security.cert.CertificateException ex) {
            throw new SignerException(ex);
        } catch (CMSException ex) {
            // When file is mismatch with sign
            if (ex instanceof CMSSignerDigestMismatchException)
                throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex);
            else
                throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex);
        } catch (ParseException e) {
            throw new SignerException(e);
        }
    }
    logger.info(cadesMessagesBundle.getString("info.signature.verified", verified));
    // TODO Efetuar o parsing da estrutura CMS
    return true;
}
Also used : Attribute(org.bouncycastle.asn1.cms.Attribute) SignedOrUnsignedAttribute(org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.SignedOrUnsignedAttribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) ASN1UTCTime(org.bouncycastle.asn1.ASN1UTCTime) SignerInformation(org.bouncycastle.cms.SignerInformation) CertificateException(java.security.cert.CertificateException) CRLValidator(org.demoiselle.signer.core.validator.CRLValidator) Timestamp(org.demoiselle.signer.timestamp.Timestamp) SignatureInformations(org.demoiselle.signer.policy.impl.cades.SignatureInformations) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) PeriodValidator(org.demoiselle.signer.core.validator.PeriodValidator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) CMSSignerDigestMismatchException(org.bouncycastle.cms.CMSSignerDigestMismatchException) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CertificateValidatorCRLException(org.demoiselle.signer.core.exception.CertificateValidatorCRLException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateTrustPoint(org.demoiselle.signer.policy.engine.asn1.etsi.CertificateTrustPoint) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) CertificateValidatorException(org.demoiselle.signer.core.exception.CertificateValidatorException) ParseException(java.text.ParseException) TSPException(org.bouncycastle.tsp.TSPException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CMSException(org.bouncycastle.cms.CMSException) CertificateValidatorCRLException(org.demoiselle.signer.core.exception.CertificateValidatorCRLException) CMSSignerDigestMismatchException(org.bouncycastle.cms.CMSSignerDigestMismatchException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) LinkedList(java.util.LinkedList) CertificateValidatorException(org.demoiselle.signer.core.exception.CertificateValidatorException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ParseException(java.text.ParseException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CMSException(org.bouncycastle.cms.CMSException)

Example 72 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project AndroidAsync by koush.

the class AsyncSSLSocketWrapper method selfSign.

private static Certificate selfSign(KeyPair keyPair, String subjectDN) throws Exception {
    Provider bcProvider = new BouncyCastleProvider();
    Security.addProvider(bcProvider);
    long now = System.currentTimeMillis();
    Date startDate = new Date(now);
    X500Name dnName = new X500Name("CN=" + subjectDN);
    // <-- Using the current timestamp as the certificate serial number
    BigInteger certSerialNumber = new BigInteger(Long.toString(now));
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(startDate);
    // <-- 1 Yr validity
    calendar.add(Calendar.YEAR, 1);
    Date endDate = calendar.getTime();
    // <-- Use appropriate signature algorithm based on your keyPair algorithm.
    String signatureAlgorithm = "SHA256WithRSA";
    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());
    JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, startDate, endDate, dnName, keyPair.getPublic());
    // Extensions --------------------------
    // Basic Constraints
    // <-- true for CA, false for EndEntity
    BasicConstraints basicConstraints = new BasicConstraints(true);
    // Basic Constraints is usually marked as critical.
    certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);
    return new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
}
Also used : JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) Calendar(java.util.Calendar) ContentSigner(org.bouncycastle.operator.ContentSigner) X500Name(org.bouncycastle.asn1.x500.X500Name) Date(java.util.Date) Provider(java.security.Provider) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BigInteger(java.math.BigInteger) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 73 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project ddf by codice.

the class OcspChecker method logResponse.

private void logResponse(OCSPResp response) {
    BasicOCSPResp basicOCSPResp;
    BasicOCSPResponse basicOCSPResponse;
    try {
        basicOCSPResp = (BasicOCSPResp) response.getResponseObject();
        basicOCSPResponse = BasicOCSPResponse.getInstance(((BasicOCSPResp) response.getResponseObject()).getEncoded());
        StringBuilder logBuilder = new StringBuilder();
        logBuilder.append("OCSP Response: \n");
        logBuilder.append("  responseStatus: " + getValueOrDefault(response.getStatus(), "") + "\n");
        logBuilder.append("  responseBytes:\n");
        logBuilder.append("  responseType: " + getValueOrDefault(basicOCSPResponse, "").getClass().getSimpleName() + "\n");
        logBuilder.append("    response:\n");
        logBuilder.append("      tbsResponseData:\n");
        if (basicOCSPResponse.getTbsResponseData() != null) {
            logBuilder.append("        version: " + getValueOrDefault(basicOCSPResponse.getTbsResponseData().getVersion(), "").toString() + "\n");
            logBuilder.append("        responderId:\n");
            if (basicOCSPResponse.getTbsResponseData().getResponderID() != null) {
                logBuilder.append("          byName: " + getValueOrDefault(basicOCSPResponse.getTbsResponseData().getResponderID().getName(), "").toString() + "\n");
                logBuilder.append("          byKey: " + getValueOrDefault(Arrays.toString(basicOCSPResponse.getTbsResponseData().getResponderID().getKeyHash()), "") + "\n");
            } else {
                logBuilder.append("          byName:\n");
            }
            if (basicOCSPResponse.getTbsResponseData().getProducedAt() != null) {
                logBuilder.append("        producedAt: " + getValueOrDefault(basicOCSPResponse.getTbsResponseData().getProducedAt().getTimeString(), "") + "\n");
            } else {
                logBuilder.append("        producedAt:\n");
            }
        }
        logBuilder.append("        responses:\n");
        if (basicOCSPResp.getResponses() != null) {
            SingleResp[] singleResps = basicOCSPResp.getResponses();
            for (int i = 0; i < singleResps.length; i++) {
                CertificateID certificateID = singleResps[i].getCertID();
                if (certificateID != null) {
                    logBuilder.append("        certID #: " + i + "\n");
                    logBuilder.append("          hashAlgorithm: " + getValueOrDefault(certificateID.getHashAlgOID(), "").toString() + "\n");
                    logBuilder.append("          issuerNameHash: " + getValueOrDefault(Arrays.toString(certificateID.getIssuerNameHash()), "") + "\n");
                    logBuilder.append("          issuerKeyHash: " + getValueOrDefault(Arrays.toString(certificateID.getIssuerKeyHash()), "") + "\n");
                    logBuilder.append("          cert serial number: " + getValueOrDefault(certificateID.getSerialNumber(), "") + "\n");
                    logBuilder.append("        certStatus: " + getValueOrDefault(singleResps[i].getCertStatus(), "good").getClass().getSimpleName() + "\n");
                    logBuilder.append("        thisUpdate: " + getValueOrDefault(singleResps[i].getThisUpdate(), "").toString() + "\n");
                    logBuilder.append("        nextUpdate: " + getValueOrDefault(singleResps[i].getNextUpdate(), "").toString() + "\n");
                }
            }
        }
        if (basicOCSPResp.getSignatureAlgorithmID() != null) {
            logBuilder.append("      signatureAlgorithm: " + getValueOrDefault(basicOCSPResp.getSignatureAlgorithmID().getAlgorithm(), "").toString() + "\n");
        }
        logBuilder.append("      signature: " + getValueOrDefault(Arrays.toString(basicOCSPResp.getSignature()), "") + "\n");
        logBuilder.append("      certs:\n");
        if (basicOCSPResp.getCerts() != null) {
            X509CertificateHolder[] x509CertificateHolders = basicOCSPResp.getCerts();
            for (int i = 0; i < x509CertificateHolders.length; i++) {
                logBuilder.append("        certificate: " + i + "\n");
                logBuilder.append("          issuer: " + getValueOrDefault(x509CertificateHolders[i].getIssuer(), "").toString() + "\n");
                logBuilder.append("          subject: " + getValueOrDefault(x509CertificateHolders[i].getSubject(), "").toString() + "\n");
                if (basicOCSPResp.getSignatureAlgorithmID() != null) {
                    logBuilder.append("          signatureAlgorithm: " + getValueOrDefault(x509CertificateHolders[i].getSignatureAlgorithm().getAlgorithm(), "").toString() + "\n");
                }
                logBuilder.append("          start date: " + getValueOrDefault(x509CertificateHolders[i].toASN1Structure().getStartDate(), "").toString() + "\n");
                logBuilder.append("          end date: " + getValueOrDefault(x509CertificateHolders[i].toASN1Structure().getEndDate(), "").toString() + "\n");
                logBuilder.append("          cert serial number: " + getValueOrDefault(x509CertificateHolders[i].getSerialNumber(), "") + "\n");
            }
        }
        LOGGER.trace(logBuilder.toString());
    } catch (IOException | OCSPException e) {
        LOGGER.trace("Could not log response, issue converting response to a BasicOcspResponse.", e);
    }
}
Also used : BasicOCSPResponse(org.bouncycastle.asn1.ocsp.BasicOCSPResponse) CertificateID(org.bouncycastle.cert.ocsp.CertificateID) OCSPException(org.bouncycastle.cert.ocsp.OCSPException) BasicOCSPResp(org.bouncycastle.cert.ocsp.BasicOCSPResp) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) IOException(java.io.IOException) SingleResp(org.bouncycastle.cert.ocsp.SingleResp)

Example 74 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project athenz by yahoo.

the class CryptoTest method testSignVerifyExtractedECKey.

@Test
public void testSignVerifyExtractedECKey() {
    PrivateKey privateKey = Crypto.loadPrivateKey(ecPrivateKey);
    assertNotNull(privateKey);
    String signature = Crypto.sign(serviceToken, privateKey);
    PublicKey publicKey = Crypto.extractPublicKey(privateKey);
    assertNotNull(publicKey);
    assertTrue(Crypto.verify(serviceToken, publicKey, signature));
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) Test(org.testng.annotations.Test)

Example 75 with Signature

use of org.bouncycastle.asn1.ocsp.Signature in project athenz by yahoo.

the class CryptoTest method testSignVerifyRSAKey.

@Test
public void testSignVerifyRSAKey() {
    PrivateKey privateKey = Crypto.loadPrivateKey(rsaPrivateKey);
    assertNotNull(privateKey);
    String signature = Crypto.sign(serviceToken, privateKey);
    assertEquals(signature, serviceRSASignature);
    PublicKey publicKey = Crypto.loadPublicKey(rsaPublicKey);
    assertNotNull(publicKey);
    assertTrue(Crypto.verify(serviceToken, publicKey, signature));
}
Also used : PrivateKey(java.security.PrivateKey) PublicKey(java.security.PublicKey) DERIA5String(org.bouncycastle.asn1.DERIA5String) Test(org.testng.annotations.Test)

Aggregations

IOException (java.io.IOException)58 DERIA5String (org.bouncycastle.asn1.DERIA5String)36 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)31 DERBitString (org.bouncycastle.asn1.DERBitString)31 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)30 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)30 InvalidKeyException (java.security.InvalidKeyException)28 X509Certificate (java.security.cert.X509Certificate)28 SignatureException (java.security.SignatureException)27 DERSequence (org.bouncycastle.asn1.DERSequence)26 PublicKey (java.security.PublicKey)25 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)23 DEROctetString (org.bouncycastle.asn1.DEROctetString)22 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)22 Signature (java.security.Signature)21 CertificateException (java.security.cert.CertificateException)21 BigInteger (java.math.BigInteger)20 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)19 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)18 NoSuchProviderException (java.security.NoSuchProviderException)16