// adds unsigned certs & revocation infos (CRL or OCSP) to existing certs & revocation info list // ('certificates' and 'crls' CMS fields) public void appendValidationValues(Collection certificateValues, Collection revocationValues) { try { Store certStore = cmsSignedData.getCertificates(); Store crlStore = cmsSignedData.getCRLs(); if (certificateValues != null && !certificateValues.isEmpty()) { Collection<Certificate> existingCerts = getSignatureCertificateInfo(); Set<Certificate> newCerts = new HashSet<Certificate>(existingCerts); // 'Set' to avoid duplicates newCerts.addAll(certificateValues); certStore = new JcaCertStore(newCerts); } if (revocationValues != null && !revocationValues.isEmpty()) { Collection<CRL> existingCrls = getUnsignedCRLs(); Set<CRL> newCrls = new HashSet<CRL>(existingCrls); // 'Set' to avoid duplicates // FIXME : also add OCSP info (use OtherRevocationInfoFormat of RevocationInfoChoices, see // RFC 3852) for (Object o : revocationValues) { if (o instanceof CRL) newCrls.add((CRL) o); } crlStore = new JcaCRLStore(newCrls); } cmsSignedData = CMSSignedData.replaceCertificatesAndCRLs( cmsSignedData, certStore, cmsSignedData.getAttributeCertificates(), crlStore); } catch (Exception e) { ExceptionHandlerTyped.<SPISignatureException>handle(SPISignatureException.class, e); } }
private void verifyRSASignatures(CMSSignedData s, byte[] contentDigest) throws Exception { Store certStore = s.getCertificates(); SignerInformationStore signers = s.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certStore.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder cert = (X509CertificateHolder) certIt.next(); if (!signer.verify( new BcRSASignerInfoVerifierBuilder( new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()) .build(cert))) { fail("signature verification failed"); } if (contentDigest != null) { if (!Arrays.areEqual(contentDigest, signer.getContentDigest())) { fail("digest verification failed"); } } } }
@Test public void testCMD() throws Exception { Authentication auth = new SkeletonKeyClientBuilder() .username("wburke") .password("geheim") .authentication("Skeleton Key"); ResteasyClient client = new ResteasyClient(); WebTarget target = client.target(generateBaseUrl()); String tiny = target.path("tokens").path("url").request().post(Entity.json(auth), String.class); System.out.println(tiny); System.out.println("tiny.size: " + tiny.length()); Security.addProvider(new BouncyCastleProvider()); KeyPair keyPair = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); X509Certificate cert = KeyTools.generateTestCertificate(keyPair); byte[] signed = p7s(privateKey, cert, null, tiny.getBytes()); CMSSignedData data = new CMSSignedData(signed); byte[] bytes = (byte[]) data.getSignedContent().getContent(); System.out.println("BYTES: " + new String(bytes)); System.out.println("size:" + signed.length); System.out.println("Base64.size: " + Base64.encodeBytes(signed).length()); SignerInformation signer = (SignerInformation) data.getSignerInfos().getSigners().iterator().next(); System.out.println("valid: " + signer.verify(cert, "BC")); }
private SignatureData getFromCmsSignature( SignatureVerificationRequest signatureVerificationRequest, SignatureVerificationResponse response) throws CMSException { String signature = signatureVerificationRequest.getSignature(); byte[] decoded = Base64.decode(signature); CMSSignedData cmsSignedData = new CMSSignedData(decoded); String encodedSignedData = new String((byte[]) cmsSignedData.getSignedContent().getContent()); // Fetch information about the issuers List<String> certInfos = new ArrayList<String>(); Collection certificates = cmsSignedData.getCertificates().getMatches(null); for (Object certificate : certificates) { X509CertificateHolder holder = (X509CertificateHolder) certificate; certInfos.add(holder.getSubject().toString()); CertificateInfo ci = new CertificateInfo(); ci.setSubjectDn(holder.getSubject().toString()); ci.setValidTo(simpleDateFormat.format(holder.getNotAfter())); response.getCertificateInfos().getCertificateInfo().add(ci); } // Fetch timestamp Date signingDate = findTimestamp(cmsSignedData); String dateString = simpleDateFormat.format(signingDate); response.setSignatureDate(dateString); // Create the SignatureData to be verified SignatureData signData = new SignatureData(); signData.setEncodedTbs(encodedSignedData); signData.setSignature(signature); ELegType clientType = new ELegType("test", "test", PkiClient.NETMAKER_NETID_4); signData.setClientType(clientType); return signData; }
/** * Verify the email is signed by the given certificate. * * @param signedData * @param mailMsg * @return * @throws CMSException * @throws OperatorCreationException * @throws CertificateException */ @SuppressWarnings({"rawtypes"}) protected boolean isValid(CMSSignedData signedData, MailMessage mailMsg) throws OperatorCreationException, CMSException, CertificateException { boolean verify = false; SignerInformationStore signerStore = signedData.getSignerInfos(); Iterator<SignerInformation> it = signerStore.getSigners().iterator(); while (it.hasNext()) { SignerInformation signer = it.next(); org.bouncycastle.util.Store store = signedData.getCertificates(); @SuppressWarnings("unchecked") Collection certCollection = store.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next(); X509Certificate certificate = new JcaX509CertificateConverter().setProvider(PROVIDER_NAME).getCertificate(certHolder); verify = signer.verify( new JcaSimpleSignerInfoVerifierBuilder() .setProvider(PROVIDER_NAME) .build(certificate)); mailMsg.setHasSignature(true); mailMsg.setSignaturePassed(verify); mailMsg.setNameOfPrincipal(certificate.getSubjectDN().getName()); } return verify; }
/** * Validates that a signed entity has a valid message and signature. The signer's certificate is * validated to ensure authenticity of the message. Message tampering is also checked with the * message's digest and the signed digest in the message signature. * * @param signedEntity The entity containing the original signed part and the message signature. * @param signerCertificate The certificate used to sign the message. * @param anchors A collection of certificate anchors used to determine if the certificates used * in the signature can be validated as trusted certificates. */ public void checkSignature( SignedEntity signedEntity, X509Certificate signerCertificate, Collection<X509Certificate> anchors) throws SignatureValidationException { CMSSignedData signatureEnvelope = deserializeSignatureEnvelope(signedEntity); try { // there may be multiple signatures in the signed part... iterate through all the signing // certificates until one // is verified with the signerCertificate for (SignerInformation sigInfo : (Collection<SignerInformation>) signatureEnvelope.getSignerInfos().getSigners()) if (sigInfo.verify(signerCertificate, CryptoExtensions.getJCEProviderName())) return; // verified... return // at this point the signerCertificate cannot be verified with one of the signing // certificates.... throw new SignatureValidationException("Signature validation failure."); } catch (SignatureValidationException sve) { throw sve; } catch (Exception e) { throw new SignatureValidationException("Signature validation failure.", e); } }
private int verify(String signatureb64) { int verified = 0; try { CMSSignedData signature = new CMSSignedData(Base64.decode(signatureb64)); // batch verification Store certs = signature.getCertificates(); SignerInformationStore signers = signature.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next(); System.out.println(verified); if (signer.verify( new JcaSimpleSignerInfoVerifierBuilder() .setProvider(new BouncyCastleProvider()) .build(certHolder))) { verified++; } } System.out.println(verified); } catch (CMSException | StoreException | CertificateException | OperatorCreationException ex) { System.err.println("error : " + ex.getMessage()); } return verified; }
private void testDetachedRSA() throws Exception { Digest md = new SHA1Digest(); List certList = new ArrayList(); CMSTypedData msg = new CMSProcessableByteArray("Hello world!".getBytes()); certList.add(_origCert); certList.add(_signCert); Store certs = new CollectionStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); byte[] digValue = new byte[md.getDigestSize()]; byte[] data = "Hello world!".getBytes(); md.update(data, 0, data.length); md.doFinal(digValue, 0); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digValue))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); AsymmetricKeyParameter privKey = (AsymmetricKeyParameter) _origKP.getPrivate(); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); BcContentSignerBuilder contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId); gen.addSignerInfoGenerator( new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()) .setSignedAttributeGenerator( new DefaultSignedAttributeTableGenerator(new AttributeTable(v))) .build(contentSignerBuilder.build(privKey), _origCert)); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); // // the signature is detached, so need to add msg before passing on // s = new CMSSignedData(msg, s.getEncoded()); // // compute expected content digest // verifyRSASignatures(s, digValue); }
private static byte[] p7s( PrivateKey priv, X509Certificate storecert, CertStore certs, byte[] contentbytes) throws CertStoreException, CMSException, NoSuchAlgorithmException, NoSuchProviderException, IOException { CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); signGen.addSigner(priv, (X509Certificate) storecert, CMSSignedDataGenerator.DIGEST_SHA512); // signGen.addCertificatesAndCRLs(certs); CMSProcessable content = new CMSProcessableByteArray(contentbytes); CMSSignedData signedData = signGen.generate(content, true, "BC"); return signedData.getEncoded(); }
private static ProvisioningProfile create(File file) { InputStream in = null; try { in = new BufferedInputStream(new FileInputStream(file)); CMSSignedData data = new CMSSignedData(in); byte[] content = (byte[]) data.getSignedContent().getContent(); NSDictionary dict = (NSDictionary) PropertyListParser.parse(content); return new ProvisioningProfile(file, dict); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(in); } }
/** * If the {@code DSSDocument} is a CMS message and the signed content's content is not null then * the {@code CMSSignedData} is returned. All exceptions are hidden * * @param dssDocument * @return {@code CMSSignedData} or {@code null} */ public static CMSSignedData getOriginalSignedData(final DSSDocument dssDocument) { CMSSignedData originalSignedData = null; try { // check if input toSignDocument is already signed originalSignedData = new CMSSignedData(dssDocument.getBytes()); if (originalSignedData.getSignedContent().getContent() == null) { originalSignedData = null; } } catch (Exception e) { // not a parallel signature } return originalSignedData; }
// For external signatures, inputStream parameter is the data being signed (external eContent) public boolean verifyExternalWithContent(InputStream inputStream) throws CMSException, IOException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, OperatorCreationException, CertificateException { CMSSignedDataParser sp = new CMSSignedDataParser(new CMSTypedStream(inputStream), cmsSignedData.getEncoded()); sp.getSignedContent() .drain(); // here digests are computed and passed to newly created SignerInformation objects Collection signers = sp.getSignerInfos().getSigners(); if (signers.size() != 1) hasMultipleSignerInfos = true; Iterator iterator = signers.iterator(); firstSignerInfo = (SignerInformation) iterator.next(); return CMSVerifier.verify(firstSignerInfo, cmsSignedData.getCertificates()); }
private void parseCms() { Collection signers = cmsSignedData.getSignerInfos().getSigners(); if (signers.size() != 1) hasMultipleSignerInfos = true; Iterator iterator = signers.iterator(); firstSignerInfo = (SignerInformation) iterator.next(); }
/** * Returns the ASN.1 encoded representation of {@code CMSSignedData}. * * @param data * @return * @throws DSSException */ public static byte[] getEncoded(final CMSSignedData data) throws DSSException { try { return data.getEncoded(); } catch (IOException e) { throw new DSSException(e); } }
public byte[] getEncoded() { try { return cmsSignedData.getEncoded(); } catch (IOException e) { ExceptionHandlerTyped.<SPISignatureException>handle(SPISignatureException.class, e); } return null; }
/** * Tests that it is possible to specify a signature algorithm who's name is not simply a * concatenation of a digest algorithm and the key algorithm. * * <p>This test also sets the signature provider as a provider supporting the RSASSA-PSS * algorithms might not be installed. * * @throws Exception */ public void testWithSignatureAlgorithmSHA256withRSAandMGF1() throws Exception { File sourceFile = new File("target/test-classes/wineyes.exe"); File targetFile = new File("target/test-classes/wineyes-signed.exe"); FileUtils.copyFile(sourceFile, targetFile); PEFile peFile = null; try { peFile = new PEFile(targetFile); PESigner signer = new PESigner(getKeyStore(), ALIAS, PRIVATE_KEY_PASSWORD) .withTimestamping(false) .withDigestAlgorithm(DigestAlgorithm.SHA1) .withSignatureAlgorithm("SHA256withRSAandMGF1", new BouncyCastleProvider()); signer.sign(peFile); peFile = new PEFile(targetFile); List<CMSSignedData> signatures = peFile.getSignatures(); assertNotNull(signatures); assertEquals(1, signatures.size()); CMSSignedData signedData = signatures.get(0); assertNotNull(signedData); // Check the signature algorithm final SignerInformation si = (SignerInformation) signedData.getSignerInfos().getSigners().iterator().next(); assertEquals( "Digest algorithm", NISTObjectIdentifiers.id_sha256, si.getDigestAlgorithmID().getAlgorithm()); assertEquals( "Encryption algorithm", PKCSObjectIdentifiers.id_RSASSA_PSS.getId(), si.getEncryptionAlgOID()); } finally { if (peFile != null) { peFile.close(); } } }
public static boolean isValidSignature(CMSSignedData signedData, X509Certificate rootCert) throws Exception { boolean[] bArr = new boolean[2]; bArr[0] = true; CertStore certsAndCRLs = signedData.getCertificatesAndCRLs("Collection", "BC"); SignerInformationStore signers = signedData.getSignerInfos(); Iterator it = signers.getSigners().iterator(); if (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); SignerId signerConstraints = signer.getSID(); signerConstraints.setKeyUsage(bArr); PKIXCertPathBuilderResult result = buildPath(rootCert, signer.getSID(), certsAndCRLs); return signer.verify(result.getPublicKey(), "BC"); } return false; }
public boolean verifyEstrai(String pathBase, File pathFilesSignedd) { boolean esito = false; byte[] buffer = new byte[(int) pathFilesSignedd.length()]; DataInputStream in; try { in = new DataInputStream(new FileInputStream(pathFilesSignedd)); in.readFully(buffer); in.close(); Security.addProvider(new BouncyCastleProvider()); CMSSignedData signature = new CMSSignedData(buffer); SignerInformation signer = (SignerInformation) signature.getSignerInfos().getSigners().iterator().next(); CertStore cs = signature.getCertificatesAndCRLs("Collection", "BC"); Iterator iter = cs.getCertificates(signer.getSID()).iterator(); X509Certificate certificate = (X509Certificate) iter.next(); CMSProcessable sc = signature.getSignedContent(); byte[] data = (byte[]) sc.getContent(); // Verifie la signature // System.out.println(signer.verify(certificate, "BC")); esito = signer.verify(certificate.getPublicKey(), "BC"); System.out.println("Verifica FILE: " + esito); String fatturapaName = pathFilesSignedd.getName().substring(0, pathFilesSignedd.getName().length() - 4).trim(); System.out.println(" test:" + fatturapaName); FileOutputStream envfos = new FileOutputStream(new File(pathBase, fatturapaName)); envfos.write(data); envfos.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return esito; }
// ROB duplicato del metodo in VerifyTask ... private InputStream getCmsInputStream(String path) { FileInputStream is = null; try { is = new FileInputStream(path); } catch (FileNotFoundException ex) { System.out.println("Errore nell'acquisizione del file: " + ex); } ByteArrayInputStream bais = null; try { CMSSignedData cms = new CMSSignedData(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); cms.getSignedContent().write(baos); bais = new ByteArrayInputStream(baos.toByteArray()); } catch (CMSException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bais; }
public Certificate getSignerCertificate() { try { Collection certificateCollection = cmsSignedData.getCertificates().getMatches(firstSignerInfo.getSID()); Iterator iterator = certificateCollection.iterator(); X509CertificateHolder certHolder = (X509CertificateHolder) iterator.next(); return CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME) .generateCertificate(new ByteArrayInputStream(certHolder.getEncoded())); } catch (Exception e) { log.error(Channel.TECH, "Could not extract signer certificate from CMS signature : %1$s", e); } return null; }
public void appendSignatureTimeStamp(byte[] timeStampTokenBytes) { try { AttributeTable at = firstSignerInfo.getUnsignedAttributes(); firstSignerInfo = SignerInformation.replaceUnsignedAttributes( firstSignerInfo, appendTimestampAttribute(timeStampTokenBytes, at)); Collection<SignerInformation> signers = new ArrayList<SignerInformation>(1); signers.add(firstSignerInfo); SignerInformationStore sis = new SignerInformationStore(signers); cmsSignedData = CMSSignedData.replaceSigners(cmsSignedData, sis); } catch (Exception e) { ExceptionHandlerTyped.<SPISignatureException>handle(SPISignatureException.class, e); } }
/** * Genera una lista contenente tutti i firmatari presenti nella busta crittografica * * @return la lista con tutti i firmatari */ List<SignerInformation> getAllSigners() { // genera la lista List<SignerInformation> sigInfoList = new LinkedList<SignerInformation>(); // recupera i firmatari SignerInformationStore signers = signedData.getSignerInfos(); Collection<?> c = signers.getSigners(); Iterator<?> it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); sigInfoList.add(signer); } // fine while return sigInfoList; }
public List<Certificate> getSignatureCertificateInfo() { try { Store certificateStore = cmsSignedData.getCertificates(); Collection<X509CertificateHolder> certificateCollection = certificateStore.getMatches(null); List<Certificate> x509CertsCollection = new ArrayList<Certificate>(certificateCollection.size()); for (X509CertificateHolder certHolder : certificateCollection) { x509CertsCollection.add( CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME) .generateCertificate(new ByteArrayInputStream(certHolder.getEncoded()))); } return x509CertsCollection; } catch (Exception e) { ExceptionHandlerTyped.<SPISignatureException>handle(SPISignatureException.class, e); } return null; }
// unsigned CRLs at the root of CMS structure (outside signerInfos) public Collection<CRL> getUnsignedCRLs() { try { Collection<CertificateList> crlCollection = cmsSignedData.getCRLs().getMatches(null); // Then we need to "cast" from bouncycastle.CertificateList to java.CRL Collection<CRL> x509CrlsCollection = new HashSet<CRL>(crlCollection.size()); for (CertificateList certList : crlCollection) { x509CrlsCollection.add( CertificateFactory.getInstance("X.509", BouncyCastleProvider.PROVIDER_NAME) .generateCRL(new ByteArrayInputStream(certList.getEncoded()))); } return x509CrlsCollection; } catch (Exception e) { ExceptionHandlerTyped.<SPISignatureException>handle(SPISignatureException.class, e); } return null; }
private Date findTimestamp(CMSSignedData cmsSignedData) { Iterator iterator = cmsSignedData.getSignerInfos().getSigners().iterator(); while (iterator.hasNext()) { SignerInformation signerInformation = (SignerInformation) iterator.next(); AttributeTable signedAttrTable = signerInformation.getSignedAttributes(); if (signedAttrTable == null) { continue; } ASN1EncodableVector v = signedAttrTable.getAll(CMSAttributes.signingTime); switch (v.size()) { case 0: continue; case 1: Attribute t = (Attribute) v.get(0); ASN1Set attrValues = t.getAttrValues(); if (attrValues.size() != 1) { continue; } // found it try { return ((ASN1UTCTime) attrValues.getObjectAt(0).getDERObject()).getDate(); } catch (ParseException e) { e.printStackTrace(); } continue; default: continue; } } // no timestamp found return null; }
private MimeMultipart createSignatureEntity( byte[] entity, Collection<X509Certificate> signingCertificates) { MimeMultipart retVal = null; try { MimeBodyPart signedContent = new MimeBodyPart(new ByteArrayInputStream(entity)); ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); caps.addCapability(SMIMECapability.dES_CBC); caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1")); caps.addCapability(x509CertificateObjectsIdent); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); List certList = new ArrayList(); CMSSignedDataGenerator generator = new CMSSignedDataGenerator(); for (X509Certificate signer : signingCertificates) { if (signer instanceof X509CertificateEx) { generator.addSigner( ((X509CertificateEx) signer).getPrivateKey(), signer, toDigestAlgorithmOid(this.m_digestAlgorithm), createAttributeTable(signedAttrs), null); certList.add(signer); } } CertStore certsAndcrls = CertStore.getInstance( "Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderName()); generator.addCertificatesAndCRLs(certsAndcrls); CMSProcessableBodyPart content = new CMSProcessableBodyPart(signedContent); CMSSignedData signedData = generator.generate(content, false, CryptoExtensions.getJCEProviderName()); String header = "signed; protocol=\"application/pkcs7-signature\"; micalg=" + toDigestAlgorithmMicalg(this.m_digestAlgorithm); String encodedSig = Base64.encodeBase64String(signedData.getEncoded()); retVal = new MimeMultipart(header.toString()); MimeBodyPart sig = new MimeBodyPart(new InternetHeaders(), encodedSig.getBytes("ASCII")); sig.addHeader( "Content-Type", "application/pkcs7-signature; name=smime.p7s; smime-type=signed-data"); sig.addHeader("Content-Disposition", "attachment; filename=\"smime.p7s\""); sig.addHeader("Content-Description", "S/MIME Cryptographic Signature"); sig.addHeader("Content-Transfer-Encoding", "base64"); retVal.addBodyPart(signedContent); retVal.addBodyPart(sig); } catch (MessagingException e) { throw new MimeException(MimeError.InvalidMimeEntity, e); } catch (IOException e) { throw new SignatureException(SignatureError.InvalidMultipartSigned, e); } catch (Exception e) { throw new NHINDException(MimeError.Unexpected, e); } return retVal; }
private static byte[] getEncoded(CMSSignedData obj) throws IOException { if (obj != null) { return obj.getEncoded(); } return new byte[] {'0', 0}; }
@Test public void testCMSSignature() throws Exception { // setup byte[] toBeSigned = "hello world".getBytes(); String signatureDescription = "Test CMS Signature"; CMSTestSignatureService signatureService = new CMSTestSignatureService(toBeSigned, signatureDescription); KeyPair keyPair = PkiTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); X509Certificate certificate = PkiTestUtils.generateCertificate( keyPair.getPublic(), "CN=Test", notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null, new KeyUsage(KeyUsage.nonRepudiation)); List<X509Certificate> signingCertificateChain = new LinkedList<X509Certificate>(); signingCertificateChain.add(certificate); // operate DigestInfo digestInfo = signatureService.preSign(null, signingCertificateChain, null, null, null); // verify assertNotNull(digestInfo); byte[] digestValue = digestInfo.digestValue; LOG.debug("digest value: " + Hex.encodeHexString(digestValue)); assertNotNull(digestValue); assertEquals(signatureDescription, digestInfo.description); assertEquals("SHA1", digestInfo.digestAlgo); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPrivate()); byte[] digestInfoValue = ArrayUtils.addAll(PkiTestUtils.SHA1_DIGEST_INFO_PREFIX, digestValue); byte[] signatureValue = cipher.doFinal(digestInfoValue); LOG.debug("signature value: " + Hex.encodeHexString(signatureValue)); // operate signatureService.postSign(signatureValue, signingCertificateChain); // verify byte[] cmsSignature = signatureService.getCMSSignature(); CMSSignedData signedData = new CMSSignedData(cmsSignature); SignerInformationStore signers = signedData.getSignerInfos(); Iterator<SignerInformation> iter = signers.getSigners().iterator(); while (iter.hasNext()) { SignerInformation signer = iter.next(); SignerId signerId = signer.getSID(); assertTrue(signerId.match(certificate)); assertTrue(signer.verify(keyPair.getPublic(), BouncyCastleProvider.PROVIDER_NAME)); } byte[] data = (byte[]) signedData.getSignedContent().getContent(); assertArrayEquals(toBeSigned, data); }
protected SignerInformation createSignerInformation() throws Exception { X509CertificateEx internalCert = TestUtils.getInternalCert("user1"); String testMessage = TestUtils.readResource("MultipartMimeMessage.txt"); MimeMessage entity = EntitySerializer.Default.deserialize(testMessage); Message message = new Message(entity); MimeEntity entityToSig = message.extractEntityForSignature(true); byte[] messageBytes = EntitySerializer.Default.serializeToBytes(entityToSig); // Serialize message out as // ASCII encoded... MimeBodyPart partToSign = null; try { partToSign = new MimeBodyPart(new ByteArrayInputStream(messageBytes)); } catch (Exception e) { } SMIMESignedGenerator gen = new SMIMESignedGenerator(); ASN1EncodableVector signedAttrs = new ASN1EncodableVector(); SMIMECapabilityVector caps = new SMIMECapabilityVector(); caps.addCapability(SMIMECapability.dES_EDE3_CBC); caps.addCapability(SMIMECapability.rC2_CBC, 128); caps.addCapability(SMIMECapability.dES_CBC); caps.addCapability(new DERObjectIdentifier("1.2.840.113549.1.7.1")); caps.addCapability(PKCSObjectIdentifiers.x509Certificate); signedAttrs.add(new SMIMECapabilitiesAttribute(caps)); List<X509Certificate> certList = new ArrayList<X509Certificate>(); gen.addSigner( internalCert.getPrivateKey(), internalCert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null); certList.add(internalCert); theGetCertificates = certList; MimeMultipart retVal = null; CertStore certsAndcrls = CertStore.getInstance( "Collection", new CollectionCertStoreParameters(certList), CryptoExtensions.getJCEProviderName()); gen.addCertificatesAndCRLs(certsAndcrls); retVal = gen.generate(partToSign, CryptoExtensions.getJCEProviderName()); ByteArrayOutputStream oStream = new ByteArrayOutputStream(); retVal.writeTo(oStream); oStream.flush(); byte[] serialzedBytes = oStream.toByteArray(); ByteArrayDataSource dataSource = new ByteArrayDataSource(serialzedBytes, retVal.getContentType()); MimeMultipart verifyMM = new MimeMultipart(dataSource); CMSSignedData signeddata = new CMSSignedData( new CMSProcessableBodyPartInbound(partToSign), verifyMM.getBodyPart(1).getInputStream()); SignerInformationStore signers = signeddata.getSignerInfos(); Collection c = signers.getSigners(); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); return signer; } return null; }
public boolean doJob() { String strMethod = "doJob()"; try { // _validateCmsSignature(); CMSSignedData cms = _getSignPkcs7(); SignerInformationStore sis = cms.getSignerInfos(); Collection colSignerInfo = sis.getSigners(); Iterator itrSignerInfo = colSignerInfo.iterator(); SignerInformation sin = (SignerInformation) itrSignerInfo.next(); // r�cup�ration du certificat du signataire CertStore cse = cms.getCertificatesAndCRLs("Collection", CmsVerif._STR_KST_PROVIDER_BC); Iterator itrCert = cse.getCertificates(sin.getSID()).iterator(); X509Certificate crt = (X509Certificate) itrCert.next(); // Verifie la signature boolean blnCoreValidity = sin.verify(crt, CmsVerif._STR_KST_PROVIDER_BC); if (blnCoreValidity) { MySystem.s_printOutTrace(this, strMethod, "blnCoreValidity=true"); String strBody = "CMS Detached signature is OK!"; strBody += "\n\n" + ". CMS signature file location:"; strBody += "\n " + super._strPathAbsFileSig_; strBody += "\n\n" + ". Data file location:"; strBody += "\n " + super._strPathAbsFileData_; OPAbstract.s_showDialogInfo(super._frmOwner_, strBody); // SignerInfo sio = sin.toSignerInfo(); SignerId sid = sin.getSID(); if (sid != null) { System.out.println("sid.getSerialNumber()=" + sid.getSerialNumber()); System.out.println("sid.getIssuerAsString()=" + sid.getIssuerAsString()); System.out.println("sid.getSubjectAsString()=" + sid.getSubjectAsString()); } /*System.out.println("sin.getDigestAlgOID()=" + sin.getDigestAlgOID()); System.out.println("sin.getEncryptionAlgOID()=" + sin.getEncryptionAlgOID()); System.out.println("sin.toString()=" + sin.toString()); System.out.println("sin.getVersion()=" + sin.getVersion());*/ } else { MySystem.s_printOutWarning(this, strMethod, "blnCoreValidity=true"); String strBody = "CMS Detached signature is WRONG!"; strBody += "\n\n" + ". CMS signature file location:"; strBody += "\n " + super._strPathAbsFileSig_; strBody += "\n\n" + ". Data file location:"; strBody += "\n " + super._strPathAbsFileData_; OPAbstract.s_showDialogWarning(super._frmOwner_, strBody); } } catch (Exception exc) { exc.printStackTrace(); MySystem.s_printOutError(this, strMethod, "exc caught"); String strBody = "Failed to verify CMS detached signature."; strBody += "\n\n" + "Possible reason: wrong data file"; strBody += "\n\n" + "got exception."; strBody += "\n" + exc.getMessage(); strBody += "\n\n" + "More: see your session.log"; OPAbstract.s_showDialogError(super._frmOwner_, strBody); return false; } // TODO return true; }