List of usage examples for org.bouncycastle.cms CMSSignedData CMSSignedData
public CMSSignedData(ContentInfo sigData) throws CMSException
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"); }/*w w w .ja v a2 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_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 ww .j av a2s . 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:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
/** * Interpreta um dado do tipo otherName. Obs. O JDK 5.0 no tem classes que * lidem com um dado do tipo OtherName. necessrio usar o BouncyCastle. * // w w w .j a v a2 s . c o m * @param encoded * O dado em ASN.1. * @return Um par contendo o OID e o contedo. */ /* * @SuppressWarnings("unchecked") private static Pair<DERObjectIdentifier, * String> getOtherName(byte[] encoded) throws IOException { // O JDK 5.0 * no tem classes que lidem com um dado do tipo OtherName. // necessrio * usar o BouncyCastle. ASN1InputStream inps = new ASN1InputStream(encoded); * DERSequence seq = null; DERObjectIdentifier oid = null; String conteudo = * ""; seq = (DERSequence) inps.readObject(); inps.close(); Enumeration en = * seq.getObjects(); oid = (DERObjectIdentifier) en.nextElement(); DERObject * obj = ((ASN1TaggedObject) ((ASN1TaggedObject) en * .nextElement()).getObject()).getObject(); if (obj instanceof DERString) { * // Certificados antigos SERASA - // incorretos conteudo = ((DERString) * obj).getString(); } else if (obj instanceof DEROctetString) { // * Certificados corretos conteudo = new String(((DEROctetString) * obj).getOctets(), "ISO-8859-1"); } return new Pair<DERObjectIdentifier, * String>(oid, conteudo); } */ @SuppressWarnings("unchecked") protected static Properties recuperaNomesAlternativos(final byte[] assinatura) throws InvalidKeyException, SecurityException, CRLException, CertificateException, NoSuchProviderException, NoSuchAlgorithmException, SignatureException, AplicacaoException, ChainValidationException, IOException, CMSException, CertStoreException { final CMSSignedData signedData = new CMSSignedData(assinatura); // CertStore certs = signedData.getCertificatesAndCRLs("Collection", "BC"); Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Collection<SignerInformation> c = signers.getSigners(); Iterator<SignerInformation> it = c.iterator(); @SuppressWarnings("unused") String sCN = ""; while (it.hasNext()) { SignerInformation signer = it.next(); // Collection certCollection = certs.getCertificates(signer.getSID()); Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID()); @SuppressWarnings("unused") String ss = signer.getDigestAlgOID(); @SuppressWarnings("unused") String sss = signer.getDigestAlgorithmID().getObjectId().getId(); Iterator<X509CertificateHolder> certIt = certCollection.iterator(); X509CertificateHolder certHolder = certIt.next(); X509Certificate cert = AssinaturaDigital.getX509Certificate(certHolder); /* * *** cdigo comentado movido para * Certificado.recuperarPropriedadesNomesAlteranativos(cert)***** * ATENO: Cdigo sempre retorna na primeira iterao do for ?!!*** * (LAGS) Properties props = new Properties(); for (List<?> * subjectAlternativeName : cert .getSubjectAlternativeNames()) { * String email; Pair<DERObjectIdentifier, String> otherName; * * @SuppressWarnings("unused") int pos; * * // O primeiro elemento um Integer com o valor 0 = otherName, 1 * // = // rfc822name etc. // O segundo valor um byte array ou uma * String. Veja o javadoc // de // getSubjectAlternativeNames. * switch (((Number) subjectAlternativeName.get(0)).intValue()) { * case 0: // OtherName - contm CPF, CNPJ etc. // o OID fica em * otherName.first otherName = getOtherName((byte[]) * subjectAlternativeName .get(1)); * props.put(otherName.first.getId(), otherName.second); break; case * 1: // rfc822Name - usado para email email = (String) * subjectAlternativeName.get(1); props.put("email", email); break; * default: break; } } return props; */ return CertificadoUtil.recuperarPropriedadesNomesAlteranativos(cert); } return null; }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("static-access") protected static byte[] converterPkcs7EmCMSComCertificadosECRLs(final byte[] assinatura) throws Exception { CMSSignedData cmssd = new CMSSignedData(assinatura); Store certs = cmssd.getCertificates(); Store certsAndCrls = buscarCrlParaCadaCertificado(certs); CMSSignedData cmssdcrl = cmssd.replaceCertificatesAndCRLs(cmssd, certsAndCrls, certsAndCrls, certsAndCrls); return cmssdcrl.getEncoded(); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static void main(String[] args) throws Exception { byte[] pdf;/*www .j av a2s .c o m*/ { File f = new File("c:/trabalhos/java/teste.pdf"); FileInputStream fin = new FileInputStream(f); pdf = new byte[(int) f.length()]; fin.read(pdf); fin.close(); } PdfReader reader = new PdfReader(pdf); FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf"); final int SIZE = 256000; PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.TYPE, PdfName.SIG); dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); sap.setCryptoDictionary(dic); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(SIZE)); sap.setSignDate(Calendar.getInstance()); sap.preClose(exc); byte[] data = streamToByteArray(sap.getRangeStream()); FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64"); fout2.write(Base64.encode(data).getBytes()); fout2.close(); File f = new File("c:/trabalhos/java/teste_sign.b64"); FileInputStream fin = new FileInputStream(f); byte[] signatureB64 = new byte[(int) f.length()]; fin.read(signatureB64); @SuppressWarnings("unused") StringBuilder sb = new StringBuilder(); byte[] signature1 = Base64.decode(new String(signatureB64)); fin.close(); byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); byte[] signature = A_T.getEncoded(); byte[] outc = new byte[(SIZE - 2) / 2]; System.arraycopy(signature, 0, outc, 0, signature.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic2); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
@SuppressWarnings("unchecked") protected static void addSignatureToPDF(byte[] pdf, byte[] signature) throws Exception { PdfReader reader = new PdfReader(pdf); FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf"); final int SIZE = 128000; PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0'); PdfSignatureAppearance sap = stp.getSignatureAppearance(); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.TYPE, PdfName.SIG);/*w w w. ja v a 2 s . c o m*/ dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS")); dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached")); sap.setCryptoDictionary(dic); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(SIZE)); sap.preClose(exc); byte[] data = streamToByteArray(sap.getRangeStream()); FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64"); fout2.write(Base64.encode(data).getBytes()); fout2.close(); File f = new File("c:/trabalhos/java/teste_sign.b64"); FileInputStream fin = new FileInputStream(f); byte[] signatureB64 = new byte[(int) f.length()]; fin.read(signatureB64); @SuppressWarnings("unused") StringBuilder sb = new StringBuilder(); byte[] signature1 = Base64.decode(new String(signatureB64)); fin.close(); byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); signature = A_T.getEncoded(); byte[] outc = new byte[(SIZE - 2) / 2]; System.arraycopy(signature, 0, outc, 0, signature.length); PdfDictionary dic2 = new PdfDictionary(); dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true)); sap.close(dic2); }
From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java
License:Open Source License
protected static byte[] converterPkcs7EmCMSComCertificadosCRLsECarimboDeTempo(byte[] pkcs7) throws Exception { byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(pkcs7); CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP)); return A_T.getEncoded(); // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura); ////from w w w. java2 s .c o m // addSignatureToPDF(conteudo, A_T.getEncoded()); // // FileOutputStream fout = new FileOutputStream( // "c:/trabalhos/java/sign.pdf"); // fout.write(conteudo); // fout.close(); // // FileOutputStream fout2 = new FileOutputStream( // "c:/trabalhos/java/sign.cms"); // fout2.write(A_T.getEncoded()); // fout2.close(); }
From source file:ch.cyberduck.core.aquaticprime.Receipt.java
License:Open Source License
/** * Verifies the App Store Receipt/*from w w w .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 w w. j a v a2 s.c o m*/ // 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:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java
License:Open Source License
/** * Will attempt to initialize the signer certificate * //from w ww . j ava 2 s . c o m * @param cmsSignatureBase64 * Base 64 encoded CMS/PKCS7 String * @throws CMSException * @throws CertificateException */ public MobileIdCmsVerifier(String cmsSignatureBase64) throws CMSException, CertificateException { this.cmsSignedData = new CMSSignedData(Base64.decodeBase64(cmsSignatureBase64)); // Find the signer certificate SignerInformationStore signerInfoStore = cmsSignedData.getSignerInfos(); signerInfo = (SignerInformation) signerInfoStore.getSigners().iterator().next(); x509CertHolder = (X509CertificateHolder) cmsSignedData.getCertificates().getMatches(signerInfo.getSID()) .iterator().next(); signerCert = new JcaX509CertificateConverter().getCertificate(x509CertHolder); }