Example usage for org.bouncycastle.asn1 ASN1InputStream readObject

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

Introduction

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

Prototype

public ASN1Primitive readObject() throws IOException 

Source Link

Usage

From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source License

/**
 * Use this constructor if you want to verify a signature.
 * @param contentsKey the /Contents key// w  ww .ja  v a  2  s .  com
 * @param filterSubtype the filtersubtype
 * @param provider the provider or <code>null</code> for the default provider
 */
@SuppressWarnings({ "unchecked" })
public PdfPKCS7(byte[] contentsKey, PdfName filterSubtype, String provider) {
    this.filterSubtype = filterSubtype;
    isTsp = PdfName.ETSI_RFC3161.equals(filterSubtype);
    isCades = PdfName.ETSI_CADES_DETACHED.equals(filterSubtype);
    try {
        this.provider = provider;
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(contentsKey));

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

        try {
            pkcs = din.readObject();
        } catch (IOException e) {
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("can.t.decode.pkcs7signeddata.object"));
        }
        if (!(pkcs instanceof ASN1Sequence)) {
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.a.sequence"));
        }
        ASN1Sequence signedData = (ASN1Sequence) pkcs;
        ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0);
        if (!objId.getId().equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
        ASN1Sequence content = (ASN1Sequence) ((ASN1TaggedObject) signedData.getObjectAt(1)).getObject();
        // the positions that we care are:
        //     0 - version
        //     1 - digestAlgorithms
        //     2 - possible ID_PKCS7_DATA
        //     (the certificates and crls are taken out by other means)
        //     last - signerInfos

        // the version
        version = ((ASN1Integer) content.getObjectAt(0)).getValue().intValue();

        // the digestAlgorithms
        digestalgos = new HashSet<String>();
        Enumeration<ASN1Sequence> e = ((ASN1Set) content.getObjectAt(1)).getObjects();
        while (e.hasMoreElements()) {
            ASN1Sequence s = e.nextElement();
            ASN1ObjectIdentifier o = (ASN1ObjectIdentifier) s.getObjectAt(0);
            digestalgos.add(o.getId());
        }

        // the possible ID_PKCS7_DATA
        ASN1Sequence rsaData = (ASN1Sequence) content.getObjectAt(2);
        if (rsaData.size() > 1) {
            ASN1OctetString rsaDataContent = (ASN1OctetString) ((ASN1TaggedObject) rsaData.getObjectAt(1))
                    .getObject();
            RSAdata = rsaDataContent.getOctets();
        }

        int next = 3;
        while (content.getObjectAt(next) instanceof ASN1TaggedObject)
            ++next;

        // the certificates
        /*
                 This should work, but that's not always the case because of a bug in BouncyCastle:
        */
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(contentsKey));
        certs = cr.engineReadAll();
        /*    
                    The following workaround was provided by Alfonso Massa, but it doesn't always work either.
                
                    ASN1Set certSet = null;
                    ASN1Set crlSet = null;
                    while (content.getObjectAt(next) instanceof ASN1TaggedObject) {
        ASN1TaggedObject tagged = (ASN1TaggedObject)content.getObjectAt(next);
                
        switch (tagged.getTagNo()) {
        case 0:
            certSet = ASN1Set.getInstance(tagged, false);
            break;
        case 1:
            crlSet = ASN1Set.getInstance(tagged, false);
            break;
        default:
            throw new IllegalArgumentException("unknown tag value " + tagged.getTagNo());
        }
        ++next;
                    }
                    certs = new ArrayList<Certificate>(certSet.size());
                
                    CertificateFactory certFact = CertificateFactory.getInstance("X.509", new BouncyCastleProvider());
                    for (Enumeration en = certSet.getObjects(); en.hasMoreElements();) {
        ASN1Primitive obj = ((ASN1Encodable)en.nextElement()).toASN1Primitive();
        if (obj instanceof ASN1Sequence) {
           ByteArrayInputStream stream = new ByteArrayInputStream(obj.getEncoded());
           X509Certificate x509Certificate = (X509Certificate)certFact.generateCertificate(stream);
           stream.close();
        certs.add(x509Certificate);
        }
                    }
        */
        // the signerInfos
        ASN1Set signerInfos = (ASN1Set) content.getObjectAt(next);
        if (signerInfos.size() != 1)
            throw new IllegalArgumentException(MessageLocalization.getComposedMessage(
                    "this.pkcs.7.object.has.multiple.signerinfos.only.one.is.supported.at.this.time"));
        ASN1Sequence signerInfo = (ASN1Sequence) signerInfos.getObjectAt(0);
        // the positions that we care are
        //     0 - version
        //     1 - the signing certificate issuer and serial number
        //     2 - the digest algorithm
        //     3 or 4 - digestEncryptionAlgorithm
        //     4 or 5 - encryptedDigest
        signerversion = ((ASN1Integer) signerInfo.getObjectAt(0)).getValue().intValue();
        // Get the signing certificate
        ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1);
        X509Principal issuer = new X509Principal(
                issuerAndSerialNumber.getObjectAt(0).toASN1Primitive().getEncoded());
        BigInteger serialNumber = ((ASN1Integer) issuerAndSerialNumber.getObjectAt(1)).getValue();
        for (Object element : certs) {
            X509Certificate cert = (X509Certificate) element;
            if (cert.getIssuerDN().equals(issuer) && serialNumber.equals(cert.getSerialNumber())) {
                signCert = cert;
                break;
            }
        }
        if (signCert == null) {
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("can.t.find.signing.certificate.with.serial.1",
                            issuer.getName() + " / " + serialNumber.toString(16)));
        }
        signCertificateChain();
        digestAlgorithmOid = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0))
                .getId();
        next = 3;
        boolean foundCades = false;
        if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) {
            ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next);
            ASN1Set sseq = ASN1Set.getInstance(tagsig, false);
            sigAttr = sseq.getEncoded();
            // maybe not necessary, but we use the following line as fallback:
            sigAttrDer = sseq.getEncoded(ASN1Encoding.DER);

            for (int k = 0; k < sseq.size(); ++k) {
                ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k);
                String idSeq2 = ((ASN1ObjectIdentifier) seq2.getObjectAt(0)).getId();
                if (idSeq2.equals(SecurityIDs.ID_MESSAGE_DIGEST)) {
                    ASN1Set set = (ASN1Set) seq2.getObjectAt(1);
                    digestAttr = ((ASN1OctetString) set.getObjectAt(0)).getOctets();
                } else if (idSeq2.equals(SecurityIDs.ID_ADBE_REVOCATION)) {
                    ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
                    ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
                    for (int j = 0; j < seqout.size(); ++j) {
                        ASN1TaggedObject tg = (ASN1TaggedObject) seqout.getObjectAt(j);
                        if (tg.getTagNo() == 0) {
                            ASN1Sequence seqin = (ASN1Sequence) tg.getObject();
                            findCRL(seqin);
                        }
                        if (tg.getTagNo() == 1) {
                            ASN1Sequence seqin = (ASN1Sequence) tg.getObject();
                            findOcsp(seqin);
                        }
                    }
                } else if (isCades && idSeq2.equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V1)) {
                    ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
                    ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
                    SigningCertificate sv2 = SigningCertificate.getInstance(seqout);
                    ESSCertID[] cerv2m = sv2.getCerts();
                    ESSCertID cerv2 = cerv2m[0];
                    byte[] enc2 = signCert.getEncoded();
                    MessageDigest m2 = new BouncyCastleDigest().getMessageDigest("SHA-1");
                    byte[] signCertHash = m2.digest(enc2);
                    byte[] hs2 = cerv2.getCertHash();
                    if (!Arrays.equals(signCertHash, hs2))
                        throw new IllegalArgumentException(
                                "Signing certificate doesn't match the ESS information.");
                    foundCades = true;
                } else if (isCades && idSeq2.equals(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2)) {
                    ASN1Set setout = (ASN1Set) seq2.getObjectAt(1);
                    ASN1Sequence seqout = (ASN1Sequence) setout.getObjectAt(0);
                    SigningCertificateV2 sv2 = SigningCertificateV2.getInstance(seqout);
                    ESSCertIDv2[] cerv2m = sv2.getCerts();
                    ESSCertIDv2 cerv2 = cerv2m[0];
                    AlgorithmIdentifier ai2 = cerv2.getHashAlgorithm();
                    byte[] enc2 = signCert.getEncoded();
                    MessageDigest m2 = new BouncyCastleDigest()
                            .getMessageDigest(DigestAlgorithms.getDigest(ai2.getAlgorithm().getId()));
                    byte[] signCertHash = m2.digest(enc2);
                    byte[] hs2 = cerv2.getCertHash();
                    if (!Arrays.equals(signCertHash, hs2))
                        throw new IllegalArgumentException(
                                "Signing certificate doesn't match the ESS information.");
                    foundCades = true;
                }
            }
            if (digestAttr == null)
                throw new IllegalArgumentException(MessageLocalization
                        .getComposedMessage("authenticated.attribute.is.missing.the.digest"));
            ++next;
        }
        if (isCades && !foundCades)
            throw new IllegalArgumentException("CAdES ESS information missing.");
        digestEncryptionAlgorithmOid = ((ASN1ObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++))
                .getObjectAt(0)).getId();
        digest = ((ASN1OctetString) signerInfo.getObjectAt(next++)).getOctets();
        if (next < signerInfo.size() && signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) {
            ASN1TaggedObject taggedObject = (ASN1TaggedObject) signerInfo.getObjectAt(next);
            ASN1Set unat = ASN1Set.getInstance(taggedObject, false);
            AttributeTable attble = new AttributeTable(unat);
            Attribute ts = attble.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
            if (ts != null && ts.getAttrValues().size() > 0) {
                ASN1Set attributeValues = ts.getAttrValues();
                ASN1Sequence tokenSequence = ASN1Sequence.getInstance(attributeValues.getObjectAt(0));
                ContentInfo contentInfo = new ContentInfo(tokenSequence);
                this.timeStampToken = new TimeStampToken(contentInfo);
            }
        }
        if (isTsp) {
            ContentInfo contentInfoTsp = new ContentInfo(signedData);
            this.timeStampToken = new TimeStampToken(contentInfoTsp);
            TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
            String algOID = info.getMessageImprintAlgOID().getId();
            messageDigest = DigestAlgorithms.getMessageDigestFromOid(algOID, null);
        } else {
            if (RSAdata != null || digestAttr != null) {
                if (PdfName.ADBE_PKCS7_SHA1.equals(getFilterSubtype())) {
                    messageDigest = DigestAlgorithms.getMessageDigest("SHA1", provider);
                } else {
                    messageDigest = DigestAlgorithms.getMessageDigest(getHashAlgorithm(), provider);
                }
                encContDigest = DigestAlgorithms.getMessageDigest(getHashAlgorithm(), provider);
            }
            sig = initSignature(signCert.getPublicKey());
        }
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source License

