Example usage for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME

List of usage examples for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME

Introduction

In this page you can find the example usage for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.

Prototype

String PROVIDER_NAME

To view the source code for org.bouncycastle.jce.provider BouncyCastleProvider PROVIDER_NAME.

Click Source Link

Usage

From source file:com.opentrust.spi.pdf.PDFEnvelopedSignature.java

License:Mozilla Public License

/**
  * Verifies a signature using the sub-filter adbe.pkcs7.detached or
  * adbe.pkcs7.sha1 or ETSI.CAdES.detached or ETSI.RFC3161
  * @param contentsKey the /Contents key
  * @param provider the provider or <code>null</code> for the default provider
 * @param acroFields //from w w  w.  j  a  va  2 s .c o m
  */
protected PDFEnvelopedSignature(byte[] contentsKey, String provider, PdfName subFilter, AcroFields acroFields,
        String signatureFieldName) {
    try {
        log.debug(Channel.TECH,
                "Verifying an adbe.pkcs7.detached, adbe.pkcs7.sha1 or ETSI.CAdES.detached signature");
        this.acroFields = acroFields;
        this.signatureFieldName = signatureFieldName;
        this.contentsKey = contentsKey;
        if (subFilter == PdfName.ADBE_PKCS7_DETACHED)
            this.subFilter = SF_ADBE_PKCS7_DETACHED;
        else if (subFilter == PdfName.ADBE_PKCS7_SHA1)
            this.subFilter = SF_ADBE_PKCS7_SHA1;
        else if (subFilter == PdfName.ETSI_CADES_DETACHED)
            this.subFilter = SF_ETSI_CADES_DETACHED;
        else if (subFilter == PdfName.ETSI_RFC3161)
            this.subFilter = SF_ETSI_RFC3161;
        else
            throw new IllegalArgumentException("Unknown subFilter found in signature dictionary : "
                    + (subFilter == null ? null : new String(subFilter.getBytes())));

        log.debug(Channel.TECH, "Signature subFilter is %1$s", this.subFilter);

        if (this.subFilter == SF_ETSI_RFC3161) {
            // Then contentsKey contains a TimeStamptoken
            //docTimestampTStoken = TimestampTokenManagerFactory.getInstance().getTimeStampToken(contentsKey);
            docTimestampTStoken = new BCTimeStampToken(contentsKey);
            dataDigestAlgorithm = docTimestampTStoken.getMessageImprintAlgName();
            verifyDigest = MessageDigest.getInstance(dataDigestAlgorithm, BouncyCastleProvider.PROVIDER_NAME);
        } else {
            cmsSignature = new CMSSignedDataWrapper(contentsKey); // uses provider BC, not provider given as parameter. TODO ?
            // the version
            version = cmsSignature.getVersion();
            log.debug(Channel.TECH, "Parsing CMS Data, version=%1$s", version);

            cmsContentType = cmsSignature.getContentType();
            log.debug(Channel.TECH, "Parsing CMS Data, cmsContentType=%1$s", cmsContentType);

            if (cmsSignature.hasMultipleSignerInfos())
                throw new IllegalArgumentException(
                        "This PKCS#7 object has multiple SignerInfos - only one is supported at this time"); // and even forbidden for PAdES ?

            // the digestAlgorithms property is not fetched. We have no use for it, it is used internally by CMSSignature 

            certs = cmsSignature.getSignatureCertificateInfo();
            crls = cmsSignature.getCRLs();
            ocspResponses = cmsSignature.getOCSPResponses();
            log.debug(Channel.TECH, "Parsing CMS Data, certs=%1$s", certs);
            log.debug(Channel.TECH, "Parsing CMS Data, crls=%1$s", crls);
            log.debug(Channel.TECH, "Parsing CMS Data, ocspResponses=%1$s", ocspResponses);

            signerversion = cmsSignature.getSignerVersion();
            log.debug(Channel.TECH, "Parsing CMS Data, signerversion=%1$s", signerversion);

            signCert = (X509Certificate) cmsSignature.getSignerCertificate();
            if (signCert == null) {
                throw new IllegalArgumentException("Can't find signing certificate");
            }
            log.debug(Channel.TECH, "Parsing CMS Data, signCert=%1$s", signCert);

            dataDigestAlgorithm = cmsSignature.getDataDigestAlgorithm();
            log.debug(Channel.TECH, "Parsing CMS Data, dataDigestAlgorithm=%1$s", dataDigestAlgorithm);
            keyAndParameterAlgorithm = cmsSignature.getEncryptionAlgorithm();
            log.debug(Channel.TECH, "Parsing CMS Data, keyAndParameterAlgorithm=%1$s",
                    keyAndParameterAlgorithm);

            List<TimestampToken> timestps = cmsSignature.getSignatureTimestamps();
            if (!timestps.isEmpty()) {
                timestampToken = timestps.get(0);
                log.debug(Channel.TECH, "Parsing CMS Data, found timestamp token with date %1$s",
                        timestampToken.getDateTime());
            } else
                log.debug(Channel.TECH, "Parsing CMS Data, no timestamp token found");

            // sigAttr and digestAttr properties are not fetched. We have no use for them, they are used internally by CMSSignature

            if (cmsSignature.getSigningTime() != null) {
                cmsSignDate = Calendar.getInstance();
                cmsSignDate.setTime(cmsSignature.getSigningTime());
            }
            log.debug(Channel.TECH, "Parsing CMS Data, cmsSignDate=%1$s", cmsSignDate);

            adbePkcs7Sha1Data = cmsSignature.getEncodedEncapsulatedData();
            if (adbePkcs7Sha1Data != null) {
                if (this.subFilter != SF_ADBE_PKCS7_SHA1)
                    throw new Exception(
                            "Invalid CMS : cannot have encapsulated data for " + this.subFilter + " subfilter");
                verifyDigest = MessageDigest.getInstance("SHA1", BouncyCastleProvider.PROVIDER_NAME);
            } else {
                if (this.subFilter == SF_ADBE_PKCS7_SHA1)
                    throw new Exception("Invalid CMS : must have encapsulated data for " + SF_ADBE_PKCS7_SHA1
                            + " subfilter");
                verifyDigest = MessageDigest.getInstance(dataDigestAlgorithm,
                        BouncyCastleProvider.PROVIDER_NAME);
                try {
                    if (cmsSignature.getContentTimestamp() != null
                            && cmsSignature.getContentTimestamp().getMessageImprintAlgName() != null)
                        contentTimestampVerifyDigest = MessageDigest.getInstance(
                                cmsSignature.getContentTimestamp().getMessageImprintAlgName(),
                                BouncyCastleProvider.PROVIDER_NAME);
                    //TODO : fo not compute digest for ContentTS when digestAlgo is the same as dataDigestAlgorithm
                } catch (Exception e) {
                    log.error(Channel.TECH, "Error while parsing content timestamp : %1$s", e);
                }
            }
        }
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.opentrust.spi.pdf.PDFEnvelopedSignature.java

License:Mozilla Public License

/**
  * Used to build a PKCS7 object given all its properties (digest, certs, crls, raw signature, adbePkcs7Sha1...).
  **//*ww w .  jav  a2s  .c  om*/

//FIXME : move to other class !!!
public PDFEnvelopedSignature(byte[] digest, Certificate[] certChain, CRL[] crlList,
        OCSPResponse[] ocspResponseEncoded, String dataHashAlgorithm, String provider, byte signature[],
        byte adbePkcs7Sha1Data[], String digestEncryptionAlgorithm, Date signingTime) {
    try {
        log.debug(Channel.TECH, "Building PDFEnvelopedSignature object");
        Hashtable<DERObjectIdentifier, Attribute> signedAttributesHashtable = new Hashtable<DERObjectIdentifier, Attribute>();

        List<OCSPResponse> ocspResponses = ocspResponseEncoded == null ? null
                : Arrays.asList(ocspResponseEncoded);
        List<CRL> crls = null;
        if (crlList != null) {
            crls = Arrays.asList(crlList);
        }

        AlgorithmID algorithmID = CryptoConstants.AlgorithmID.valueOfTag(dataHashAlgorithm);
        if (algorithmID == null || algorithmID.getType() != AlgorithmType.DIGEST)
            throw new NoSuchAlgorithmException("Unknown Hash Algorithm " + dataHashAlgorithm);

        Attribute messageDigestAttribute = new Attribute(CMSAttributes.messageDigest,
                new DERSet(new DEROctetString(digest)));

        signedAttributesHashtable.put(CMSAttributes.messageDigest, messageDigestAttribute);
        this.signCert = (X509Certificate) certChain[0];
        dataDigestAlgorithm = algorithmID.getOID();
        this.crls = crls;
        this.certs = Arrays.asList(certChain);
        this.ocspResponses = ocspResponses;
        keyAndParameterAlgorithm = digestEncryptionAlgorithm;
        this.adbePkcs7Sha1Data = adbePkcs7Sha1Data;
        cmsGenerator = (CMSSignedDataStreamGenerator) CMSForPAdESBasicGenerator.buildCMSSignedGenerator(
                new ContentSignerWithProvidedSignatureValue(signature,
                        AlgorithmID.valueOfTag(getSignatureAlgorithm()).getOID()),
                true, BouncyCastleProvider.PROVIDER_NAME, signedAttributesHashtable, signCert, certs,
                signingTime, dataDigestAlgorithm, crls, ocspResponses);
        bOut = new ByteArrayOutputStream();
        sigOut = cmsGenerator.open(bOut, adbePkcs7Sha1Data != null);
        if (adbePkcs7Sha1Data != null)
            sigOut.write(adbePkcs7Sha1Data);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.rcn.service.CertificateService.java

License:Open Source License

public String generateCert(String certName, String password, int validDays, Optional<String> caPem,
        String caPassword, boolean generateCaCert, Optional<String> pkc10Request) {
    try {/*ww w . java2 s  .c  om*/
        Optional<Tuple<KeyPair, X509Certificate>> caTuple = caPem.map(c -> fromPem(c, caPassword));
        Optional<KeyPair> ca = caTuple.map(a -> a.getX());

        Optional<KeyPair> optKeyPair = Optional.ofNullable(pkc10Request.isPresent() ? null : generateKey());

        PublicKey publicKey = pkc10Request.map(this::fromPkcs10).orElseGet(() -> optKeyPair.get().getPublic());

        Date now = new Date();
        Calendar tenYears = Calendar.getInstance();
        tenYears.add(Calendar.DATE, validDays);
        X500Principal x500Principal = new X500Principal(certName);
        BigInteger serial = rndBigInt(new BigInteger("8180385048")); //max value for SN
        X500Principal issuer = caTuple.map(a -> a.getY().getSubjectX500Principal())
                .orElseGet(() -> x500Principal);
        JcaX509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(issuer, serial, now,
                new Date(tenYears.getTimeInMillis()), x500Principal, publicKey);

        v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifier(getSubjectPublicKeyInfo(publicKey)));

        ca.ifPresent(caKey -> v3CertGen.addExtension(X509Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifier(getSubjectPublicKeyInfo(caKey.getPublic()))));

        if (generateCaCert) {
            addCaExtension(v3CertGen);
        } else {
            addRegularExtension(Optional.empty(), v3CertGen);
        }

        KeyPair caKey = ca.orElseGet(
                () -> optKeyPair.orElseThrow(() -> new SecurityException("no private key for self-sign cert")));
        X509Certificate certificate = new JcaX509CertificateConverter()
                .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(v3CertGen.build(new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(caKey.getPrivate())));
        String certPem = toPem(certificate, Optional.empty());

        String keyPem = optKeyPair
                .map(k -> toPem(k, Optional.ofNullable(password.length() > 0 ? password : null))).orElse("");

        return String.format("%s%s", certPem, keyPem);
    } catch (Exception e) {
        throw new SecurityException(e);
    }
}

From source file:com.tercatech.jtsocket.JTSocketSecure.java

License:Open Source License

public JTSocketSecure(String key) throws NoSuchProviderException {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    this.key = new SecretKeySpec(key.getBytes(), "AES");
    this.iv = new IvParameterSpec(key.getBytes());

    Cipher temp = null;//from w w w. ja  v  a 2 s .  c  o m
    try {
        temp = Cipher.getInstance("AES/CBC/NoPadding", BouncyCastleProvider.PROVIDER_NAME);
    } catch (NoSuchAlgorithmException e) {
        System.out.println("AES not installed (this should never happen");
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        System.out.println("NoPadding not installed (this is pretty ridiculous");
        e.printStackTrace();
    }
    aes = temp; // Seriously, aes was going to be initialized in the one line in the try?
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

License:Open Source License

/**
 * Returns a signed certificate./*from ww w. j a  va2s .  c  o m*/
 *
 * @param builder
 *            builder to create the certificate
 * @param key
 *            private key for the certificate
 * @return a signed certificate
 * @throws OperatorCreationException
 *             if there was a problem creation a bouncy castle operator
 * @throws CertificateException
 *             if any of the certificates in the keystore could not be
 *             loaded
 */
private final X509Certificate getSignedCertificate(final X509v3CertificateBuilder builder, final PrivateKey key)
        throws OperatorCreationException, CertificateException {
    final ContentSigner signer; // Content signer
    final String provider; // Provider
    final X509Certificate signed; // Signed certificate

    provider = BouncyCastleProvider.PROVIDER_NAME;
    signer = new JcaContentSignerBuilder(getSignatureAlgorithm()).setProvider(provider).build(key);

    signed = new JcaX509CertificateConverter().setProvider(provider).getCertificate(builder.build(signer));

    LOGGER.debug("Signed certificate with {} private key {}, using algorithm {}", key.getAlgorithm(),
            Arrays.asList(key.getEncoded()), key.getFormat());

    return signed;
}

From source file:com.yosanai.java.swing.config.FileBackedConfigDialog.java

License:Open Source License

public void init(String... keys) {
    if (null == configuration) {
        ConfigPasswordDialog dialog = new ConfigPasswordDialog(null, true);
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        if (null == Security.getProvider(BouncyCastleProvider.PROVIDER_NAME)) {
            Security.insertProviderAt(new BouncyCastleProvider(), 1);
        }/*from  w w  w . j  a  v a2  s.c  o m*/
        encryptor.setAlgorithm(DEFAULT_ALGORITHM);
        dialog.setEncryptor(encryptor);
        dialog.setVisible(true);
        if (ConfigPasswordDialog.RET_OK == dialog.getReturnStatus()) {
            try {
                configuration = new EncryptedXMLConfiguration(encryptor);
                configuration.setFileName(file);
                configuration.load(file);
            } catch (ConfigurationException e) {
                try {
                    String defaultPath = System.getProperty("user.home") + "/" + file;
                    new File(defaultPath).createNewFile();
                    FileInputStream ins = new FileInputStream(defaultPath);
                    String entries = IOUtils.toString(ins);
                    IOUtils.closeQuietly(ins);
                    if (StringUtils.isBlank(entries)) {
                        configuration = new EncryptedXMLConfiguration(encryptor);
                        configuration.setFileName(defaultPath);
                        try {
                            configuration.save();
                        } catch (ConfigurationException cfEx) {
                            Logger.getLogger(FileBackedConfigDialog.class.getName()).log(Level.SEVERE, null,
                                    cfEx);
                        }
                    }
                } catch (IOException ioEx) {
                    Logger.getLogger(FileBackedConfigDialog.class.getName()).log(Level.SEVERE, null, ioEx);
                }
            }
        }
    }
    if (null != configuration) {
        configuration.setAutoSave(true);
        load(keys);
    }
}

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

License:Apache License

protected byte[] signManifestUsingContent(PKSigningInformation signingInformation, CMSTypedData content)
        throws PKSigningException {
    if (signingInformation == null || !signingInformation.isValid()) {
        throw new IllegalArgumentException("Signing information not valid");
    }//  w  ww  . j  av a 2 s.  co m

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

        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);

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

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

        JcaCertStore certs = new JcaCertStore(certList);

        generator.addCertificates(certs);

        CMSSignedData sigData = generator.generate(content, false);
        return sigData.getEncoded();
    } catch (Exception e) {
        throw new PKSigningException("Error when signing manifest", e);
    }
}

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

License:Apache License

private void addBCProvider() {
    if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new BouncyCastleProvider());
    }//from w  ww.  ja  va 2s  .  c om

}

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

