Example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

List of usage examples for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1InputStream ASN1InputStream.

Prototype

public ASN1InputStream(byte[] input) 

Source Link

Document

Create an ASN1InputStream based on the input byte array.

Usage

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

/**
 * Read an existing PKCS#7 object from a DER encoded byte array
 */// w w  w.j  av  a 2 s . c  om
protected static org.bouncycastle.asn1.cms.SignedData cmsSignedData(byte[] in) {
    ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(in));

    //
    // Basic checks to make sure it's a PKCS#7 SignedData Object
    //
    ASN1Primitive cms;

    try {
        cms = din.readObject();
    } catch (IOException e) {
        throw new SecurityException("can't decode CMSSignedData object");
    } finally {
        try {
            din.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    if (!(cms instanceof ASN1Sequence)) {
        throw new SecurityException("Not a valid PKCS#7 object - not a sequence");
    }

    ContentInfo content = ContentInfo.getInstance(cms);

    org.bouncycastle.asn1.cms.SignedData data = org.bouncycastle.asn1.cms.SignedData
            .getInstance(content.getContent());

    return data;
}

From source file:br.gov.jfrj.siga.cd.CRLLocator.java

License:Open Source License

/**
 * Uma vez instanciado o objeto,  possvel fazer a busca da CRL referente
 * ao certificado a ser verificado. A CRL  retornada, independente do
 * construtor utilizado, desde que esteja disponvel.
 * /*from w  w  w . j a  v  a  2  s  . c om*/
 * @return um objeto X509CRLObject para uso posterior.
 * @throws CRLException
 */
public X509CRLObject getCRL() throws InvalidCRLException, CRLException {

    try {
        if (this.certificate != null)
            this.getRemoteCRL();
        else
            this.getLocalCRL();

        // Maneira um pouco mais dificil de instanciar um X509CRLObject
        final ByteArrayInputStream bis = new ByteArrayInputStream(this.crl);
        final ASN1InputStream stream = new ASN1InputStream(bis);
        final CertificateList cl = new CertificateList((ASN1Sequence) stream.readObject());

        return new SigaX509CRLObject(cl);

    } catch (final MalformedURLException e) {

        throw new InvalidCRLException("URL de acesso a CRL est mal formada ou  invlida! (" + this.uri + ")",
                e);

    } catch (final ProtocolException e) {

        throw new InvalidCRLException(
                "Falha ao setar o mtodo HTTP/GET para fazer o download da CRL! (" + this.uri + ")", e);

    } catch (final IOException e) {

        throw new InvalidCRLException("Falha ao gerar a CRL! (" + this.uri + ")", e);
    }
}

From source file:br.gov.jfrj.siga.cd.TimeStamper.java

License:Open Source License

/**
 * Modyfy PKCS#7 data by adding timestamp
 * //from  w  ww. jav  a 2  s  .co m
 * (at) param signedData (at) throws Exception
 */
public static CMSSignedData addTimestamp(CMSSignedData signedData) throws Exception {
    Collection ss = signedData.getSignerInfos().getSigners();
    SignerInformation si = (SignerInformation) ss.iterator().next();
    TimeStampToken tok = getTimeStampToken(si.getSignature());

    //      CertStore certs = tok.getCertificatesAndCRLs("Collection", "BC");
    Store certs = tok.getCertificates();
    Store certsAndCrls = AssinaturaDigital.buscarCrlParaCadaCertificado(certs);

    CMSSignedData cmssdcrl = CMSSignedData.replaceCertificatesAndCRLs(tok.toCMSSignedData(), certsAndCrls,
            certsAndCrls, certsAndCrls);

    tok = new TimeStampToken(cmssdcrl);

    ASN1InputStream asn1InputStream = new ASN1InputStream(tok.getEncoded());
    ASN1Primitive tstDER = asn1InputStream.readObject();
    DERSet ds = new DERSet(tstDER);
    Attribute a = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, ds);
    ASN1EncodableVector dv = new ASN1EncodableVector();
    dv.add(a);
    AttributeTable at = new AttributeTable(dv);
    si = SignerInformation.replaceUnsignedAttributes(si, at);
    ss.clear();
    ss.add(si);
    SignerInformationStore sis = new SignerInformationStore(ss);
    signedData = CMSSignedData.replaceSigners(signedData, sis);
    return signedData;
}