/**
 * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
 * in the signerInfo can also be set, OR a time-stamp-authority client
 * may be provided.//from ww  w  .  j  a v  a 2s.c  om
 * @param secondDigest the digest in the authenticatedAttributes
 * @param signingTime the signing time in the authenticatedAttributes
 * @param tsaClient TSAClient - null or an optional time stamp authority client
 * @return byte[] the bytes for the PKCS7SignedData object
 * @since   2.1.6
 */
public byte[] getEncodedPKCS7(byte secondDigest[], Calendar signingTime, TSAClient tsaClient, byte[] ocsp,
        Collection<byte[]> crlBytes, CryptoStandard sigtype) {
    try {
        if (externalDigest != null) {
            digest = externalDigest;
            if (RSAdata != null)
                RSAdata = externalRSAdata;
        } else if (externalRSAdata != null && RSAdata != null) {
            RSAdata = externalRSAdata;
            sig.update(RSAdata);
            digest = sig.sign();
        } else {
            if (RSAdata != null) {
                RSAdata = messageDigest.digest();
                sig.update(RSAdata);
            }
            digest = sig.sign();
        }

        // Create the set of Hash algorithms
        ASN1EncodableVector digestAlgorithms = new ASN1EncodableVector();
        for (Object element : digestalgos) {
            ASN1EncodableVector algos = new ASN1EncodableVector();
            algos.add(new ASN1ObjectIdentifier((String) element));
            algos.add(DERNull.INSTANCE);
            digestAlgorithms.add(new DERSequence(algos));
        }

        // Create the contentInfo.
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA));
        if (RSAdata != null)
            v.add(new DERTaggedObject(0, new DEROctetString(RSAdata)));
        DERSequence contentinfo = new DERSequence(v);

        // Get all the certificates
        //
        v = new ASN1EncodableVector();
        for (Object element : certs) {
            ASN1InputStream tempstream = new ASN1InputStream(
                    new ByteArrayInputStream(((X509Certificate) element).getEncoded()));
            v.add(tempstream.readObject());
        }

        DERSet dercertificates = new DERSet(v);

        // Create signerinfo structure.
        //
        ASN1EncodableVector signerinfo = new ASN1EncodableVector();

        // Add the signerInfo version
        //
        signerinfo.add(new ASN1Integer(signerversion));

        v = new ASN1EncodableVector();
        v.add(CertificateInfo.getIssuer(signCert.getTBSCertificate()));
        v.add(new ASN1Integer(signCert.getSerialNumber()));
        signerinfo.add(new DERSequence(v));

        // Add the digestAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestAlgorithmOid));
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // add the authenticated attribute if present
        if (secondDigest != null && signingTime != null) {
            signerinfo.add(new DERTaggedObject(false, 0,
                    getAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, sigtype)));
        }
        // Add the digestEncryptionAlgorithm
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(digestEncryptionAlgorithmOid));
        v.add(new DERNull());
        signerinfo.add(new DERSequence(v));

        // Add the digest
        signerinfo.add(new DEROctetString(digest));

        // When requested, go get and add the timestamp. May throw an exception.
        // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
        // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
        if (tsaClient != null) {
            byte[] tsImprint = tsaClient.getMessageDigest().digest(digest);
            byte[] tsToken = tsaClient.getTimeStampToken(tsImprint);
            if (tsToken != null) {
                ASN1EncodableVector unauthAttributes = buildUnauthenticatedAttributes(tsToken);
                if (unauthAttributes != null) {
                    signerinfo.add(new DERTaggedObject(false, 1, new DERSet(unauthAttributes)));
                }
            }
        }

        // Finally build the body out of all the components above
        ASN1EncodableVector body = new ASN1EncodableVector();
        body.add(new ASN1Integer(version));
        body.add(new DERSet(digestAlgorithms));
        body.add(contentinfo);
        body.add(new DERTaggedObject(false, 0, dercertificates));

        // Only allow one signerInfo
        body.add(new DERSet(new DERSequence(signerinfo)));

        // Now we have the body, wrap it in it's PKCS7Signed shell
        // and return it
        //
        ASN1EncodableVector whole = new ASN1EncodableVector();
        whole.add(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA));
        whole.add(new DERTaggedObject(0, new DERSequence(body)));

        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        ASN1OutputStream dout = new ASN1OutputStream(bOut);
        dout.writeObject(new DERSequence(whole));
        dout.close();

        return bOut.toByteArray();
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source License

