Example usage for org.bouncycastle.cms CMSProcessableFile CMSProcessableFile

List of usage examples for org.bouncycastle.cms CMSProcessableFile CMSProcessableFile

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSProcessableFile CMSProcessableFile.

Prototype

public CMSProcessableFile(File file) 

Source Link

Usage

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

/**
 * @param key/*from  ww w.  j a  v a  2s  . com*/
 * @param certs
 * @param algo
 * @param data
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws CertStoreException
 * @throws IOException
 * @throws CertificateEncodingException
 * @throws GeneralSecurityException
 */
public static byte[] pkcsDigSig(PrivateKey key, Certificate[] certs, SigningAlgo algo, StreamData data)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, CertStoreException, IOException,
        CertificateEncodingException, GeneralSecurityException {

    tstObjArg("input-content", data);
    tstObjArg("private-key", key);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    Provider prov = Crypto.getInstance().getProvider();
    List<Certificate> lst = asList(true, certs);
    CMSTypedData cms;
    X509Certificate cert = (X509Certificate) lst.get(0);

    try {
        ContentSigner cs = new JcaContentSignerBuilder(algo.toString()).setProvider(prov).build(key);

        JcaSignerInfoGeneratorBuilder bdr = new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider(prov).build());
        bdr.setDirectSignature(true);

        gen.addSignerInfoGenerator(bdr.build(cs, cert));
        gen.addCertificates(new JcaCertStore(lst));

        if (data.isDiskFile()) {
            cms = new CMSProcessableFile(data.getFileRef());
        } else {
            cms = new CMSProcessableByteArray(data.getBytes());
        }

        return gen.generate(cms, false).getEncoded();
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }

}

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

/**
 * @param cert/*from   w w  w  .  j ava  2 s . co  m*/
 * @param data
 * @param signature
 * @return
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws CertificateEncodingException
 */
public static byte[] verifyPkcsDigSig(Certificate cert, StreamData data, byte[] signature)
        throws GeneralSecurityException, IOException, CertificateEncodingException {

    tstObjArg("digital-signature", signature);
    tstObjArg("cert", cert);
    tstObjArg("input-content", data);

    Provider prov = Crypto.getInstance().getProvider();
    SignerInformation si;
    CMSProcessable cproc;
    CMSSignedData cms;
    byte[] digest;

    if (data.isDiskFile()) {
        cproc = new CMSProcessableFile(data.getFileRef());
    } else {
        cproc = new CMSProcessableByteArray(data.getBytes());
    }

    try {
        cms = new CMSSignedData(cproc, signature);
        digest = null;
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }

    List<Certificate> cl = LT();
    cl.add(cert);
    Store s = new JcaCertStore(cl);
    Collection<?> c;
    JcaSimpleSignerInfoVerifierBuilder bdr;

    for (Object obj : cms.getSignerInfos().getSigners())
        try {
            si = (SignerInformation) obj;
            c = s.getMatches(si.getSID());
            for (Iterator<?> it = c.iterator(); it.hasNext();) {
                bdr = new JcaSimpleSignerInfoVerifierBuilder().setProvider(prov);
                if (si.verify(bdr.build((X509CertificateHolder) it.next()))) {
                    digest = si.getContentDigest();
                    break;
                }
            }
            if (digest != null) {
                break;
            }
        } catch (Exception e) {
        }

    if (digest == null) {
        throw new GeneralSecurityException("Failed to decode signature: no matching certificate");
    }
    // else
    return digest;
}

From source file:de.brendamour.jpasskit.signing.PKFileBasedSigningUtil.java

License:Apache License

public void signManifestFileAndWriteToDirectory(final File temporaryPassDirectory, final File manifestJSONFile,
        final PKSigningInformation signingInformation) throws PKSigningException {

    if (temporaryPassDirectory == null || manifestJSONFile == null) {
        throw new IllegalArgumentException("Temporary directory or manifest file not provided");
    }//from   w  ww .j  a  v a2 s.  co m

    CMSProcessableFile content = new CMSProcessableFile(manifestJSONFile);
    byte[] signedDataBytes = signManifestUsingContent(signingInformation, content);

    File signatureFile = new File(temporaryPassDirectory.getAbsolutePath() + File.separator + "signature");
    FileOutputStream signatureOutputStream = null;
    try {
        signatureOutputStream = new FileOutputStream(signatureFile);
        signatureOutputStream.write(signedDataBytes);
    } catch (IOException e) {
        throw new PKSigningException("Error when writing signature to folder", e);
    } finally {
        IOUtils.closeQuietly(signatureOutputStream);
    }
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

License:Apache License

public static void signManifestFile(final File temporaryPassDirectory, final File manifestJSONFile,
        final PKSigningInformation signingInformation) throws Exception {

    if (temporaryPassDirectory == null || manifestJSONFile == null || signingInformation == null
            || !signingInformation.isValid()) {
        throw new IllegalArgumentException("Null params are not supported");
    }/*  ww  w.  ja  va2 s. c o  m*/
    addBCProvider();

    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(signingInformation.getSigningPrivateKey());

    generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                    .build(sha1Signer, signingInformation.getSigningCert()));

    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(signingInformation.getAppleWWDRCACert());
    certList.add(signingInformation.getSigningCert());

    Store certs = new JcaCertStore(certList);

    generator.addCertificates(certs);

    CMSSignedData sigData = generator.generate(new CMSProcessableFile(manifestJSONFile), false);
    byte[] signedDataBytes = sigData.getEncoded();

    File signatureFile = new File(temporaryPassDirectory.getAbsolutePath() + File.separator + "signature");
    FileOutputStream signatureOutputStream = new FileOutputStream(signatureFile);
    signatureOutputStream.write(signedDataBytes);
    signatureOutputStream.close();
}

