Example usage for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder

List of usage examples for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder

Introduction

In this page you can find the example usage for org.bouncycastle.operator.jcajce JcaContentSignerBuilder JcaContentSignerBuilder.

Prototype

public JcaContentSignerBuilder(String signatureAlgorithm) 

Source Link

Usage

From source file:com.aaasec.sigserv.csspsupport.models.SupportModel.java

License:EUPL

public static X509Certificate generateV1Certificate(String subject, KeyPair pair, SigAlgorithms algorithm)
        throws OperatorCreationException, IOException, CertificateException, KeyStoreException,
        NoSuchAlgorithmException {

    BigInteger certSerial = BigInteger.valueOf(System.currentTimeMillis());
    X500Name issuerDN = new X500Name("CN=" + subject);
    X500Name subjectDN = new X500Name("CN=" + subject);
    Calendar startTime = Calendar.getInstance();
    startTime.setTime(new Date());
    startTime.add(Calendar.HOUR, -2);
    Calendar expiryTime = Calendar.getInstance();
    expiryTime.setTime(new Date());
    expiryTime.add(Calendar.YEAR, 10);
    Date notBefore = startTime.getTime();
    Date notAfter = expiryTime.getTime();
    PublicKey pubKey = (pair.getPublic());
    X509v1CertificateBuilder certGen = new JcaX509v1CertificateBuilder(issuerDN, certSerial, notBefore,
            notAfter, subjectDN, pubKey);

    ContentSigner signer = new JcaContentSignerBuilder(algorithm.getDummyCertAlgo()).build(pair.getPrivate());
    byte[] encoded = certGen.build(signer).getEncoded();
    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    InputStream is = new ByteArrayInputStream(encoded);
    X509Certificate generateCertificate = (X509Certificate) fact.generateCertificate(is);
    is.close();//from  w  ww  . j a  va2  s  .  c om

    String certStr = generateCertificate.toString();
    //        strb.append("Certificate:\n").append(certStr).append("\n");

    return generateCertificate;
}

From source file:com.ackpdfbox.app.CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation.//  w w w  .  j a va2s . com
 *
 * This method will be called from inside of the pdfbox and create the PKCS #7 signature.
 * The given InputStream contains the bytes that are given by the byte range.
 *
 * This method is for internal use only.
 *
 * Use your favorite cryptographic library to implement PKCS #7 signature creation.
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    //TODO this method should be private
    try {
        List<Certificate> certList = new ArrayList<Certificate>();
        certList.add(certificate);
        Store certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate
                .getInstance(ASN1Primitive.fromByteArray(certificate.getEncoded()));
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
        gen.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                        .build(sha1Signer, new X509CertificateHolder(cert)));
        gen.addCertificates(certs);
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        CMSSignedData signedData = gen.generate(msg, false);
        if (tsaClient != null) {
            signedData = signTimeStamps(signedData);
        }
        return signedData.getEncoded();
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (TSPException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
}

From source file:com.adaptris.security.certificate.CertRequestHandler.java

License:Apache License

/**
 * Create a certificate Request.//  w ww. java 2s  .  c om
 */
private static CertificationRequest createCertRequest(Certificate c, PrivateKey key) throws Exception {

    X509Certificate x509 = (X509Certificate) c;
    x509.getSigAlgName();

    X500Name entityName = new X500Name(x509.getSubjectDN().getName());
    KeyPair entityPair = KeyPairGenerator.getInstance("RSA").genKeyPair();
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(x509.getPublicKey().getEncoded());
    // Generate the certificate signing request
    PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(entityName,
            publicKeyInfo);
    //        // SCEP servers usually require a challenge password
    //        csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERPrintableString(new String(
    //                "password".toCharArray())));
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(x509.getSigAlgName());
    PKCS10CertificationRequest csr = csrBuilder.build(builder.build(entityPair.getPrivate()));

    //    CertificateRequest certRequest = new CertificateRequest(
    //        x509.getPublicKey(), (Name) x509.getSubjectDN());
    //
    //    certRequest.sign(x509.getSignatureAlgorithm(), key);
    return csr.toASN1Structure();
}

From source file:com.adaptris.security.certificate.X509Builder.java

License:Apache License