/**
 * This method provides that encoding and the parameters must be
 * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}.
 * //from   w  ww  .j  a  va2  s.  c om
 * @param secondDigest the content digest
 * @param signingTime the signing time
 * @return the byte array representation of the authenticatedAttributes ready to be signed
 */
private DERSet getAuthenticatedAttributeSet(byte secondDigest[], Calendar signingTime, byte[] ocsp,
        Collection<byte[]> crlBytes, CryptoStandard sigtype) {
    try {
        ASN1EncodableVector attribute = new ASN1EncodableVector();
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE));
        v.add(new DERSet(new ASN1ObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_SIGNING_TIME));
        v.add(new DERSet(new DERUTCTime(signingTime.getTime())));
        attribute.add(new DERSequence(v));
        v = new ASN1EncodableVector();
        v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST));
        v.add(new DERSet(new DEROctetString(secondDigest)));
        attribute.add(new DERSequence(v));
        boolean haveCrl = false;
        if (crlBytes != null) {
            for (byte[] bCrl : crlBytes) {
                if (bCrl != null) {
                    haveCrl = true;
                    break;
                }
            }
        }
        if (ocsp != null || haveCrl) {
            v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION));

            ASN1EncodableVector revocationV = new ASN1EncodableVector();

            if (haveCrl) {
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                for (byte[] bCrl : crlBytes) {
                    if (bCrl == null)
                        continue;
                    ASN1InputStream t = new ASN1InputStream(new ByteArrayInputStream(bCrl));
                    v2.add(t.readObject());
                }
                revocationV.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
            }

            if (ocsp != null) {
                DEROctetString doctet = new DEROctetString(ocsp);
                ASN1EncodableVector vo1 = new ASN1EncodableVector();
                ASN1EncodableVector v2 = new ASN1EncodableVector();
                v2.add(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
                v2.add(doctet);
                ASN1Enumerated den = new ASN1Enumerated(0);
                ASN1EncodableVector v3 = new ASN1EncodableVector();
                v3.add(den);
                v3.add(new DERTaggedObject(true, 0, new DERSequence(v2)));
                vo1.add(new DERSequence(v3));
                revocationV.add(new DERTaggedObject(true, 1, new DERSequence(vo1)));
            }

            v.add(new DERSet(new DERSequence(revocationV)));
            attribute.add(new DERSequence(v));
        }
        if (sigtype == CryptoStandard.CADES) {
            v = new ASN1EncodableVector();
            v.add(new ASN1ObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2));

            ASN1EncodableVector aaV2 = new ASN1EncodableVector();
            AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(digestAlgorithmOid),
                    null);
            aaV2.add(algoId);
            MessageDigest md = interfaceDigest.getMessageDigest(getHashAlgorithm());
            byte[] dig = md.digest(signCert.getEncoded());
            aaV2.add(new DEROctetString(dig));

            v.add(new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2)))));
            attribute.add(new DERSequence(v));
        }

        return new DERSet(attribute);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.itextpdf.text.pdf.security.PdfPKCS7.java