From source file:net.sf.assinafacil.AssinadorMSCAPI.java

License:Open Source License

@Override
/***//from   ww w. j  a v  a 2  s .  c o  m
 * Assina digitalmente o arquivo de entrada e gera o arquivo de sa\u00edda.
 * nesse caso a senha n\u00e3o \u00e9 utilizada pois o keystore \u00e9 um token suja senha 
 * ser\u00e1 requerida pelo MSCAPI.
 * 
 * @return Mensagem de status que ser\u00e1 exibida na interface.
 */
public String signFile(String fileInput, String signedFileName, String password, String certificateAlias)
        throws Exception {
    if (!isInitialized()) {
        throw new java.security.KeyException(
                "Chaveiro n\u00c3\u00a3o inicializado ou erro ao acess\u00c3\u00a1-lo.");
    }

    PrivateKey priv = null;
    Certificate storecert = null;
    Certificate[] certChain = null;
    ArrayList<Certificate> certList = new ArrayList<Certificate>();
    CertStore certs = null;
    CMSSignedData signedData = null;
    CMSProcessable content = null;
    byte[] signeddata = null;

    String retorno;

    if (signedFileName == null)
        signedFileName = fileInput;

    certChain = keyStore.getCertificateChain(certificateAlias);

    if (certChain == null) {
        throw new GeneralSecurityException(
                "Cadeia do certificado " + certificateAlias + " n\u00c3\u00a3o encontrada.");
    }
    certList.addAll(Arrays.asList(certChain));

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

    storecert = keyStore.getCertificate(certificateAlias);
    priv = (PrivateKey) (keyStore.getKey(certificateAlias, null));
    if (priv == null) {
        throw new java.security.AccessControlException(
                "Acesso \u00c3\u00a0 chave foi negado... senha inv\u00c3\u00a1lida?");
    }

    CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();
    signGen.addSigner(priv, (X509Certificate) storecert, CMSSignedDataGenerator.DIGEST_SHA1);
    signGen.addCertificatesAndCRLs(certs);

    try {
        signedData = new CMSSignedData(new FileInputStream(fileInput));
        content = signedData.getSignedContent();
        signGen.addSigners(signedData.getSignerInfos());
        signGen.addCertificatesAndCRLs(signedData.getCertificatesAndCRLs("Collection", "BC"));
        CMSSignedData signedData2 = signGen.generate(content, true, PROVIDER_STRING);
        signeddata = signedData2.getEncoded();

        retorno = "Arquivo " + signedFileName + " foi assinado novamente.";

    } catch (CMSException e) {
        content = new CMSProcessableFile(new File(fileInput));
        signedData = signGen.generate(content, true, PROVIDER_STRING);
        signeddata = signedData.getEncoded();

        retorno = "Arquivo " + signedFileName + " foi assinado.";
    }

    FileOutputStream fileOutput = new FileOutputStream(signedFileName);
    fileOutput.write(signeddata);
    fileOutput.close();

    Logger.getLogger(AssinadorMSCAPI.class.getName()).log(Level.INFO, retorno);

    return retorno;
}

From source file:org.primeoservices.cfpass.PassUtils.java

License:Apache License

