Package org.bouncycastle.cms

Examples of org.bouncycastle.cms.CMSSignedDataGenerator


            Security.addProvider(new BouncyCastleProvider());

            PrivateKey key = getPrivateKey(args[1]);
            System.out.println("File read sucessfully");

            CMSSignedDataGenerator generator = new CMSSignedDataGenerator();

            CMSTypedData body = getCMSContent(args[0]);
            System.out.println("Content read sucessfully");

            X509Certificate cert = (X509Certificate) readCert(args[2]);
            System.out.println("Certificate read sucessfully");

            ContentSigner sha256Signer = new JcaContentSignerBuilder("SHA256withRSA").setProvider("BC").build(key);

            Store certs = certToStore(cert);

            generator.addCertificates(certs);
            generator.addSignerInfoGenerator(
                          new JcaSignerInfoGeneratorBuilder(
                                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
                          .build(sha256Signer, cert));

            CMSSignedData signed = generator.generate(body, true);
            System.out.println("Signed");

            Properties props = System.getProperties();
            Session session = Session.getDefaultInstance(props, null);
           
View Full Code Here


            AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WITHRSAENCRYPTION");
            AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
            RSAPrivateKey privateRSAKey = (RSAPrivateKey)privKey;
            RSAKeyParameters keyParams = new RSAKeyParameters(true, privateRSAKey.getModulus(), privateRSAKey.getPrivateExponent());
            ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(keyParams);
            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
            gen.addSignerInfoGenerator(
                    new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                        .build(sigGen, new X509CertificateHolder(certificate)));
            CMSProcessableInputStream processable = new CMSProcessableInputStream(content);
            CMSSignedData signedData = gen.generate(processable, false);
            return signedData.getEncoded();
        }
        catch (CertificateEncodingException e)
        {
            throw new IOException(e);
View Full Code Here

    {
        try
        {
            org.bouncycastle.asn1.x509.Certificate certificate =
                    org.bouncycastle.asn1.x509.Certificate.getInstance(ASN1Primitive.fromByteArray(certificateChain[0].getEncoded()));
            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

           
            AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WITHRSAENCRYPTION");
            AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
            RSAPrivateKey privateRSAKey = (RSAPrivateKey)privateKey;
            RSAKeyParameters keyParams = new RSAKeyParameters(true, privateRSAKey.getModulus(), privateRSAKey.getPrivateExponent());
            ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(keyParams);

            gen.addSignerInfoGenerator(
                    new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                        .build(sigGen, new X509CertificateHolder(certificate)));
            CMSProcessableInputStream processable = new CMSProcessableInputStream(content);
            CMSSignedData signedData = gen.generate(processable, false);
            if (tsaClient != null)
            {
                signedData = signTimeStamps(signedData);
            }
            return signedData.getEncoded();
View Full Code Here

   */
  public byte[] sign(InputStream content) throws SignatureException,
      IOException
  {
    CMSProcessableInputStream input = new CMSProcessableInputStream(content);
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    // CertificateChain
    List<Certificate> certList = Arrays.asList(cert);

    CertStore certStore = null;
    try
    {
      certStore = CertStore.getInstance("Collection",
          new CollectionCertStoreParameters(certList), provider);
      gen.addSigner(privKey, (X509Certificate) certList.get(0),
          CMSSignedGenerator.DIGEST_SHA256);
      gen.addCertificatesAndCRLs(certStore);
      CMSSignedData signedData = gen.generate(input, false, provider);
      return signedData.getEncoded();
    }
    catch (Exception e)
    {
      // should be handled
View Full Code Here

   * </p>
   */
  public byte[] sign(InputStream content) throws SignatureException, IOException
  {
    CMSProcessableInputStream input = new CMSProcessableInputStream(content);
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    // CertificateChain
    List<Certificate> certList = Arrays.asList(cert);

    CertStore certStore = null;
    try {
      certStore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), provider);
      gen.addSigner(privKey, (X509Certificate) certList.get(0), CMSSignedGenerator.DIGEST_SHA256);
      gen.addCertificatesAndCRLs(certStore);
      CMSSignedData signedData = gen.generate(input, false, provider);
      return signedData.getEncoded();
    } catch (Exception e) {
      // should be handled
      System.err.println("Error while creating pkcs7 signature.");
      e.printStackTrace();
View Full Code Here

   
    private byte[] createPKCS7(Certificate[] chain, PrivateKey pk, X509Certificate cert) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, CMSException, IOException {
      Collection<Certificate> certList = Arrays.asList(chain);
      CMSProcessable msg = new CMSProcessableByteArray(new byte[0]);
      CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
      CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
      gen.addCertificatesAndCRLs(certs);
      // it is possible to sign the pkcs7, but it's not currently used
      CMSSignedData s = null;
      if ( (pk != null) && (cert != null) ) {
        gen.addSigner(pk, cert, CMSSignedDataGenerator.DIGEST_MD5);
          s = gen.generate(msg, true, "BC");
      } else {
          s = gen.generate(msg, "BC");       
      }
      return s.getEncoded();
    }   
View Full Code Here

    }
    ExtendedCAServiceResponse returnval = null;
    final X509Certificate signerCert = (X509Certificate) certificatechain.get(0);
    final CmsCAServiceRequest serviceReq = (CmsCAServiceRequest)request;
    // Create the signed data
    final CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();
    try {
      byte[] resp = serviceReq.getDoc();
      // Add our signer info and sign the message
      if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_SIGN) != 0) {
        final CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certificatechain), "BC");
        gen1.addCertificatesAndCRLs(certs);
        gen1.addSigner(privKey, signerCert, CMSSignedGenerator.DIGEST_SHA1);
        final CMSProcessable msg = new CMSProcessableByteArray(resp);
        final CMSSignedData s = gen1.generate(msg, true, "BC");
        resp = s.getEncoded();
      }
      if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_ENCRYPT) != 0) {
        CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
        edGen.addKeyTransRecipient(getCMSCertificate());
View Full Code Here

                CertStore certs = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(certList), "BC");

                // Create the signed CMS message to be contained inside the envelope
                // this message does not contain any message, and no signerInfo
                CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
                gen.addCertificatesAndCRLs(certs);
                CMSSignedData s = gen.generate(null, false, "BC");

                // Envelope the CMS message
                if (recipientKeyInfo != null) {
                    try {
                        X509Certificate rec = (X509Certificate)CertTools.getCertfromByteArray(recipientKeyInfo);
                        log.debug("Added recipient information - issuer: '" + CertTools.getIssuerDN(rec) + "', serno: '" + CertTools.getSerialNumberAsString(rec));
                        edGen.addKeyTransRecipient(rec);
                    } catch (CertificateException e) {
                        throw new IOException("Can not decode recipients self signed certificate!");
                    }
                } else {
                    edGen.addKeyTransRecipient((X509Certificate) cert);
                }
                CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(s.getEncoded()),
                        SMIMECapability.dES_CBC.getId(), "BC");

                log.debug("Enveloped data is " + ed.getEncoded().length + " bytes long");
                msg = new CMSProcessableByteArray(ed.getEncoded());
            } else {
                // Create an empty message here
                //msg = new CMSProcessableByteArray("PrimeKey".getBytes());
                msg = new CMSProcessableByteArray(new byte[0]);
            }

            // Create the outermost signed data
            CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();

            // add authenticated attributes...status, transactionId, sender- and recipientNonce and more...
            Hashtable attributes = new Hashtable();
            DERObjectIdentifier oid;
            Attribute attr;
            DERSet value;
           
            // Content Type
            /* Added automagically by CMSSignedDataGenerator
            oid = PKCSObjectIdentifiers.pkcs_9_at_contentType;
            value = new DERSet(PKCSObjectIdentifiers.data);
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
            */

            // Message digest
            /* Added automagically by CMSSignedDataGenerator
            byte[] digest = null;
            if (s != null) {
                MessageDigest md = MessageDigest.getInstance("SHA1");
                digest = md.digest(s.getEncoded());
            } else {
                digest = new byte[]{0};
            }
            oid = PKCSObjectIdentifiers.pkcs_9_at_messageDigest;
            value = new DERSet(new DEROctetString(digest));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
            */

            // Message type (certrep)
            oid = new DERObjectIdentifier(ScepRequestMessage.id_messageType);
            value = new DERSet(new DERPrintableString("3"));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);

            // TransactionId
            if (transactionId != null) {
                oid = new DERObjectIdentifier(ScepRequestMessage.id_transId);
                log.debug("Added transactionId: " + transactionId);
                value = new DERSet(new DERPrintableString(transactionId));
                attr = new Attribute(oid, value);
                attributes.put(attr.getAttrType(), attr);
            }

            // status
            oid = new DERObjectIdentifier(ScepRequestMessage.id_pkiStatus);
            value = new DERSet(new DERPrintableString(status.getValue()));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);

            if (status.equals(ResponseStatus.FAILURE)) {
                oid = new DERObjectIdentifier(ScepRequestMessage.id_failInfo);
                log.debug("Added failInfo: " + failInfo.getValue());
                value = new DERSet(new DERPrintableString(failInfo.getValue()));
                attr = new Attribute(oid, value);
                attributes.put(attr.getAttrType(), attr);
            }

            // senderNonce
            if (senderNonce != null) {
                oid = new DERObjectIdentifier(ScepRequestMessage.id_senderNonce);
                log.debug("Added senderNonce: " + senderNonce);
                value = new DERSet(new DEROctetString(Base64.decode(senderNonce.getBytes())));
                attr = new Attribute(oid, value);
                attributes.put(attr.getAttrType(), attr);
            }

            // recipientNonce
            if (recipientNonce != null) {
                oid = new DERObjectIdentifier(ScepRequestMessage.id_recipientNonce);
                log.debug("Added recipientNonce: " + recipientNonce);
                value = new DERSet(new DEROctetString(Base64.decode(recipientNonce.getBytes())));
                attr = new Attribute(oid, value);
                attributes.put(attr.getAttrType(), attr);
            }

            // Add our signer info and sign the message
            log.debug("Signing SCEP message with cert: "+CertTools.getSubjectDN(signCert));
            gen1.addSigner(signKey, (X509Certificate)signCert, digestAlg, new AttributeTable(attributes), null);
            signedData = gen1.generate(msg, true, provider);
            responseMessage = signedData.getEncoded();
            if (responseMessage != null) {
                ret = true;
            }
        } catch (InvalidAlgorithmParameterException e) {
View Full Code Here

    byte[] retdata = null;
    try{
          ArrayList certList = new ArrayList();
          certList.add(signCert);
          CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), provider);         
      CMSSignedDataGenerator    gen = new CMSSignedDataGenerator();
      gen.addCertificatesAndCRLs(certs);
      gen.addSigner(signKey, signCert, signAlg);       
      CMSSignedData           signedData = gen.generate(new CMSProcessableByteArray(data), true, provider);
      retdata = signedData.getEncoded();
    } catch(Exception e){
      log.error("Error signing data : ", e);
    }
    return retdata;