private X509Certificate build()
        throws NoSuchAlgorithmException, CertificateException, OperatorCreationException {
    X509Certificate result = null;
    if (privateKey == null) {
        this.createKeyPair();
    }/*from   w  w w  .j  ava  2  s.co  m*/

    // The certificate is self-signed, so use the current
    // subject as the issuer
    X500Name name = certificateParm.getSubjectInfo();

    // The certificate is self-signed, do we exactly care what
    // the serial number that uniquely identifies is
    BigInteger serial = BigInteger
            .valueOf(new Integer(SecurityUtil.getSecureRandom().nextInt(10000)).longValue());

    GregorianCalendar valid = new GregorianCalendar();
    Date notBefore = valid.getTime();
    valid.add(Calendar.MONTH, 12);
    Date notAfter = valid.getTime();

    SubjectPublicKeyInfo pubKeyInfo = SubjectPublicKeyInfo
            .getInstance(ASN1Sequence.getInstance(publicKey.getEncoded()));

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(name, serial, notBefore, notAfter, name,
            pubKeyInfo);
    String alg = certificateParm.getSignatureAlgorithm();
    JcaContentSignerBuilder builder = new JcaContentSignerBuilder(alg);

    // build and sign the certificate
    X509CertificateHolder certHolder = certGen.build(builder.build(privateKey));

    result = new JcaX509CertificateConverter().getCertificate(certHolder);
    // result = new X509CertificateObject(certHolder.toASN1Structure());

    return result;
}

From source file:com.android.apksigner.core.internal.apk.v1.V1SchemeSigner.java

License:Apache License

private static byte[] generateSignatureBlock(SignerConfig signerConfig, byte[] signatureFileBytes)
        throws InvalidKeyException, CertificateEncodingException, SignatureException {
    JcaCertStore certs = new JcaCertStore(signerConfig.certificates);
    X509Certificate signerCert = signerConfig.certificates.get(0);
    String jcaSignatureAlgorithm = getJcaSignatureAlgorithm(signerCert.getPublicKey(),
            signerConfig.signatureDigestAlgorithm);
    try {// w w w.  j ava  2 s.co m
        ContentSigner signer = new JcaContentSignerBuilder(jcaSignatureAlgorithm)
                .build(signerConfig.privateKey);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        gen.addSignerInfoGenerator(
                new SignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build(),
                        SignerInfoSignatureAlgorithmFinder.INSTANCE).setDirectSignature(true).build(signer,
                                new JcaX509CertificateHolder(signerCert)));
        gen.addCertificates(certs);

        CMSSignedData sigData = gen.generate(new CMSProcessableByteArray(signatureFileBytes), false);

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
            DEROutputStream dos = new DEROutputStream(out);
            dos.writeObject(asn1.readObject());
        }
        return out.toByteArray();
    } catch (OperatorCreationException | CMSException | IOException e) {
        throw new SignatureException("Failed to generate signature", e);
    }
}

From source file:com.android.builder.internal.packaging.sign.SignatureExtension.java

License:Apache License

/**
 * Computes the digital signature of an array of data.
 *
 * @param data the data//www . java  2s .com
 * @return the digital signature
 * @throws IOException failed to read/write signature data
 * @throws CertificateEncodingException failed to sign the data
 * @throws OperatorCreationException failed to sign the data
 * @throws CMSException failed to sign the data
 */
private byte[] computePkcs7Signature(@NonNull byte[] data)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {
    CMSProcessableByteArray cmsData = new CMSProcessableByteArray(data);

    ArrayList<X509Certificate> certList = new ArrayList<>();
    certList.add(mCertificate);
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    String signatureAlgName = mSignatureAlgorithm.signatureAlgorithmName(mDigestAlgorithm);
    ContentSigner shaSigner = new JcaContentSignerBuilder(signatureAlgName).build(mPrivateKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(shaSigner, mCertificate));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(cmsData, false);

    ByteArrayOutputStream outputBytes = new ByteArrayOutputStream();

    /*
     * DEROutputStream is not closeable! OMG!
     */
    DEROutputStream dos = null;
    try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
        dos = new DEROutputStream(outputBytes);
        dos.writeObject(asn1.readObject());

        DEROutputStream toClose = dos;
        dos = null;
        toClose.close();
    } catch (IOException e) {
        if (dos != null) {
            try {
                dos.close();
            } catch (IOException ee) {
                e.addSuppressed(ee);
            }
        }
    }

    return outputBytes.toByteArray();
}

From source file:com.android.builder.internal.packaging.sign.SignatureTestUtils.java

License:Apache License

/**
 * Generates a private key / certificate.
 *
 * @param sign the asymmetric cypher, <em>e.g.</em>, {@code RSA}
 * @param full the full signature algorithm name, <em>e.g.</em>, {@code SHA1withRSA}
 * @return the pair with the private key and certificate
 * @throws Exception failed to generate the signature data
 *//*w ww.j a  va2 s .  c  o  m*/
