List of usage examples for org.bouncycastle.cms CMSProcessable getContent
public Object getContent();
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java
License:Open Source License
@Override public byte[] getAttached(byte[] signed, boolean validate) { byte[] result = null; if (validate) { this.check(null, signed); }//w w w. ja v a 2s .co m CMSSignedData signedData = null; try { signedData = new CMSSignedData(signed); } catch (CMSException exception) { throw new SignerException("Invalid bytes for a package PKCS7", exception); } try { CMSProcessable contentProcessable = signedData.getSignedContent(); if (contentProcessable != null) { result = (byte[]) contentProcessable.getContent(); } } catch (Exception exception) { throw new SignerException("Error on get content from PKCS7", exception); } return result; }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_1_0.java
License:Open Source License
@Override public void validate(byte[] content, byte[] contentSigned) { if (contentSigned == null || contentSigned.length == 0) { throw new SignaturePolicyException("Content signed is null"); }//from w ww . ja v a2 s. c o m X509Certificate certificate = null; PublicKey publicKey = null; /* * Validando a integridade do arquivo */ CMSSignedData signedData = null; try { if (content == null) { signedData = new CMSSignedData(contentSigned); } else { signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned); } } catch (CMSException exception) { throw new SignerException("Invalid bytes for a package PKCS7", exception); } /* * Validando as informaes da assinatura */ SignerInformationStore signerInformationStore = signedData.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator() .next(); /* * Retirando o Certificado Digital e a chave Pblica da assinatura */ try { CertStore certs; try { Security.addProvider(new BouncyCastleProvider()); certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> collCertificados = certs .getCertificates(signerInformation.getSID()); if (!collCertificados.isEmpty()) { certificate = (X509Certificate) collCertificados.iterator().next(); publicKey = certificate.getPublicKey(); } } catch (NoSuchAlgorithmException exception) { throw new SignerException(exception); } catch (NoSuchProviderException exception) { throw new SignerException(exception); } catch (CMSException exception) { throw new SignerException(exception); } catch (CertStoreException exception) { throw new SignerException(exception); } } catch (SignerException exception) { throw new SignerException( "Error on get information about certificates and public keys from a package PKCS7", exception); } /* * Validando os atributos assinados */ AttributeTable signedAttributesTable = signerInformation.getSignedAttributes(); /* * Validando o atributo ContentType */ org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable .get(CMSAttributes.contentType); if (attributeContentType == null) { throw new SignerException("Package PKCS7 without attribute ContentType"); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { throw new SignerException("ContentType isn't a DATA type"); } /* * Com o atributo ContentType vlido, extrair o contedo assinado, caso * possua o contedo atached */ try { CMSProcessable contentProcessable = signedData.getSignedContent(); if (contentProcessable != null) { content = (byte[]) contentProcessable.getContent(); } } catch (Exception exception) { throw new SignerException(exception); } /* * Validando o atributo MessageDigest */ org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable .get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException("Package PKCS7 without attribute MessageDigest"); } Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject(); ASN1OctetString octeto = ASN1OctetString.getInstance(der); byte[] hashContentSigned = octeto.getOctets(); String algorithm = SignerAlgorithmEnum .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString()) .getAlgorithmHash(); if (!algorithm.equals(DigestAlgorithmEnum.SHA_1.getAlgorithm())) { throw new SignerException("Algoritmo de resumo invlido para esta poltica"); } Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_1.getAlgorithm()); byte[] hashContent = digest.digest(content); if (!MessageDigest.isEqual(hashContentSigned, hashContent)) { throw new SignerException("Hash not equal"); } try { signerInformation.verify(publicKey, "BC"); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException("Invalid signature", e); } // Valida a cadeia de certificao de um arquivo assinado //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_1_0, CertPathEncoding.PKCS7); Date dataSigner = null; try { org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable .get(CMSAttributes.signingTime); ASN1Set valorDateSigner = attributeSigningTime.getAttrValues(); DERSet derSet = (DERSet) valorDateSigner.getDERObject(); DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0); dataSigner = time.getAdjustedDate(); } catch (ParseException ex) { throw new SignerException("SigningTime error", ex); } //Para a verso 1.0, o perodo para assinatura desta PA de 31/10/2008 a 31/12/2014. // Calendar calendar = GregorianCalendar.getInstance(); // calendar.set(2008, Calendar.OCTOBER, 31, 0, 0, 0); // Date firstDate = calendar.getTime(); // // calendar.set(2014, Calendar.DECEMBER, 31, 23, 59, 59); // Date lastDate = calendar.getTime(); // // if (dataSigner != null) { // if (dataSigner.before(firstDate)) { // throw new SignerException("Invalid signing time. Not valid before 10/31/2008"); // } // if (dataSigner.after(lastDate)) { // throw new SignerException("Invalid signing time. Not valid after 12/31/2014"); // } // } else { // throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null"); // } }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_1_1.java
License:Open Source License
@Override public void validate(byte[] content, byte[] contentSigned) { if (contentSigned == null || contentSigned.length == 0) { throw new SignaturePolicyException("Content signed is null"); }// ww w .j a v a 2 s . c om X509Certificate certificate = null; PublicKey publicKey = null; // Validando a integridade do arquivo CMSSignedData signedData = null; try { if (content == null) { signedData = new CMSSignedData(contentSigned); } else { signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned); } } catch (CMSException exception) { throw new SignerException("Invalid bytes for a package PKCS7", exception); } // Validando as informaes da assinatura SignerInformationStore signerInformationStore = signedData.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator() .next(); // Retirando o Certificado Digital e a chave Pblica da assinatura try { CertStore certs; try { Security.addProvider(new BouncyCastleProvider()); certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> collCertificados = certs .getCertificates(signerInformation.getSID()); if (!collCertificados.isEmpty()) { certificate = (X509Certificate) collCertificados.iterator().next(); publicKey = certificate.getPublicKey(); } } catch (NoSuchAlgorithmException exception) { throw new SignerException(exception); } catch (NoSuchProviderException exception) { throw new SignerException(exception); } catch (CMSException exception) { throw new SignerException(exception); } catch (CertStoreException exception) { throw new SignerException(exception); } } catch (SignerException exception) { throw new SignerException( "Error on get information about certificates and public keys from a package PKCS7", exception); } // Validando os atributos assinados AttributeTable signedAttributesTable = signerInformation.getSignedAttributes(); // Validando o atributo ContentType org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable .get(CMSAttributes.contentType); if (attributeContentType == null) { throw new SignerException("Package PKCS7 without attribute ContentType"); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { throw new SignerException("ContentType isn't a DATA type"); } // Com o atributo ContentType vlido, extrair o contedo assinado, caso // possua o contedo atached try { CMSProcessable contentProcessable = signedData.getSignedContent(); if (contentProcessable != null) { content = (byte[]) contentProcessable.getContent(); } } catch (Exception exception) { throw new SignerException(exception); } // Validando o atributo MessageDigest org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable .get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException("Package PKCS7 without attribute MessageDigest"); } Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject(); ASN1OctetString octeto = ASN1OctetString.getInstance(der); byte[] hashContentSigned = octeto.getOctets(); String algorithm = SignerAlgorithmEnum .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString()) .getAlgorithmHash(); if (!algorithm.equals(DigestAlgorithmEnum.SHA_1.getAlgorithm()) && !algorithm.equals(DigestAlgorithmEnum.SHA_256.getAlgorithm())) { throw new SignerException("Algoritmo de resumo invlido para esta poltica"); } Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(algorithm); byte[] hashContent = digest.digest(content); if (!MessageDigest.isEqual(hashContentSigned, hashContent)) { throw new SignerException("Hash not equal"); } try { signerInformation.verify(publicKey, "BC"); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException("Invalid signature", e); } // O atributo signingCertificate deve conter referncia apenas ao // certificado do signatrio. org.bouncycastle.asn1.cms.Attribute signedSigningCertificate = signedAttributesTable .get(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.12")); if (signedSigningCertificate != null) { // Uso futuro, para processamento dos valores ASN1Set set = signedSigningCertificate.getAttrValues(); } else { throw new SignerException("O Atributo signingCertificate no pode ser nulo."); } // Valida a cadeia de certificao de um arquivo assinado //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_1_1, CertPathEncoding.PKCS7); Date dataSigner = null; try { org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable .get(CMSAttributes.signingTime); ASN1Set valorDateSigner = attributeSigningTime.getAttrValues(); DERSet derSet = (DERSet) valorDateSigner.getDERObject(); DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0); dataSigner = time.getAdjustedDate(); } catch (Throwable error) { throw new SignerException("SigningTime error", error); } //Para a verso 1.1, o perodo para assinatura desta PA de 26/12/2011 a 29/02/2012. // Calendar calendar = GregorianCalendar.getInstance(); // calendar.set(2011, Calendar.DECEMBER, 26, 0, 0, 0); // Date firstDate = calendar.getTime(); // // calendar.set(2012, Calendar.FEBRUARY, 29, 23, 59, 59); // Date lastDate = calendar.getTime(); // // if (dataSigner != null) { // if (dataSigner.before(firstDate)) { // throw new SignerException("Invalid signing time. Not valid before 12/26/2011"); // } // if (dataSigner.after(lastDate)) { // throw new SignerException("Invalid signing time. Not valid after 02/29/2012"); // } // } else { // throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null"); // } }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_2_0.java
License:Open Source License
@Override public void validate(byte[] content, byte[] contentSigned) { if (contentSigned == null || contentSigned.length == 0) { throw new SignaturePolicyException("Content signed is null"); }//from w w w.j a v a 2s .co m X509Certificate certificate = null; PublicKey publicKey = null; // Validando a integridade do arquivo CMSSignedData signedData = null; try { if (content == null) { signedData = new CMSSignedData(contentSigned); } else { signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned); } } catch (CMSException exception) { throw new SignerException("Invalid bytes for a package PKCS7", exception); } // Validando as informaes da assinatura SignerInformationStore signerInformationStore = signedData.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator() .next(); // Retirando o Certificado Digital e a chave Pblica da assinatura try { CertStore certs; try { Security.addProvider(new BouncyCastleProvider()); certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> collCertificados = certs .getCertificates(signerInformation.getSID()); if (!collCertificados.isEmpty()) { certificate = (X509Certificate) collCertificados.iterator().next(); publicKey = certificate.getPublicKey(); } } catch (NoSuchAlgorithmException exception) { throw new SignerException(exception); } catch (NoSuchProviderException exception) { throw new SignerException(exception); } catch (CMSException exception) { throw new SignerException(exception); } catch (CertStoreException exception) { throw new SignerException(exception); } } catch (SignerException exception) { throw new SignerException( "Error on get information about certificates and public keys from a package PKCS7", exception); } // Validando os atributos assinados AttributeTable signedAttributesTable = signerInformation.getSignedAttributes(); // Validando o atributo ContentType org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable .get(CMSAttributes.contentType); if (attributeContentType == null) { throw new SignerException("Package PKCS7 without attribute ContentType"); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { throw new SignerException("ContentType isn't a DATA type"); } // Com o atributo ContentType vlido, extrair o contedo assinado, caso // possua o contedo atached try { CMSProcessable contentProcessable = signedData.getSignedContent(); if (contentProcessable != null) { content = (byte[]) contentProcessable.getContent(); } } catch (Exception exception) { throw new SignerException(exception); } // Validando o atributo MessageDigest org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable .get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException("Package PKCS7 without attribute MessageDigest"); } Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject(); ASN1OctetString octeto = ASN1OctetString.getInstance(der); byte[] hashContentSigned = octeto.getOctets(); String algorithm = SignerAlgorithmEnum .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString()) .getAlgorithmHash(); if (!algorithm.equals(DigestAlgorithmEnum.SHA_256.getAlgorithm())) { throw new SignerException("Algoritmo de resumo invlido para esta poltica"); } Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_256.getAlgorithm()); byte[] hashContent = digest.digest(content); if (!MessageDigest.isEqual(hashContentSigned, hashContent)) { throw new SignerException("Hash not equal"); } try { signerInformation.verify(publicKey, "BC"); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException("Invalid signature", e); } // O atributo signingCertificate deve conter referncia apenas ao // certificado do signatrio. org.bouncycastle.asn1.cms.Attribute signedSigningCertificate = signedAttributesTable .get(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.12")); if (signedSigningCertificate != null) { // Uso futuro, para processamento dos valores ASN1Set set = signedSigningCertificate.getAttrValues(); } else { throw new SignerException("O Atributo signingCertificate no pode ser nulo."); } // Valida a cadeia de certificao de um arquivo assinado //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_2_0, CertPathEncoding.PKCS7); Date dataSigner = null; try { org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable .get(CMSAttributes.signingTime); ASN1Set valorDateSigner = attributeSigningTime.getAttrValues(); DERSet derSet = (DERSet) valorDateSigner.getDERObject(); DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0); dataSigner = time.getAdjustedDate(); } catch (ParseException ex) { } //Para a verso 2.0, o perodo para assinatura desta PA de 26/12/2011 a 21/06/2023. Calendar calendar = GregorianCalendar.getInstance(); calendar.set(2011, Calendar.DECEMBER, 26, 0, 0, 0); Date firstDate = calendar.getTime(); calendar.set(2023, Calendar.JUNE, 21, 23, 59, 59); Date lastDate = calendar.getTime(); if (dataSigner != null) { if (dataSigner.before(firstDate)) { throw new SignerException("Invalid signing time. Not valid before 12/26/2011"); } if (dataSigner.after(lastDate)) { throw new SignerException("Invalid signing time. Not valid after 06/21/2023"); } } else { throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null"); } }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_2_1.java
License:Open Source License
@Override public void validate(byte[] content, byte[] contentSigned) { if (contentSigned == null || contentSigned.length == 0) { throw new SignaturePolicyException("Content signed is null"); }//from ww w. j av a 2s. co m X509Certificate certificate = null; PublicKey publicKey = null; // Validando a integridade do arquivo CMSSignedData signedData = null; try { if (content == null) { signedData = new CMSSignedData(contentSigned); } else { signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned); } } catch (CMSException exception) { throw new SignerException("Invalid bytes for a package PKCS7", exception); } // Validando as informaes da assinatura SignerInformationStore signerInformationStore = signedData.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator() .next(); // Retirando o Certificado Digital e a chave Pblica da assinatura try { CertStore certs; try { Security.addProvider(new BouncyCastleProvider()); certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> collCertificados = certs .getCertificates(signerInformation.getSID()); if (!collCertificados.isEmpty()) { certificate = (X509Certificate) collCertificados.iterator().next(); publicKey = certificate.getPublicKey(); } } catch (NoSuchAlgorithmException exception) { throw new SignerException(exception); } catch (NoSuchProviderException exception) { throw new SignerException(exception); } catch (CMSException exception) { throw new SignerException(exception); } catch (CertStoreException exception) { throw new SignerException(exception); } } catch (SignerException exception) { throw new SignerException( "Error on get information about certificates and public keys from a package PKCS7", exception); } // Validando os atributos assinados AttributeTable signedAttributesTable = signerInformation.getSignedAttributes(); // Validando o atributo ContentType org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable .get(CMSAttributes.contentType); if (attributeContentType == null) { throw new SignerException("Package PKCS7 without attribute ContentType"); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { throw new SignerException("ContentType isn't a DATA type"); } // Com o atributo ContentType vlido, extrair o contedo assinado, caso // possua o contedo atached try { CMSProcessable contentProcessable = signedData.getSignedContent(); if (contentProcessable != null) { content = (byte[]) contentProcessable.getContent(); } } catch (Exception exception) { throw new SignerException(exception); } // Validando o atributo MessageDigest org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable .get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException("Package PKCS7 without attribute MessageDigest"); } Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject(); ASN1OctetString octeto = ASN1OctetString.getInstance(der); byte[] hashContentSigned = octeto.getOctets(); String algorithm = SignerAlgorithmEnum .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString()) .getAlgorithmHash(); if (!algorithm.equals(DigestAlgorithmEnum.SHA_256.getAlgorithm())) { throw new SignerException("Algoritmo de resumo invlido para esta poltica"); } Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_256.getAlgorithm()); byte[] hashContent = digest.digest(content); if (!MessageDigest.isEqual(hashContentSigned, hashContent)) { throw new SignerException("Hash not equal"); } try { signerInformation.verify(publicKey, "BC"); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException("Invalid signature", e); } // Valida a cadeia de certificao de um arquivo assinado //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_2_0, CertPathEncoding.PKCS7); Date dataSigner = null; try { org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable .get(CMSAttributes.signingTime); ASN1Set valorDateSigner = attributeSigningTime.getAttrValues(); DERSet derSet = (DERSet) valorDateSigner.getDERObject(); DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0); dataSigner = time.getAdjustedDate(); } catch (Throwable error) { } //Para a verso 2.1, o perodo para assinatura desta PA de 06/03/2012 a 21/06/2023. Calendar calendar = GregorianCalendar.getInstance(); calendar.set(2012, Calendar.MARCH, 06, 0, 0, 0); Date firstDate = calendar.getTime(); calendar.set(2023, Calendar.JUNE, 21, 23, 59, 59); Date lastDate = calendar.getTime(); if (dataSigner != null) { if (dataSigner.before(firstDate)) { throw new SignerException("Invalid signing time. Not valid before 03/06/2012"); } if (dataSigner.after(lastDate)) { throw new SignerException("Invalid signing time. Not valid after 06/21/2023"); } } else { throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null"); } // O atributo signingCertificate deve conter referncia apenas ao // certificado do signatrio. org.bouncycastle.asn1.cms.Attribute signedSigningCertificate = signedAttributesTable .get(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.47")); if (signedSigningCertificate != null) { // Uso futuro, para processamento dos valores ASN1Set set = signedSigningCertificate.getAttrValues(); } else { throw new SignerException("O Atributo signingCertificate no pode ser nulo."); } }
From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.policies.ADRBCMS_2_2.java
License:Open Source License
@Override public void validate(byte[] content, byte[] contentSigned) { if (contentSigned == null || contentSigned.length == 0) { throw new SignaturePolicyException("Content signed is null"); }//from w w w .j a va 2s . c o m X509Certificate certificate = null; PublicKey publicKey = null; // Validando a integridade do arquivo CMSSignedData signedData = null; try { if (content == null) { signedData = new CMSSignedData(contentSigned); } else { signedData = new CMSSignedData(new CMSProcessableByteArray(content), contentSigned); } } catch (CMSException exception) { throw new SignerException("Invalid bytes for a package PKCS7", exception); } // Validando as informaes da assinatura SignerInformationStore signerInformationStore = signedData.getSignerInfos(); SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator() .next(); // Retirando o Certificado Digital e a chave Pblica da assinatura try { CertStore certs; try { Security.addProvider(new BouncyCastleProvider()); certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Collection<? extends Certificate> collCertificados = certs .getCertificates(signerInformation.getSID()); if (!collCertificados.isEmpty()) { certificate = (X509Certificate) collCertificados.iterator().next(); publicKey = certificate.getPublicKey(); } } catch (NoSuchAlgorithmException exception) { throw new SignerException(exception); } catch (NoSuchProviderException exception) { throw new SignerException(exception); } catch (CMSException exception) { throw new SignerException(exception); } catch (CertStoreException exception) { throw new SignerException(exception); } } catch (SignerException exception) { throw new SignerException( "Error on get information about certificates and public keys from a package PKCS7", exception); } // Validando os atributos assinados AttributeTable signedAttributesTable = signerInformation.getSignedAttributes(); // Validando o atributo ContentType org.bouncycastle.asn1.cms.Attribute attributeContentType = signedAttributesTable .get(CMSAttributes.contentType); if (attributeContentType == null) { throw new SignerException("Package PKCS7 without attribute ContentType"); } if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) { throw new SignerException("ContentType isn't a DATA type"); } // Com o atributo ContentType vlido, extrair o contedo assinado, caso // possua o contedo atached try { CMSProcessable contentProcessable = signedData.getSignedContent(); if (contentProcessable != null) { content = (byte[]) contentProcessable.getContent(); } } catch (Exception exception) { throw new SignerException(exception); } // Validando o atributo MessageDigest org.bouncycastle.asn1.cms.Attribute attributeMessageDigest = signedAttributesTable .get(CMSAttributes.messageDigest); if (attributeMessageDigest == null) { throw new SignerException("Package PKCS7 without attribute MessageDigest"); } Object der = attributeMessageDigest.getAttrValues().getObjectAt(0).getDERObject(); ASN1OctetString octeto = ASN1OctetString.getInstance(der); byte[] hashContentSigned = octeto.getOctets(); String algorithm = SignerAlgorithmEnum .getSignerOIDAlgorithmHashEnum(signerInformation.getDigestAlgorithmID().getObjectId().toString()) .getAlgorithmHash(); if (!(DigestAlgorithmEnum.SHA_256.getAlgorithm().equalsIgnoreCase(algorithm) || DigestAlgorithmEnum.SHA_512.getAlgorithm().equalsIgnoreCase(algorithm))) { throw new SignerException("Algoritmo de resumo invlido para esta poltica"); } Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(algorithm); byte[] hashContent = digest.digest(content); if (!MessageDigest.isEqual(hashContentSigned, hashContent)) { throw new SignerException("Hash not equal"); } try { signerInformation.verify(publicKey, "BC"); } catch (NoSuchAlgorithmException e) { throw new SignerException(e); } catch (NoSuchProviderException e) { throw new SignerException(e); } catch (CMSException e) { throw new SignerException("Invalid signature", e); } // Valida a cadeia de certificao de um arquivo assinado //ValidadorUtil.validate(contentSigned, OIDICPBrasil.POLICY_ID_AD_RB_CMS_V_2_0, CertPathEncoding.PKCS7); Date dataSigner = null; try { org.bouncycastle.asn1.cms.Attribute attributeSigningTime = signedAttributesTable .get(CMSAttributes.signingTime); ASN1Set valorDateSigner = attributeSigningTime.getAttrValues(); DERSet derSet = (DERSet) valorDateSigner.getDERObject(); DERUTCTime time = (DERUTCTime) derSet.getObjectAt(0); dataSigner = time.getAdjustedDate(); } catch (Throwable error) { } //Para a verso 2.2, o perodo para assinatura desta PA de 06/03/2012 a 21/06/2023. Calendar calendar = GregorianCalendar.getInstance(); calendar.set(2012, Calendar.APRIL, 27, 0, 0, 0); Date firstDate = calendar.getTime(); calendar.set(2029, Calendar.MARCH, 02, 23, 59, 59); Date lastDate = calendar.getTime(); if (dataSigner != null) { if (dataSigner.before(firstDate)) { throw new SignerException("Invalid signing time. Not valid before 03/06/2012"); } if (dataSigner.after(lastDate)) { throw new SignerException("Invalid signing time. Not valid after 06/21/2023"); } } else { throw new SignerException("There is SigningTime attribute on Package PKCS7, but it is null"); } // O atributo signingCertificate deve conter referncia apenas ao // certificado do signatrio. org.bouncycastle.asn1.cms.Attribute signedSigningCertificate = signedAttributesTable .get(new DERObjectIdentifier("1.2.840.113549.1.9.16.2.47")); if (signedSigningCertificate != null) { // Uso futuro, para processamento dos valores ASN1Set set = signedSigningCertificate.getAttrValues(); } else { throw new SignerException("O Atributo signingCertificate no pode ser nulo."); } }
From source file:ch.cyberduck.core.aquaticprime.Receipt.java
License:Open Source License
/** * Verifies the App Store Receipt/* w ww . ja va 2 s . com*/ * * @return False if receipt validation failed. */ @Override public boolean verify() { try { Security.addProvider(new BouncyCastleProvider()); PKCS7SignedData signature = new PKCS7SignedData( IOUtils.toByteArray(new FileInputStream(this.getFile().getAbsolute()))); signature.verify(); // For additional security, you may verify the fingerprint of the root CA and the OIDs of the // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate // is (1 2 840 113635 100 6 11 1). // Extract the receipt attributes CMSSignedData s = new CMSSignedData(new FileInputStream(this.getFile().getAbsolute())); CMSProcessable signedContent = s.getSignedContent(); byte[] originalContent = (byte[]) signedContent.getContent(); ASN1Object asn = ASN1Object.fromByteArray(originalContent); byte[] opaque = null; String bundleIdentifier = null; String bundleVersion = null; byte[] hash = null; if (asn instanceof DERSet) { // 2 Bundle identifier Interpret as an ASN.1 UTF8STRING. // 3 Application version Interpret as an ASN.1 UTF8STRING. // 4 Opaque value Interpret as a series of bytes. // 5 SHA-1 hash Interpret as a 20-byte SHA-1 digest value. DERSet set = (DERSet) asn; Enumeration enumeration = set.getObjects(); while (enumeration.hasMoreElements()) { Object next = enumeration.nextElement(); if (next instanceof DERSequence) { DERSequence sequence = (DERSequence) next; DEREncodable type = sequence.getObjectAt(0); if (type instanceof DERInteger) { if (((DERInteger) type).getValue().intValue() == 2) { DEREncodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleIdentifier = new String(((DEROctetString) value).getOctets(), "utf-8"); } } else if (((DERInteger) type).getValue().intValue() == 3) { DEREncodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleVersion = new String(((DEROctetString) value).getOctets(), "utf-8"); } } else if (((DERInteger) type).getValue().intValue() == 4) { DEREncodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { opaque = ((DEROctetString) value).getOctets(); } } else if (((DERInteger) type).getValue().intValue() == 5) { DEREncodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { hash = ((DEROctetString) value).getOctets(); } } } } } } else { log.error(String.format("Expected set of attributes for %s", asn)); return false; } if (!StringUtils.equals("ch.sudo.cyberduck", StringUtils.trim(bundleIdentifier))) { log.error("Bundle identifier in ASN set does not match"); return false; } if (!StringUtils.equals(Preferences.instance().getDefault("CFBundleShortVersionString"), StringUtils.trim(bundleVersion))) { log.warn("Bundle version in ASN set does not match"); } NetworkInterface en0 = NetworkInterface.getByName("en0"); if (null == en0) { // Interface is not found when link is down #fail log.warn("No network interface en0"); } else { byte[] mac = en0.getHardwareAddress(); if (null == mac) { log.error("Cannot determine MAC address"); // Continue without validation return true; } final String hex = Hex.encodeHexString(mac); if (log.isDebugEnabled()) { log.debug("Interface en0:" + hex); } // Compute the hash of the GUID MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(mac); digest.update(opaque); digest.update(bundleIdentifier.getBytes(Charset.forName("utf-8"))); byte[] result = digest.digest(); if (Arrays.equals(result, hash)) { if (log.isInfoEnabled()) { log.info(String.format("Valid receipt for GUID %s", hex)); } this.name = hex; } else { log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt", hex)); return false; } } } catch (Exception e) { log.error("Unknown receipt validation error", e); // Shutdown if receipt is not valid return false; } // Always return true to dismiss donation prompt. return true; }
From source file:ch.cyberduck.core.aquaticprime.ReceiptVerifier.java
License:Open Source License
@Override public boolean verify() { try {//from w ww.jav a 2 s. c om // For additional security, you may verify the fingerprint of the root CA and the OIDs of the // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate // is (1 2 840 113635 100 6 11 1). final CMSSignedData s = new CMSSignedData(new FileInputStream(file.getAbsolute())); Store certs = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); for (SignerInformation signer : (Iterable<SignerInformation>) signers.getSigners()) { final Collection<X509CertificateHolder> matches = certs.getMatches(signer.getSID()); for (X509CertificateHolder holder : matches) { if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder() .setProvider(new BouncyCastleProvider()).build(holder))) { return false; } } } // Extract the receipt attributes final CMSProcessable signedContent = s.getSignedContent(); byte[] originalContent = (byte[]) signedContent.getContent(); final ASN1Primitive asn = ASN1Primitive.fromByteArray(originalContent); byte[] opaque = null; String bundleIdentifier = null; String bundleVersion = null; byte[] hash = null; if (asn instanceof ASN1Set) { // 2 Bundle identifier Interpret as an ASN.1 UTF8STRING. // 3 Application version Interpret as an ASN.1 UTF8STRING. // 4 Opaque value Interpret as a series of bytes. // 5 SHA-1 hash Interpret as a 20-byte SHA-1 digest value. final ASN1Set set = (ASN1Set) asn; final Enumeration enumeration = set.getObjects(); while (enumeration.hasMoreElements()) { Object next = enumeration.nextElement(); if (next instanceof DLSequence) { DLSequence sequence = (DLSequence) next; ASN1Encodable type = sequence.getObjectAt(0); if (type instanceof ASN1Integer) { if (((ASN1Integer) type).getValue().intValue() == 2) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleIdentifier = new String(((DEROctetString) value).getOctets(), "UTF-8"); } } else if (((ASN1Integer) type).getValue().intValue() == 3) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { bundleVersion = new String(((DEROctetString) value).getOctets(), "UTF-8"); } } else if (((ASN1Integer) type).getValue().intValue() == 4) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { opaque = ((DEROctetString) value).getOctets(); } } else if (((ASN1Integer) type).getValue().intValue() == 5) { final ASN1Encodable value = sequence.getObjectAt(2); if (value instanceof DEROctetString) { hash = ((DEROctetString) value).getOctets(); } } } } } } else { log.error(String.format("Expected set of attributes for %s", asn)); return false; } if (!StringUtils.equals(PreferencesFactory.get().getDefault("application.identifier"), StringUtils.trim(bundleIdentifier))) { log.error(String.format("Bundle identifier %s in ASN set does not match", bundleIdentifier)); return false; } if (!StringUtils.equals(PreferencesFactory.get().getDefault("application.version"), StringUtils.trim(bundleVersion))) { log.warn(String.format("Bundle version %s in ASN set does not match", bundleVersion)); } final NetworkInterface en0 = NetworkInterface.getByName("en0"); if (null == en0) { // Interface is not found when link is down #fail log.warn("No network interface en0"); return true; } else { final byte[] mac = en0.getHardwareAddress(); if (null == mac) { log.error("Cannot determine MAC address"); // Continue without validation return true; } final String hex = Hex.encodeHexString(mac); if (log.isDebugEnabled()) { log.debug(String.format("Interface en0 %s", hex)); } // Compute the hash of the GUID final MessageDigest digest = MessageDigest.getInstance("SHA-1"); digest.update(mac); if (null == opaque) { log.error(String.format("Missing opaque string in ASN.1 set %s", asn)); return false; } digest.update(opaque); if (null == bundleIdentifier) { log.error(String.format("Missing bundle identifier in ASN.1 set %s", asn)); return false; } digest.update(bundleIdentifier.getBytes(Charset.forName("UTF-8"))); final byte[] result = digest.digest(); if (Arrays.equals(result, hash)) { if (log.isInfoEnabled()) { log.info(String.format("Valid receipt for GUID %s", hex)); } guid = hex; return true; } else { log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt", hex)); return false; } } } catch (IOException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (GeneralSecurityException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (SecurityException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (CMSException e) { log.error("Receipt validation error", e); // Shutdown if receipt is not valid return false; } catch (Exception e) { log.error("Unknown receipt validation error", e); return true; } }
From source file:chapter9.KEKEnvelopedDataExample.java
/** * * @param args//from w w w. j ava2 s . com * @throws Exception */ public static void main(String[] args) throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance(CryptoDefs.Algorithm.DESede.getName(), CryptoDefs.Provider.BC.getName()); SecretKey key = keyGen.generateKey(); //1.- Set up the generator CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator(); byte[] kekID = new byte[] { 1, 2, 3, 4, 5 }; edGen.addKEKRecipient(key, kekID); //2.- Create the enveloped-data object CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes()); CMSEnvelopedData enveloped = edGen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC, CryptoDefs.Provider.BC.getName()); //3.- Re-create enveloped = new CMSEnvelopedData(enveloped.getEncoded()); //4.- Look for our recipient identifier RecipientId recId = new KEKRecipientId(kekID); RecipientInformationStore recipients = enveloped.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient != null) { //5.- Decrypt the data byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName()); //6.- Compare recovered data to the original data if (Arrays.equals((byte[]) data.getContent(), recData)) System.out.println("\t data recovery succeeded!!"); else System.out.println("\t data recovery failed!!"); } else System.out.println("\t Could not find a matching recipient!!"); }
From source file:chapter9.KeyTransEnvelopedDataExample.java
/** * * @param args/*from w ww .j a v a2 s . c o m*/ * @throws Exception */ public static void main(String[] args) throws Exception { KeyStore credentials = Utils.createCredentials(); PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD); Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS); X509Certificate cert = (X509Certificate) chain[0]; //1.- Set up the generator CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator(); gen.addKeyTransRecipient(cert); //2.- Create the enveloped-data object CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes()); CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC, CryptoDefs.Provider.BC.getName()); //3.- Re-create enveloped = new CMSEnvelopedData(enveloped.getEncoded()); //4.- Look for our recipient identifier RecipientId recId = new KeyTransRecipientId(new X500Name(cert.getIssuerX500Principal().getName()), cert.getSerialNumber()); recId.setSerialNumber(cert.getSerialNumber()); recId.setIssuer(cert.getIssuerX500Principal().getEncoded()); RecipientInformationStore recipients = enveloped.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); if (recipient != null) { //5.- Decrypt the data byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName()); //6.- Compare recovered data to the original data if (Arrays.equals((byte[]) data.getContent(), recData)) System.out.println("\t data recovery succeeded!!"); else System.out.println("\t data recovery failed!!"); } else System.out.println("\t Could not find a matching recipient!!"); }