From source file:ca.trustpoint.m2m.M2mCertificateFactory.java

License:Apache License

/**
 * Generates a certificate object and initializes it with the data read from the
 * {@link java.io.InputStream InputStream} {@code inStream}.
 *
 * <p>/*from  w w  w  .  j  a  v a 2s  .c om*/
 * The returned certificate object can be casted to the {@link M2mCertificate M2MCertificate}
 * class.
 *
 * <p>
 * The certificate provided in {@code inStream} must be DER-encoded and may be supplied in binary
 * or printable (Base64) encoding. If the certificate is provided in Base64 encoding, it must be
 * bounded at the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at the end by
 * -----END CERTIFICATE-----.
 *
 * <p>
 * Note that if the given input stream does not support {@link java.io.InputStream#mark(int) mark}
 * and {@link java.io.InputStream#reset() reset}, this method will consume the entire input
 * stream. Otherwise, each call to this method consumes one certificate and the read position of
 * the input stream is positioned to the next available byte after the inherent end-of-certificate
 * marker. If the data in the input stream does not contain an inherent end-of-certificate marker
 * (other than EOF) and there is trailing data after the certificate is parsed, a
 * {@link java.security.cert.CertificateException CertificateException} is thrown.
 *
 * @param inStream an input stream with the certificate data.
 *
 * @return a certificate object initialized with the data from the input stream.
 *
 * @exception CertificateException on parsing errors.
 */
@Override
public Certificate engineGenerateCertificate(InputStream inStream) throws CertificateException {
    if (inStream == null) {
        throw new IllegalArgumentException("input stream is null");
    }

    try {
        ASN1InputStream aIn = new ASN1InputStream(inStream);
        ASN1ApplicationSpecific app = ASN1ApplicationSpecific.getInstance(aIn.readObject());

        aIn.close();

        int appTag = app.getApplicationTag();

        if (appTag != M2mCertificate.APPLICATION_TAG_NUMBER) {
            throw new IOException("not M2M certificate application tag: " + appTag);
        }

        ASN1Sequence seq = (ASN1Sequence) app.getObject(BERTags.SEQUENCE);
        if (seq.size() != 2) {
            throw new IOException("sequence wrong size for a M2M certificate");
        }

        // Construct M2M certificate
        M2mCertificate cert = new M2mCertificate();
        for (int i = 0; i < seq.size(); i++) {
            ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i);
            CertificateFields tag = CertificateFields.getInstance(obj.getTagNo());

            switch (tag) {
            case TBS_CERTIFICATE:
                ASN1Sequence tbsCertificate = ASN1Sequence.getInstance(obj, false);
                parseTbsCertificate(tbsCertificate, cert);
                break;
            case CA_CALC_VALUE:
                ASN1OctetString cACalcValue = ASN1OctetString.getInstance(obj, false);
                cert.setCaCalcValue(cACalcValue.getOctets());
                break;
            default:
                throw new IOException("unknown M2M data field number: " + tag.getTagNumber());
            }
        }

        return cert;
    } catch (Exception e) {
        // Catch all exceptions and convert it to a CertificateException
        throw new CertificateException("exception on parsing certificate data", e);
    }
}

From source file:ca.trustpoint.m2m.M2mCertificateFactory.java

License:Apache License

/**
 * Generates a {@link java.security.cert.CertPath CertPath} object and initializes it with the
 * data read from the {@link java.io.InputStream InputStream} inStream. The data is assumed to be
 * in the specified encoding./*from  w ww .j  a v a2s .  c  o  m*/
 *
 * <p>
 * The returned certificate path object can be typecast to the {@link M2mCertPath} class.
 *
 * @param inStream an {@link java.io.InputStream InputStream} containing the data
 * @param encoding the encoding used for the data
 * @return a {@link java.security.cert.CertPath CertPath} initialized with the data from the
 *         {@link java.io.InputStream InputStream}
 * @exception CertificateException if an exception occurs while decoding or the encoding requested
 *            is not supported
 */
@Override
public CertPath engineGenerateCertPath(InputStream inStream, String encoding) throws CertificateException {
    if (inStream == null) {
        throw new CertificateException("input stream is null");
    }

    try {
        ASN1InputStream aIn = new ASN1InputStream(inStream);
        ASN1Sequence seq = ASN1Sequence.getInstance(aIn.readObject());

        aIn.close();

        ASN1Encodable[] objs;
        List<M2mCertificate> certList;
        InputStream is;
        M2mCertificate cert;

        if (encoding.equals(SupportedEncodings.PKIPATH.getId())) {
            objs = seq.toArray();
            certList = new ArrayList<M2mCertificate>(objs.length);

            // certificates in PKIPATH encoding is from root to signer but M2MCerPath stores
            // certificates from signer to root so do it in reverse order.
            for (int i = objs.length - 1; i >= 0; i--) {
                is = new ByteArrayInputStream(objs[i].toASN1Primitive().getEncoded());
                cert = (M2mCertificate) engineGenerateCertificate(is);
                certList.add(cert);
            }
        } else if (encoding.equals(SupportedEncodings.PKCS7.getId())) {
            ContentInfo ci = ContentInfo.getInstance(seq);
            SignedData sd = SignedData.getInstance(ci.getContent());
            objs = sd.getCertificates().toArray();
            certList = new ArrayList<M2mCertificate>(objs.length);

            // certificates in PKCS7 encoding is from signer to root, the same order as in M2mCertPath
            for (int i = 0; i < objs.length; i++) {
                is = new ByteArrayInputStream(objs[i].toASN1Primitive().getEncoded());
                cert = (M2mCertificate) engineGenerateCertificate(is);
                certList.add(cert);
            }
        } else {
            throw new CertificateException("unknown encoding path: " + encoding);
        }

        return new M2mCertPath(certList);
    } catch (IOException e) {
        throw new CertificateException("IOException parsing PkiPath data: " + e, e);
    }
}

From source file:cc.arduino.plugins.unowifi.certs.WiFi101Certificate.java

License:Open Source License

private static byte[] getSubjectValueHash(X509Certificate x509) throws NoSuchAlgorithmException, IOException {
    MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
    ASN1InputStream ais = new ASN1InputStream(x509.getSubjectX500Principal().getEncoded());
    while (ais.available() > 0) {
        ASN1Primitive obj = ais.readObject();
        sha1.update(extractPrintableString(obj));
    }/*from w  w  w  .  j  a v  a  2 s  . c o m*/
    ais.close();
    return sha1.digest();
}

From source file:cf.monteux.silvertunnel.netlib.layer.tor.util.Encryption.java

License:Open Source License

/**
 * makes RSA public key from bin byte array.
 *
 * @param b byte array that contains the key
 * @return/*w  w w.  j  av a2s  .  c o  m*/
 * @see JCERSAPublicKey
 */
public static RSAPublicKey extractBinaryRSAKey(final byte[] b) {
    RSAPublicKey theKey;

    try {
        final ASN1InputStream ais = new ASN1InputStream(b);
        final Object asnObject = ais.readObject();
        final ASN1Sequence sequence = (ASN1Sequence) asnObject;
        final RSAPublicKeyStructure tempKey = new RSAPublicKeyStructure(sequence);
        theKey = getRSAPublicKey(tempKey.getModulus(), tempKey.getPublicExponent());
        ais.close();
    } catch (final IOException e) {
        logger.warn("Caught exception:" + e.getMessage());
        theKey = null;
    }

    return theKey;
}

From source file:ch.bfh.unicert.certimport.CertificateIssuer.java

License:GNU General Public License

public Certificate createClientCertificate(IdentityData id, String keyStorePath, PublicKey pk, int validity,
        String applicationIdentifier, String[] roles, String uniBoardWsdlURL, String uniBoardServiceURL,
        String section) throws CertificateCreationException {

    X509Certificate caCert;/*from   ww w.j  a  v a 2  s  .  c o  m*/
    RSAPrivateCrtKey privKey;
    try {
        caCert = this.readIssuerCertificate(this.issuerId);
        privKey = this.readPrivateKey(this.issuerId, this.privKeyPass);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        logger.log(Level.SEVERE, null, ex);
        throw new CertificateCreationException("230 Could not create client certificate. Key error");
    }

    RSAPrivateCrtKeyParameters cipherParams = this.createIssuerCipherParams(privKey);

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(getExpiryDate(validity).getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | InvalidCipherTextException | CertificateException | NoSuchAlgorithmException
            | InvalidKeyException | NoSuchProviderException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    Certificate cert = new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(),
            id.getOrganisation(), id.getOrganisationUnit(), id.getCountryName(), id.getState(),
            id.getLocality(), id.getSurname(), id.getGivenName(), applicationIdentifier, roles,
            id.getIdentityProvider(), extensionMap);

    //post message on UniBoard if corresponding JNDI parameter is defined
    postOnUniBoard(cert, uniBoardWsdlURL, uniBoardServiceURL, section, (RSAPublicKey) caCert.getPublicKey(),
            privKey);

    return cert;

}

From source file:ch.bfh.unicert.issuer.CertificateIssuerBean.java

License:GNU General Public License

/**
 * Actually creates the requestor certificate.
 *
 * @param id requestor identity data/*from   w  w w  . j av a2s.  c  o  m*/
 * @param caCert certificate of the certification authority
 * @param cipherParams issuer private key parameters used for signing
 * @param pk public key of the requestor to certify
 * @param expiry the expiry date
 * @param applicationIdentifier the application identifier for which te certificate is issued
 * @param role role for which the certificate is issued
 * @return the certificate object containing the X509 certificate
 * @throws CertificateCreationException if an error occurs
 */
private Certificate createClientCertificate(IdentityData id, X509Certificate caCert,
        CipherParameters cipherParams, PublicKey pk, Calendar expiry, String applicationIdentifier,
        String[] roles) throws CertificateCreationException {

    X509Certificate clientCert;

    Hashtable extension = new Hashtable();

    extension.put(new DERObjectIdentifier(ExtensionOID.APPLICATION_IDENTIFIER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(applicationIdentifier)));

    String completeRole = "";
    for (String role : roles) {
        completeRole += role + ", ";
    }
    completeRole = completeRole.substring(0, completeRole.length() - 2);
    extension.put(new DERObjectIdentifier(ExtensionOID.ROLE.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(completeRole)));

    extension.put(new DERObjectIdentifier(ExtensionOID.IDENTITY_PROVIDER.getOID()),
            new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(id.getIdentityProvider())));

    Map<String, String> extensionMap = new HashMap();
    if (id.getOtherValues() != null) {
        for (Entry<ExtensionOID, String> entry : id.getOtherValues().entrySet()) {
            extension.put(new DERObjectIdentifier(entry.getKey().getOID()),
                    new X509Extension(DERBoolean.FALSE, CertificateHelper.stringToDER(entry.getValue())));
            extensionMap.put(entry.getKey().getName(), entry.getValue());
        }
    }

    try {

        String x509NameString = "";
        x509NameString += "CN=" + id.getCommonName();

        if (id.getSurname() != null && !id.getSurname().equals("")) {
            x509NameString += ", SURNAME=" + id.getSurname();
        }
        if (id.getGivenName() != null && !id.getGivenName().equals("")) {
            x509NameString += ", GIVENNAME=" + id.getGivenName();
        }
        if (id.getUniqueIdentifier() != null && !id.getUniqueIdentifier().equals("")) {
            x509NameString += ", UID=" + id.getUniqueIdentifier();
        }
        if (id.getOrganisation() != null && !id.getOrganisation().equals("")) {
            x509NameString += ", O=" + id.getOrganisation();
        }
        if (id.getOrganisationUnit() != null && !id.getOrganisationUnit().equals("")) {
            x509NameString += ", OU=" + id.getOrganisationUnit();
        }
        if (id.getCountryName() != null && !id.getCountryName().equals("")) {
            x509NameString += ", C=" + id.getCountryName();
        }
        if (id.getState() != null && !id.getState().equals("")) {
            x509NameString += ", ST=" + id.getState();
        }
        if (id.getLocality() != null && !id.getLocality().equals("")) {
            x509NameString += ", L=" + id.getLocality();
        }

        X509Name x509Name = new X509Name(x509NameString);

        V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();
        certGen.setSerialNumber(new DERInteger(BigInteger.valueOf(System.currentTimeMillis())));
        certGen.setIssuer(PrincipalUtil.getSubjectX509Principal(caCert));
        certGen.setSubject(x509Name);
        certGen.setExtensions(new X509Extensions(extension));
        DERObjectIdentifier sigOID = new DERObjectIdentifier("1.2.840.113549.1.1.5");
        AlgorithmIdentifier sigAlgId = new AlgorithmIdentifier(sigOID, new DERNull());
        certGen.setSignature(sigAlgId);
        certGen.setSubjectPublicKeyInfo(new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(new ByteArrayInputStream(pk.getEncoded())).readObject()));
        certGen.setStartDate(new Time(new Date(System.currentTimeMillis())));
        certGen.setEndDate(new Time(expiry.getTime()));
        TBSCertificateStructure tbsCert = certGen.generateTBSCertificate();

        //Sign certificate
        SHA1Digest digester = new SHA1Digest();
        AsymmetricBlockCipher rsa = new PKCS1Encoding(new RSAEngine());
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        DEROutputStream dOut = new DEROutputStream(bOut);
        dOut.writeObject(tbsCert);
        byte[] signature;
        byte[] certBlock = bOut.toByteArray();
        // first create digest
        digester.update(certBlock, 0, certBlock.length);
        byte[] hash = new byte[digester.getDigestSize()];
        digester.doFinal(hash, 0);
        // then sign it
        rsa.init(true, cipherParams);
        DigestInfo dInfo = new DigestInfo(new AlgorithmIdentifier(X509ObjectIdentifiers.id_SHA1, null), hash);
        byte[] digest = dInfo.getEncoded(ASN1Encodable.DER);
        signature = rsa.processBlock(digest, 0, digest.length);

        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(tbsCert);
        v.add(sigAlgId);
        v.add(new DERBitString(signature));

        // Create CRT data structure
        clientCert = new X509CertificateObject(new X509CertificateStructure(new DERSequence(v)));
        clientCert.verify(caCert.getPublicKey());
    } catch (IOException | CertificateException | NoSuchAlgorithmException | InvalidKeyException
            | NoSuchProviderException | InvalidCipherTextException | SignatureException e) {
        logger.log(Level.SEVERE, "Could not create client certificate: {0}", new Object[] { e.getMessage() });
        throw new CertificateCreationException("230 Could not create client certificate");
    }

    return new Certificate(clientCert, id.getCommonName(), id.getUniqueIdentifier(), id.getOrganisation(),
            id.getOrganisationUnit(), id.getCountryName(), id.getState(), id.getLocality(), id.getSurname(),
            id.getGivenName(), applicationIdentifier, roles, id.getIdentityProvider(), extensionMap);

}