License:Open Source License

/**
 * Helper method that creates the BasicOCSPResp object.
 * @param seq/*from  ww  w .ja  va2s.  c o m*/
 * @throws IOException
 */
private void findOcsp(ASN1Sequence seq) throws IOException {
    basicResp = null;
    boolean ret = false;
    while (true) {
        if (seq.getObjectAt(0) instanceof ASN1ObjectIdentifier && ((ASN1ObjectIdentifier) seq.getObjectAt(0))
                .getId().equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic.getId())) {
            break;
        }
        ret = true;
        for (int k = 0; k < seq.size(); ++k) {
            if (seq.getObjectAt(k) instanceof ASN1Sequence) {
                seq = (ASN1Sequence) seq.getObjectAt(0);
                ret = false;
                break;
            }
            if (seq.getObjectAt(k) instanceof ASN1TaggedObject) {
                ASN1TaggedObject tag = (ASN1TaggedObject) seq.getObjectAt(k);
                if (tag.getObject() instanceof ASN1Sequence) {
                    seq = (ASN1Sequence) tag.getObject();
                    ret = false;
                    break;
                } else
                    return;
            }
        }
        if (ret)
            return;
    }
    ASN1OctetString os = (ASN1OctetString) seq.getObjectAt(1);
    ASN1InputStream inp = new ASN1InputStream(os.getOctets());
    BasicOCSPResponse resp = BasicOCSPResponse.getInstance(inp.readObject());
    basicResp = new BasicOCSPResp(resp);
}