public static void createSignature(final String directoryPath, final String keyStoreFilePath,
        final String keyStorePassword) throws Exception {
    // Add BC provider
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }/* www  .j av a  2 s  .c om*/

    // Check directory
    final File directory = new File(directoryPath);
    if (directory.exists() && !directory.isDirectory()) {
        throw new IllegalArgumentException(directoryPath + " is not a directory");
    }

    // Check manifest file
    final File manifest = new File(directory, "manifest.json");
    if (manifest.exists() && !manifest.isFile()) {
        throw new IllegalArgumentException("File manifest.json doesn't exists");
    }

    // Check key store
    final File keyStore = new File(keyStoreFilePath);
    if (keyStore.exists() && !keyStore.isFile()) {
        throw new IllegalArgumentException("Keystore not found");
    }

    // Load key store
    final FileInputStream clientStoreIn = new FileInputStream(keyStore);
    final KeyStore clientStore = KeyStore.getInstance("PKCS12");
    clientStore.load(clientStoreIn, keyStorePassword.toCharArray());

    // Extract private key and certificate
    final Enumeration<String> aliases = clientStore.aliases();
    String alias = "";
    while (aliases.hasMoreElements()) {
        alias = aliases.nextElement();
        if (clientStore.isKeyEntry(alias)) {
            break;
        }
    }
    final PrivateKey key = (PrivateKey) clientStore.getKey(alias, keyStorePassword.toCharArray());
    final X509Certificate cert = (X509Certificate) clientStore.getCertificate(alias);

    // Load Apple certificate
    final InputStream appleCertIn = PassUtils.class.getResourceAsStream("/AppleWWDRCA.cer");
    final CertificateFactory appleCertFactory = CertificateFactory.getInstance("X.509");
    final X509Certificate appleCert = (X509Certificate) appleCertFactory.generateCertificate(appleCertIn);

    // Signature
    final ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(key);

    final ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
    final Attribute signingAttribute = new Attribute(CMSAttributes.signingTime,
            new DERSet(new DERUTCTime(new Date())));
    signedAttributes.add(signingAttribute);
    // Create the signing table
    final AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
    // Create the table table generator that will added to the Signer builder
    final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
            signedAttributesTable);

    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(appleCert);
    certList.add(cert);
    Store certs = new JcaCertStore(certList);

    final CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                    .setSignedAttributeGenerator(signedAttributeGenerator).build(sha1Signer, cert));
    generator.addCertificates(certs);

    final CMSSignedData sigData = generator.generate(new CMSProcessableFile(manifest), false);
    final byte[] signedDataBytes = sigData.getEncoded();

    // Write signature
    final File signatureFile = new File(directoryPath, "signature");
    final FileOutputStream signatureOutputStream = new FileOutputStream(signatureFile);
    signatureOutputStream.write(signedDataBytes);
    signatureOutputStream.close();
}

From source file:org.roda.common.certification.SignatureUtility.java

/**
 * Sign the file//  w  w w. j  a  v a2 s. c  om
 * 
 * @param file
 * 
 * @return an array of bytes with the signature
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CMSException
 */
public byte[] sign(File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, CMSException {
    CMSProcessableFile cmsFile = new CMSProcessableFile(file);
    CMSSignedData data = signGenerator.generate(cmsFile);
    return data.getEncoded();
}

From source file:org.roda.common.certification.SignatureUtility.java

/**
 * Verify detached signature/*from w w  w .  j a va  2s.c o m*/
 * 
 * @param file
 * @param signature
 * @return true if valid
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CertStoreException
 * @throws CMSException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws CertificateException
 * @throws OperatorCreationException
 */
public boolean verify(File file, File signature)
        throws NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, CMSException,
        FileNotFoundException, IOException, CertificateException, OperatorCreationException {
    CMSProcessableFile cmsFile = new CMSProcessableFile(file);
    CMSSignedData signedData = new CMSSignedData(cmsFile, new FileInputStream(signature));

    return verifySignatures(signedData, null);
}

From source file:org.roda.core.plugins.plugins.characterization.SignatureUtility.java

/**
 * Sign the file//  w  ww  . ja  va 2  s  . c om
 * 
 * @param file
 * 
 * @return an array of bytes with the signature
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CMSException
 */
public byte[] sign(File file) throws CMSException, IOException {
    CMSProcessableFile cmsFile = new CMSProcessableFile(file);
    CMSSignedData data = signGenerator.generate(cmsFile);
    return data.getEncoded();
}

From source file:org.roda.core.plugins.plugins.characterization.SignatureUtility.java

/**
 * Verify detached signature/* w  w w  .  ja v a 2s.c  o  m*/
 * 
 * @param file
 * @param signature
 * @return true if valid
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CertStoreException
 * @throws CMSException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws CertificateException
 */
public boolean verify(File file, File signature) throws FileNotFoundException, CMSException,
        CertificateException, NoSuchAlgorithmException, NoSuchProviderException {
    CMSProcessableFile cmsFile = new CMSProcessableFile(file);
    CMSSignedData signedData = new CMSSignedData(cmsFile, new FileInputStream(signature));
    return verifySignatures(signedData, null);
}