List of usage examples for org.bouncycastle.cms CMSSignedData CMSSignedData
public CMSSignedData(ContentInfo sigData) throws CMSException
From source file:net.sf.assinafacil.AssinaFacilApp.java
License:Open Source License
public boolean extractSignedContent(File fileInput, File fileOutput) throws GeneralSecurityException, IOException { CMSSignedData signedData = null;//from w ww. j a v a 2 s . com CMSProcessable content = null; FileOutputStream fos = new FileOutputStream(fileOutput); try { signedData = new CMSSignedData(new FileInputStream(fileInput)); content = signedData.getSignedContent(); content.write(fos); fos.close(); return true; } catch (CMSException e) { throw new GeneralSecurityException("Arquivo no assinado ou formatao invlida."); } }
From source file:net.sf.assinafacil.AssinaFacilApp.java
License:Open Source License
public SignerInformationStore getSignatures(File fileInput) throws java.security.SignatureException, FileNotFoundException { CMSSignedData signedData = null;/*from www .j a va2s .c o m*/ SignerInformationStore signers = null; try { signedData = new CMSSignedData(new FileInputStream(fileInput)); signers = signedData.getSignerInfos(); return signers; } catch (CMSException e) { throw new SignatureException("Arquivo no assinado ou formato invlido"); } }
From source file:org.apache.kerby.pkix.SignedDataEngineTest.java
License:Apache License
/** * Tests that signed data signature validation works. * * @throws Exception//from w w w . j a va 2 s .co m */ @Test public void testSignedData() throws Exception { byte[] data = "Hello".getBytes(); byte[] signedDataBytes = SignedDataEngine.getSignedData(privateKey, certificate, data, ID_DATA); CMSSignedData signedData = new CMSSignedData(signedDataBytes); assertTrue(SignedDataEngine.validateSignedData(signedData)); }
From source file:org.cesecore.certificates.ca.X509CATest.java
License:Open Source License
@SuppressWarnings("unchecked") private void doTestX509CABasicOperations(String algName) throws Exception { final CryptoToken cryptoToken = getNewCryptoToken(); final X509CA x509ca = createTestCA(cryptoToken, CADN); Certificate cacert = x509ca.getCACertificate(); // Start by creating a PKCS7 byte[] p7 = x509ca.createPKCS7(cryptoToken, cacert, true); assertNotNull(p7);/*from www . j av a2 s . c o m*/ CMSSignedData s = new CMSSignedData(p7); Store certstore = s.getCertificates(); Collection<X509CertificateHolder> certs = certstore.getMatches(null); assertEquals(2, certs.size()); p7 = x509ca.createPKCS7(cryptoToken, cacert, false); assertNotNull(p7); s = new CMSSignedData(p7); certstore = s.getCertificates(); certs = certstore.getMatches(null); assertEquals(1, certs.size()); // Create a certificate request (will be pkcs10) byte[] req = x509ca.createRequest(cryptoToken, null, algName, cacert, CATokenConstants.CAKEYPURPOSE_CERTSIGN); PKCS10CertificationRequest p10 = new PKCS10CertificationRequest(req); assertNotNull(p10); String dn = p10.getSubject().toString(); assertEquals(CADN, dn); // Make a request with some pkcs11 attributes as well Collection<ASN1Encodable> attributes = new ArrayList<ASN1Encodable>(); // Add a subject alternative name ASN1EncodableVector altnameattr = new ASN1EncodableVector(); altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foobar.bar.com"); ExtensionsGenerator extgen = new ExtensionsGenerator(); extgen.addExtension(Extension.subjectAlternativeName, false, san); Extensions exts = extgen.generate(); altnameattr.add(new DERSet(exts)); // Add a challenge password as well ASN1EncodableVector pwdattr = new ASN1EncodableVector(); pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); ASN1EncodableVector pwdvalues = new ASN1EncodableVector(); pwdvalues.add(new DERUTF8String("foobar123")); pwdattr.add(new DERSet(pwdvalues)); attributes.add(new DERSequence(altnameattr)); attributes.add(new DERSequence(pwdattr)); // create the p10 req = x509ca.createRequest(cryptoToken, attributes, algName, cacert, CATokenConstants.CAKEYPURPOSE_CERTSIGN); p10 = new PKCS10CertificationRequest(req); assertNotNull(p10); dn = p10.getSubject().toString(); assertEquals(CADN, dn); Attribute[] attrs = p10.getAttributes(); assertEquals(2, attrs.length); PKCS10RequestMessage p10msg = new PKCS10RequestMessage(new JcaPKCS10CertificationRequest(p10)); assertEquals("foobar123", p10msg.getPassword()); assertEquals("dNSName=foobar.bar.com", p10msg.getRequestAltNames()); try { x509ca.createAuthCertSignRequest(cryptoToken, p10.getEncoded()); } catch (UnsupportedOperationException e) { // Expected for a X509 CA } // Generate a client certificate and check that it was generated correctly EndEntityInformation user = new EndEntityInformation("username", "CN=User", 666, "rfc822Name=user@user.com", "user@user.com", new EndEntityType(EndEntityTypes.ENDUSER), 0, 0, EndEntityConstants.TOKEN_USERGEN, 0, null); KeyPair keypair = genTestKeyPair(algName); CertificateProfile cp = new CertificateProfile(CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); cp.addCertificatePolicy(new CertificatePolicy("1.1.1.2", null, null)); cp.setUseCertificatePolicies(true); Certificate usercert = x509ca.generateCertificate(cryptoToken, user, keypair.getPublic(), 0, null, 10L, cp, "00000"); assertNotNull(usercert); assertEquals("CN=User", CertTools.getSubjectDN(usercert)); assertEquals(CADN, CertTools.getIssuerDN(usercert)); assertEquals(getTestKeyPairAlgName(algName).toUpperCase(), AlgorithmTools.getCertSignatureAlgorithmNameAsString(usercert).toUpperCase()); assertEquals(new String(CertTools.getSubjectKeyId(cacert)), new String(CertTools.getAuthorityKeyId(usercert))); assertEquals("user@user.com", CertTools.getEMailAddress(usercert)); assertEquals("rfc822name=user@user.com", CertTools.getSubjectAlternativeName(usercert)); assertNull(CertTools.getUPNAltName(usercert)); assertFalse(CertTools.isSelfSigned(usercert)); usercert.verify(cryptoToken .getPublicKey(x509ca.getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN))); usercert.verify(x509ca.getCACertificate().getPublicKey()); assertTrue(CertTools.isCA(x509ca.getCACertificate())); assertFalse(CertTools.isCA(usercert)); assertEquals("1.1.1.2", CertTools.getCertificatePolicyId(usercert, 0)); X509Certificate cert = (X509Certificate) usercert; boolean[] ku = cert.getKeyUsage(); assertTrue(ku[0]); assertTrue(ku[1]); assertTrue(ku[2]); assertFalse(ku[3]); assertFalse(ku[4]); assertFalse(ku[5]); assertFalse(ku[6]); assertFalse(ku[7]); int bcku = CertTools.sunKeyUsageToBC(ku); assertEquals(X509KeyUsage.digitalSignature | X509KeyUsage.nonRepudiation | X509KeyUsage.keyEncipherment, bcku); // Create a CRL Collection<RevokedCertInfo> revcerts = new ArrayList<RevokedCertInfo>(); X509CRLHolder crl = x509ca.generateCRL(cryptoToken, revcerts, 1); assertNotNull(crl); X509CRL xcrl = CertTools.getCRLfromByteArray(crl.getEncoded()); assertEquals(CADN, CertTools.getIssuerDN(xcrl)); Set<?> set = xcrl.getRevokedCertificates(); assertNull(set); BigInteger num = CrlExtensions.getCrlNumber(xcrl); assertEquals(1, num.intValue()); BigInteger deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl); assertEquals(-1, deltanum.intValue()); // Revoke some cert Date revDate = new Date(); revcerts.add(new RevokedCertInfo(CertTools.getFingerprintAsString(usercert).getBytes(), CertTools.getSerialNumber(usercert).toByteArray(), revDate.getTime(), RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, CertTools.getNotAfter(usercert).getTime())); crl = x509ca.generateCRL(cryptoToken, revcerts, 2); assertNotNull(crl); xcrl = CertTools.getCRLfromByteArray(crl.getEncoded()); set = xcrl.getRevokedCertificates(); assertEquals(1, set.size()); num = CrlExtensions.getCrlNumber(xcrl); assertEquals(2, num.intValue()); X509CRLEntry entry = (X509CRLEntry) set.iterator().next(); assertEquals(CertTools.getSerialNumber(usercert).toString(), entry.getSerialNumber().toString()); assertEquals(revDate.toString(), entry.getRevocationDate().toString()); // Getting the revocation reason is a pita... byte[] extval = entry.getExtensionValue(Extension.reasonCode.getId()); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(extval)); ASN1OctetString octs = (ASN1OctetString) aIn.readObject(); aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets())); ASN1Primitive obj = aIn.readObject(); CRLReason reason = CRLReason.getInstance((ASN1Enumerated) obj); assertEquals("CRLReason: certificateHold", reason.toString()); //DEROctetString ostr = (DEROctetString)obj; // Create a delta CRL revcerts = new ArrayList<RevokedCertInfo>(); crl = x509ca.generateDeltaCRL(cryptoToken, revcerts, 3, 2); assertNotNull(crl); xcrl = CertTools.getCRLfromByteArray(crl.getEncoded()); assertEquals(CADN, CertTools.getIssuerDN(xcrl)); set = xcrl.getRevokedCertificates(); assertNull(set); num = CrlExtensions.getCrlNumber(xcrl); assertEquals(3, num.intValue()); deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl); assertEquals(2, deltanum.intValue()); revcerts.add(new RevokedCertInfo(CertTools.getFingerprintAsString(usercert).getBytes(), CertTools.getSerialNumber(usercert).toByteArray(), revDate.getTime(), RevokedCertInfo.REVOCATION_REASON_CERTIFICATEHOLD, CertTools.getNotAfter(usercert).getTime())); crl = x509ca.generateDeltaCRL(cryptoToken, revcerts, 4, 3); assertNotNull(crl); xcrl = CertTools.getCRLfromByteArray(crl.getEncoded()); deltanum = CrlExtensions.getDeltaCRLIndicator(xcrl); assertEquals(3, deltanum.intValue()); set = xcrl.getRevokedCertificates(); assertEquals(1, set.size()); entry = (X509CRLEntry) set.iterator().next(); assertEquals(CertTools.getSerialNumber(usercert).toString(), entry.getSerialNumber().toString()); assertEquals(revDate.toString(), entry.getRevocationDate().toString()); // Getting the revocation reason is a pita... extval = entry.getExtensionValue(Extension.reasonCode.getId()); aIn = new ASN1InputStream(new ByteArrayInputStream(extval)); octs = (ASN1OctetString) aIn.readObject(); aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets())); obj = aIn.readObject(); reason = CRLReason.getInstance((ASN1Enumerated) obj); assertEquals("CRLReason: certificateHold", reason.toString()); }
From source file:org.cryptoworkshop.ximix.node.crypto.service.NodeShuffledBoardDecryptionService.java
License:Apache License
private Map<String, byte[]> createSeedCommitmentMap(SignedDataVerifier verifier, File[] fileList) { final Map<String, byte[]> transcripts = new TreeMap<>(); for (File file : fileList) { String name = file.getName(); int beginIndex = name.indexOf('.') + 1; String nodeName = name.substring(beginIndex, name.indexOf('.', beginIndex)); try {/*w w w . j a v a2 s .co m*/ BufferedInputStream sigData = new BufferedInputStream(new FileInputStream(file)); CMSSignedData cmsSignedData = new CMSSignedData(sigData); if (verifier.signatureVerified(cmsSignedData)) { transcripts.put(nodeName, cmsSignedData.getEncoded()); } else { nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR, "Signature check failed: " + file.getPath()); } sigData.close(); } catch (Exception e) { nodeContext.getEventNotifier().notify(EventNotifier.Level.ERROR, "Signature check failed on " + file.getPath() + ": " + e.getMessage(), e); } } return transcripts; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESChecker.java
License:Open Source License
/** * validade a timestampo on signature/*from w w w . ja va2 s.c o m*/ * @param attributeTimeStamp * @param varSignature * @return */ private Timestamp validateTimestamp(Attribute attributeTimeStamp, byte[] varSignature) { try { TimeStampOperator timeStampOperator = new TimeStampOperator(); byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded(); TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp)); Timestamp timeStampSigner = new Timestamp(timeStampToken); timeStampOperator.validate(varSignature, varTimeStamp, null); return timeStampSigner; } catch (CertificateCoreException | IOException | TSPException | CMSException e) { throw new SignerException(e); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESChecker.java
License:Open Source License
/** * Extracts the signed content from the digital signature structure, if it * is a signature with attached content. * * @param signed/*from ww w .j a va 2 s . c o m*/ * Signature and signed content. * @param validateOnExtract * TRUE (to execute validation) or FALSE (not execute validation) * * @return content for attached signature */ @Override public byte[] getAttached(byte[] signed, boolean validateOnExtract) { byte[] result = null; if (validateOnExtract) { this.check(null, signed); } CMSSignedData signedData = null; try { signedData = new CMSSignedData(signed); } catch (CMSException exception) { throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), exception); } try { CMSProcessable contentProcessable = signedData.getSignedContent(); if (contentProcessable != null) { result = (byte[]) contentProcessable.getContent(); } else { logger.info(cadesMessagesBundle.getString("error.get.content.empty")); } } catch (Exception exception) { throw new SignerException(cadesMessagesBundle.getString("error.get.content.pkcs7"), exception); } return result; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
/** * Extracts the signed content from the digital signature structure, if it * is a signature with attached content. * * @param signed//from ww w. j a v a2s . c o m * Signature and signed content. * @param validateOnExtract * TRUE (to execute validation) or FALSE (not execute validation) * * @return content for attached signature * @deprecated moved to CadESChecker */ @Override public byte[] getAttached(byte[] signed, boolean validateOnExtract) { byte[] result = null; if (validateOnExtract) { this.check(null, signed); } CMSSignedData signedData = null; try { signedData = new CMSSignedData(signed); } catch (CMSException exception) { throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), exception); } try { CMSProcessable contentProcessable = signedData.getSignedContent(); if (contentProcessable != null) { result = (byte[]) contentProcessable.getContent(); } } catch (Exception exception) { throw new SignerException(cadesMessagesBundle.getString("error.get.content.pkcs7"), exception); } return result; }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java
License:Open Source License
@Override public byte[] doCounterSign(byte[] previewCMSSignature) { try {/*from w ww.ja v a2 s. c om*/ Security.addProvider(new BouncyCastleProvider()); // Reading a P7S file that is preview signature. CMSSignedData cmsPreviewSignedData = new CMSSignedData(previewCMSSignature); // Build BouncyCastle object that is a set of signatures Collection<SignerInformation> previewSigners = cmsPreviewSignedData.getSignerInfos().getSigners(); for (SignerInformation previewSigner : previewSigners) { // build a counter-signature per previewSignature byte[] previewSignatureFromSigner = previewSigner.getSignature(); CMSSignedData cmsCounterSignedData = new CMSSignedData(this.doSign(previewSignatureFromSigner)); cmsPreviewSignedData = this.updateWithCounterSignature(cmsCounterSignedData, cmsPreviewSignedData, previewSigner.getSID()); } return cmsPreviewSignedData.getEncoded(); } catch (Throwable error) { throw new SignerException(error); } }
From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESTimeStampSigner.java
License:Open Source License
@Override public byte[] doTimeStampForSignature(byte[] signature) throws SignerException { try {//from w ww . j a va2 s. com Security.addProvider(new BouncyCastleProvider()); CMSSignedData cmsSignedData = new CMSSignedData(signature); SignerInformationStore signers = cmsSignedData.getSignerInfos(); Iterator<?> it = signers.getSigners().iterator(); SignerInformation signer = (SignerInformation) it.next(); AttributeFactory attributeFactory = AttributeFactory.getInstance(); ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector(); SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory .factory(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()); signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.getCertificateChain(), signer.getSignature(), signaturePolicy, null); unsignedAttributes.add(signedOrUnsignedAttribute.getValue()); AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes); List<SignerInformation> vNewSigners = new ArrayList<SignerInformation>(); vNewSigners.add(SignerInformation.replaceUnsignedAttributes(signer, unsignedAttributesTable)); SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners); CMSSignedData oSignedData = cmsSignedData; cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore); byte[] result = cmsSignedData.getEncoded(); return result; } catch (CMSException ex) { throw new SignerException(ex.getMessage()); } catch (IOException ex) { throw new SignerException(ex.getMessage()); } }