From source file:com.jlocksmith.util.ExtensionUtil.java

License:Open Source License

/**
 * Gets a DER object from the given byte array.
 * /*ww w . ja va 2 s.  c  o m*/
 * @param bytes bytes
 * 
 * @return DERObject
 * 
 * @throws IOException if a conversion error occurs
 */
private static DERObject toDERObject(byte[] bytes) throws IOException {
    ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(bytes));

    try {
        return in.readObject();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.motorolamobility.studio.android.certmanager.core.KeyStoreUtils.java

License:Apache License

/**
 * Create a new X509 certificate for a given KeyPair
 * @param keyPair the {@link KeyPair} used to create the certificate,
 *     RSAPublicKey and RSAPrivateKey are mandatory on keyPair, IllegalArgumentExeption will be thrown otherwise.
 * @param issuerName The issuer name to be used on the certificate
 * @param ownerName  The owner name to be used on the certificate
 * @param expireDate The expire date/*ww w  .  j  a v  a 2s. co m*/
 * @return The {@link X509Certificate}
 * @throws IOException
 * @throws OperatorCreationException
 * @throws CertificateException
 */
public static X509Certificate createX509Certificate(KeyPair keyPair, CertificateDetailsInfo certDetails)
        throws IOException, OperatorCreationException, CertificateException {

    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();
    if (!(publicKey instanceof RSAPublicKey) || !(privateKey instanceof RSAPrivateKey)) {
        throw new IllegalArgumentException(CertificateManagerNLS.KeyStoreUtils_RSA_Keys_Expected);
    }

    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;

    //Transform the PublicKey into the BouncyCastle expected format
    ASN1InputStream asn1InputStream = null;
    X509Certificate x509Certificate = null;

    try {
        asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(rsaPublicKey.getEncoded()));
        SubjectPublicKeyInfo pubKey = new SubjectPublicKeyInfo((ASN1Sequence) asn1InputStream.readObject());

        X500NameBuilder nameBuilder = new X500NameBuilder(new BCStrictStyle());
        addField(BCStyle.C, certDetails.getCountry(), nameBuilder);
        addField(BCStyle.ST, certDetails.getState(), nameBuilder);
        addField(BCStyle.L, certDetails.getLocality(), nameBuilder);
        addField(BCStyle.O, certDetails.getOrganization(), nameBuilder);
        addField(BCStyle.OU, certDetails.getOrganizationUnit(), nameBuilder);
        addField(BCStyle.CN, certDetails.getCommonName(), nameBuilder);

        X500Name subjectName = nameBuilder.build();
        X500Name issuerName = subjectName;
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuerName,
                BigInteger.valueOf(new SecureRandom().nextInt()), GregorianCalendar.getInstance().getTime(),
                certDetails.getExpirationDate(), subjectName, pubKey);

        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA"); //$NON-NLS-1$
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
        BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);

        //Create RSAKeyParameters, the private key format expected by Bouncy Castle
        RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(),
                rsaPrivateKey.getModulus());

        ContentSigner contentSigner = sigGen.build(keyParams);
        X509CertificateHolder certificateHolder = certBuilder.build(contentSigner);

        //Convert the X509Certificate from BouncyCastle format to the java.security format
        JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter();
        x509Certificate = certConverter.getCertificate(certificateHolder);
    } finally {
        if (asn1InputStream != null) {
            try {
                asn1InputStream.close();
            } catch (IOException e) {
                StudioLogger.error("Could not close stream while creating X509 certificate. " + e.getMessage());
            }
        }
    }

    return x509Certificate;
}