From source file:cljpdf.text.pdf.PdfPublicKeySecurityHandler.java

License:Mozilla Public License

private DERObject createDERForRecipient(byte[] in, X509Certificate cert)
        throws IOException, GeneralSecurityException {

    String s = "1.2.840.113549.3.2";

    AlgorithmParameterGenerator algorithmparametergenerator = AlgorithmParameterGenerator.getInstance(s);
    AlgorithmParameters algorithmparameters = algorithmparametergenerator.generateParameters();
    ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(
            algorithmparameters.getEncoded("ASN.1"));
    ASN1InputStream asn1inputstream = new ASN1InputStream(bytearrayinputstream);
    DERObject derobject = asn1inputstream.readObject();
    KeyGenerator keygenerator = KeyGenerator.getInstance(s);
    keygenerator.init(128);/*w  w w . ja  v  a  2 s .  c om*/
    SecretKey secretkey = keygenerator.generateKey();
    Cipher cipher = Cipher.getInstance(s);
    cipher.init(1, secretkey, algorithmparameters);
    byte[] abyte1 = cipher.doFinal(in);
    DEROctetString deroctetstring = new DEROctetString(abyte1);
    KeyTransRecipientInfo keytransrecipientinfo = computeRecipientInfo(cert, secretkey.getEncoded());
    DERSet derset = new DERSet(new RecipientInfo(keytransrecipientinfo));
    AlgorithmIdentifier algorithmidentifier = new AlgorithmIdentifier(new DERObjectIdentifier(s), derobject);
    EncryptedContentInfo encryptedcontentinfo = new EncryptedContentInfo(PKCSObjectIdentifiers.data,
            algorithmidentifier, deroctetstring);
    EnvelopedData env = new EnvelopedData(null, derset, encryptedcontentinfo, null);
    ContentInfo contentinfo = new ContentInfo(PKCSObjectIdentifiers.envelopedData, env);
    return contentinfo.getDERObject();
}