@NonNull
public static Pair<PrivateKey, X509Certificate> generateSignature(@NonNull String sign, @NonNull String full)
        throws Exception {
    // http://stackoverflow.com/questions/28538785/
    // easy-way-to-generate-a-self-signed-certificate-for-java-security-keystore-using

    KeyPairGenerator generator = null;
    try {
        generator = KeyPairGenerator.getInstance(sign);
    } catch (NoSuchAlgorithmException e) {
        Assume.assumeNoException("Algorithm " + sign + " not supported.", e);
    }

    assertNotNull(generator);
    KeyPair keyPair = generator.generateKeyPair();

    Date notBefore = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    Date notAfter = new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000);

    X500Name issuer = new X500Name(new X500Principal("cn=Myself").getName());

    SubjectPublicKeyInfo publicKeyInfo;

    if (keyPair.getPublic() instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        publicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(
                new RSAKeyParameters(false, rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent()));
    } else if (keyPair.getPublic() instanceof ECPublicKey) {
        publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    } else {
        fail();
        publicKeyInfo = null;
    }

    X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter,
            issuer, publicKeyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(full).setProvider(new BouncyCastleProvider())
            .build(keyPair.getPrivate());
    X509CertificateHolder holder = builder.build(signer);

    JcaX509CertificateConverter converter = new JcaX509CertificateConverter()
            .setProvider(new BouncyCastleProvider());

    return Pair.of(keyPair.getPrivate(), converter.getCertificate(holder));
}

From source file:com.android.builder.signing.SignedJarApkCreator.java

License:Apache License

/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);/*  ww w.ja va 2s .  c  o m*/
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder(
            mSignatureAlgorithm.signatureAlgorithmName(mDigestAlgorithm)).build(mKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) {
        DEROutputStream dos = new DEROutputStream(mOutputJar);
        try {
            dos.writeObject(asn1.readObject());
        } finally {
            dos.flush();
            dos.close();
        }
    }
}

From source file:com.android.builder.signing.SignedJarBuilder.java

License:Apache License

/** Write the certificate file with a digital signature. */
private void writeSignatureBlock(CMSTypedData data, X509Certificate publicKey, PrivateKey privateKey)
        throws IOException, CertificateEncodingException, OperatorCreationException, CMSException {

    ArrayList<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(publicKey);//from  w w  w  .j a  v  a2  s  .c  o  m
    JcaCertStore certs = new JcaCertStore(certList);

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1with" + privateKey.getAlgorithm())
            .build(privateKey);
    gen.addSignerInfoGenerator(
            new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                    .setDirectSignature(true).build(sha1Signer, publicKey));
    gen.addCertificates(certs);
    CMSSignedData sigData = gen.generate(data, false);

    ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded());
    DEROutputStream dos = new DEROutputStream(mOutputJar);
    dos.writeObject(asn1.readObject());

    dos.flush();
    dos.close();
    asn1.close();
}

From source file:com.android.ide.common.signing.KeystoreHelper.java

License:Apache License

/**
 * Generates a key and self-signed certificate pair.
 * @param asymmetric the asymmetric encryption algorithm (<em>e.g.,</em> {@code RSA})
 * @param sign the signature algorithm (<em>e.g.,</em> {@code SHA1withRSA})
 * @param validityYears number of years the certificate should be valid, must be greater than
 * zero/* w w w.  ja  va2  s .  c o m*/
 * @param dn the distinguished name of the issuer and owner of the certificate
 * @return a pair with the private key and the corresponding certificate
 * @throws KeytoolException failed to generate the pair
 */
private static Pair<PrivateKey, X509Certificate> generateKeyAndCertificate(@NonNull String asymmetric,
        @NonNull String sign, int validityYears, @NonNull String dn) throws KeytoolException {
    Preconditions.checkArgument(validityYears > 0, "validityYears <= 0");

    KeyPair keyPair;
    try {
        keyPair = KeyPairGenerator.getInstance(asymmetric).generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        throw new KeytoolException(
                "Failed to generate key and certificate pair for " + "algorithm '" + asymmetric + "'.", e);
    }

    Date notBefore = new Date(System.currentTimeMillis());
    Date notAfter = new Date(System.currentTimeMillis() + validityYears * 365L * 24 * 60 * 60 * 1000);

    X500Name issuer = new X500Name(new X500Principal(dn).getName());

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter,
            issuer, publicKeyInfo);

    ContentSigner signer;
    try {
        signer = new JcaContentSignerBuilder(sign).setProvider(new BouncyCastleProvider())
                .build(keyPair.getPrivate());
    } catch (OperatorCreationException e) {
        throw new KeytoolException("Failed to build content signer with signature algorithm '" + sign + "'.",
                e);
    }

    X509CertificateHolder holder = builder.build(signer);

    JcaX509CertificateConverter converter = new JcaX509CertificateConverter()
            .setProvider(new BouncyCastleProvider());

    X509Certificate certificate;
    try {
        certificate = converter.getCertificate(holder);
    } catch (CertificateException e) {
        throw new KeytoolException("Failed to obtain the self-signed certificate.", e);
    }

    return Pair.of(keyPair.getPrivate(), certificate);
}