From source file:com.oneis.common.utils.SSLCertificates.java

License:Mozilla Public License

private static PrivateKey readPEMPrivateKey(String filename)
        throws java.io.IOException, java.security.GeneralSecurityException {
    ByteArrayInputStream bIn = readPEM(filename);
    ASN1InputStream aIn = new ASN1InputStream(bIn);
    ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
    if (!(seq.getObjectAt(1) instanceof DERInteger)) {
        throw new RuntimeException("Can't read RSA private key from " + filename
                + " - if file starts '-----BEGIN PRIVATE KEY-----' then it needs converting to RSA format with 'openssl rsa -in server-in.key -out server.key'.");
    }/*www.j  a v a2  s . c  o m*/
    DERInteger mod = (DERInteger) seq.getObjectAt(1);
    DERInteger pubExp = (DERInteger) seq.getObjectAt(2);
    DERInteger privExp = (DERInteger) seq.getObjectAt(3);
    DERInteger p1 = (DERInteger) seq.getObjectAt(4);
    DERInteger p2 = (DERInteger) seq.getObjectAt(5);
    DERInteger exp1 = (DERInteger) seq.getObjectAt(6);
    DERInteger exp2 = (DERInteger) seq.getObjectAt(7);
    DERInteger crtCoef = (DERInteger) seq.getObjectAt(8);

    RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(mod.getValue(), pubExp.getValue(),
            privExp.getValue(), p1.getValue(), p2.getValue(), exp1.getValue(), exp2.getValue(),
            crtCoef.getValue());

    KeyFactory factory = KeyFactory.getInstance("RSA");
    return factory.generatePrivate(privSpec);
}

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