View Full Code Here

        CMSEnvelopedData ed = edGen.generate(envThis, SMIMECapability.dES_CBC.getId(), "BC");
        return ed;
    }
   
    private CMSSignedData sign(CMSProcessable signThis, String messageType) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException, InvalidAlgorithmParameterException, CertStoreException {
        CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();

        // add authenticated attributes...status, transactionId, sender- and more...
        Hashtable attributes = new Hashtable();
        DERObjectIdentifier oid;
        Attribute attr;
        DERSet value;
       
        // Message type (certreq)
        oid = new DERObjectIdentifier(ScepRequestMessage.id_messageType);
        value = new DERSet(new DERPrintableString(messageType));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        // TransactionId
        byte[] digest = CertTools.generateMD5Fingerprint(cert.getPublicKey().getEncoded());
        transactionId = new String(Base64.encode(digest));
        oid = new DERObjectIdentifier(ScepRequestMessage.id_transId);
        value = new DERSet(new DERPrintableString(Base64.encode(digest)));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        // senderNonce
        byte[] nonce = new byte[16];
        SecureRandom randomSource = SecureRandom.getInstance("SHA1PRNG");
        randomSource.nextBytes(nonce);
        senderNonce = new String(Base64.encode(nonce));
        if (nonce != null) {
            oid = new DERObjectIdentifier(ScepRequestMessage.id_senderNonce);
            log.debug("Added senderNonce: " + senderNonce);
            value = new DERSet(new DEROctetString(nonce));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // Add our signer info and sign the message
        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
        gen1.addCertificatesAndCRLs(certs);
        gen1.addSigner(keys.getPrivate(), cert, digestOid,
                new AttributeTable(attributes), null);
        // The signed data to be enveloped
        CMSSignedData s = gen1.generate(signThis, true, "BC");
        return s;
    }
View Full Code Here

TOP

Related Classes of org.bouncycastle.cms.CMSSignedDataGenerator

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.