License:Apache License

/**
 * Load certificate file in DER format from the filesystem or the classpath
 * //  ww  w .j  a  va 2 s  . c o m
 * @param filePath
 * @return
 * @throws IOException
 * @throws CertificateException
 */
public X509Certificate loadDERCertificate(final String filePath) throws IOException, CertificateException {
    FileInputStream certificateFileInputStream = null;
    try {
        File certFile = new File(filePath);
        if (!certFile.exists()) {
            // try loading it from the classpath
            URL localCertFile = PKFileBasedSigningUtil.class.getClassLoader().getResource(filePath);
            if (localCertFile == null) {
                throw new FileNotFoundException("File at " + filePath + " not found");
            }
            certFile = new File(localCertFile.getFile());
        }
        certificateFileInputStream = new FileInputStream(certFile);

        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        Certificate certificate = certificateFactory.generateCertificate(certificateFileInputStream);
        if (certificate instanceof X509Certificate) {
            ((X509Certificate) certificate).checkValidity();
            return (X509Certificate) certificate;
        }
        throw new IOException("The key from '" + filePath + "' could not be decrypted");
    } catch (IOException ex) {
        throw new IOException("The key from '" + filePath + "' could not be decrypted", ex);
    } catch (NoSuchProviderException ex) {
        throw new IOException("The key from '" + filePath + "' could not be decrypted", ex);
    } finally {
        IOUtils.closeQuietly(certificateFileInputStream);
    }
}

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

License:Apache License

/**
 * Load a DER Certificate from an <code>InputStream</code>.
 * /*w ww .  ja v  a  2s  .  c om*/
 * The caller is responsible for closing the stream after this method returns successfully or fails.
 * 
 * @param certificateInputStream
 *            <code>InputStream</code> containing the certificate.
 * @return Loaded certificate.
 * @throws IOException
 * @throws CertificateException
 */
public X509Certificate loadDERCertificate(final InputStream certificateInputStream)
        throws IOException, CertificateException {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        Certificate certificate = certificateFactory.generateCertificate(certificateInputStream);
        if (certificate instanceof X509Certificate) {
            ((X509Certificate) certificate).checkValidity();
            return (X509Certificate) certificate;
        }
        throw new IOException("The key from the input stream could not be decrypted");
    } catch (IOException ex) {
        throw new IOException("The key from the input stream could not be decrypted", ex);
    } catch (NoSuchProviderException ex) {
        throw new IOException("The key from the input stream could not be decrypted", ex);
    }
}