License:Mozilla Public License

/**
 * Verifies a signature using the sub-filter adbe.x509.rsa_sha1.
 * @param contentsKey the /Contents key//from   w  ww.  ja  v a  2 s .co  m
 * @param certsKey the /Cert key
 * @param provider the provider or <code>null</code> for the default provider
 */
public PDFEnvelopedSignature(byte[] contentsKey, byte[] certsKey, String provider, AcroFields acroFields,
        String signatureFieldName) {
    try {
        log.debug(Channel.TECH, "Verifying a adbe.x509.rsa_sha1 signature");
        this.acroFields = acroFields;
        this.signatureFieldName = signatureFieldName;
        this.subFilter = SF_ADBE_X509_RSA_SHA1;
        this.dictionaryCert = certsKey;
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(certsKey));
        certs = cr.engineReadAll();
        signCert = (X509Certificate) certs.iterator().next();
        crls = new ArrayList();
        ASN1InputStream in = new ASN1InputStream(new ByteArrayInputStream(contentsKey));
        pkcs1SigValue = ((DEROctetString) in.readObject()).getOctets();

        Cipher c = Cipher.getInstance("RSA/NONE/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
        c.init(Cipher.DECRYPT_MODE, signCert);
        byte[] raw = c.doFinal(pkcs1SigValue);
        ASN1Sequence in3 = (ASN1Sequence) ASN1Object.fromByteArray(raw);
        DigestInfo di = DigestInfo.getInstance(in3);
        dataDigestAlgorithm = di.getAlgorithmId().getAlgorithm().getId();
        keyAndParameterAlgorithm = ID_RSA;

        if (provider == null)
            sig = Signature.getInstance(getSignatureAlgorithm());
        else
            sig = Signature.getInstance(getSignatureAlgorithm(), provider);
        sig.initVerify(signCert.getPublicKey());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:com.orange.atk.sign.apk.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);//w w w .jav a  2  s . c om
    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.peterphi.std.crypto.keygen.CaHelper.java

License:Open Source License

public static PKCS10CertificationRequest generateCertificateRequest(X509Certificate cert, PrivateKey signingKey)
        throws Exception {
    ASN1EncodableVector attributes = new ASN1EncodableVector();

    Set<String> nonCriticalExtensionOIDs = cert.getNonCriticalExtensionOIDs();
    for (String nceoid : nonCriticalExtensionOIDs) {
        byte[] derBytes = cert.getExtensionValue(nceoid);
        ByteArrayInputStream bis = new ByteArrayInputStream(derBytes);
        ASN1InputStream dis = new ASN1InputStream(bis);
        try {/*from ww w.  ja v a2 s.  c o  m*/
            DERObject derObject = dis.readObject();
            DERSet value = new DERSet(derObject);
            Attribute attr = new Attribute(new DERObjectIdentifier(nceoid), value);
            attributes.add(attr);
        } finally {
            IOUtils.closeQuietly(dis);
        }
    }
    PKCS10CertificationRequest certificationRequest = new PKCS10CertificationRequest(getSignatureAlgorithm(),
            cert.getSubjectX500Principal(), cert.getPublicKey(), new DERSet(attributes), signingKey);
    return certificationRequest;
}