Example usage for org.bouncycastle.asn1 ASN1Sequence getInstance

List of usage examples for org.bouncycastle.asn1 ASN1Sequence getInstance

Introduction

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

Prototype

public static ASN1Sequence getInstance(Object obj) 

Source Link

Document

Return an ASN1Sequence from the given object.

Usage

From source file:at.asitplus.regkassen.common.util.CryptoUtil.java

License:Apache License

/**
 * Helper method to convert DER-encoded signature values (e.g. used by Java)
 * to concatenated signature values/*ww  w  .jav  a  2 s  . c o  m*/
 * (as used by the JWS-standard)
 *
 * @param derEncodedSignatureValue
 *          DER-encoded signature value
 * @return concatenated signature value (as used by JWS standard)
 * @throws IOException
 */
public static byte[] convertDEREncodedSignatureToJWSConcatenated(final byte[] derEncodedSignatureValue)
        throws IOException {
    final ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    final ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    asn1InputStream.close();
    final ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    final ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    final ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    final X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    final byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), 32);
    final byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), 32);

    final byte[] concatenatedSignatureValue = new byte[64];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, 32);
    System.arraycopy(s, 0, concatenatedSignatureValue, 32, 32);

    return concatenatedSignatureValue;
}

From source file:at.asitplus.regkassen.core.base.util.CryptoUtil.java

License:Apache License

/**
 * Helper method to convert DER-encoded signature values (e.g. used by Java) to concatenated signature values
 * (as used by the JWS-standard)// w  ww.  j a  v a2 s  .c om
 *
 * @param derEncodedSignatureValue DER-encoded signature value
 * @return concatenated signature value (as used by JWS standard)
 * @throws IOException
 */
public static byte[] convertDEREncodedSignatureToJWSConcatenated(byte[] derEncodedSignatureValue)
        throws IOException {
    ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), 32);
    byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), 32);

    byte[] concatenatedSignatureValue = new byte[64];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, 32);
    System.arraycopy(s, 0, concatenatedSignatureValue, 32, 32);

    return concatenatedSignatureValue;
}

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

License:Apache License

/**
 * Converts this instance to its string representation using the given indentation level.
 *
 * @param depth Indentation level.//  w w  w.ja  v a2  s  . c o  m
 * @return String representation of this instance at the given indentation level.
 */
public String toString(int depth) {
    StringBuffer buffer = new StringBuffer();

    final String LINE_SEPARATOR = System.getProperty("line.separator");

    FormattingUtils.indent(buffer, depth).append("M2MCertificate [APPLICATION 20] SEQUENCE {")
            .append(LINE_SEPARATOR);
    FormattingUtils.indent(buffer, depth + 1).append("[0] tbsCertificate TBSCertificate: ")
            .append(LINE_SEPARATOR);

    FormattingUtils.indent(buffer, depth + 2).append("TBSCertificate SEQUENCE {").append(LINE_SEPARATOR);
    FormattingUtils.indent(buffer, depth + 3).append("[ 0] version INTEGER:               ");
    buffer.append(VERSION).append(LINE_SEPARATOR);

    if (serialNumber != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 1] serialNumber OCTET STRING:     ");
        buffer.append(Hex.toHexString(serialNumber)).append(LINE_SEPARATOR);
    }

    if (caKeyDefinition != null) {
        if (caKeyDefinition.getAlgorithm() != null) {
            FormattingUtils.indent(buffer, depth + 3).append("[ 2] cAAlgorithm OBJECT IDENTIFIER: ");
            buffer.append(caKeyDefinition.getAlgorithm().getOid()).append(LINE_SEPARATOR);
        }

        if (caKeyDefinition.getParameters() != null) {
            FormattingUtils.indent(buffer, depth + 3).append("[ 3] cAAlgParams OCTET STRING:      ");
            buffer.append(Hex.toHexString(caKeyDefinition.getParameters())).append(LINE_SEPARATOR);
        }
    }

    if (issuer != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 4] issuer Name: ").append(LINE_SEPARATOR);
        buffer.append(issuer.toString(depth + 4));
    }

    if (validFrom != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 5] validFrom OCTET STRING: ");
        buffer.append(Hex.toHexString(BigInteger.valueOf(validFrom.getTime() / 1000).toByteArray()))
                .append(LINE_SEPARATOR);
    }

    if (validDuration != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 6] validDuration OCTET STRING: ");
        buffer.append(validDuration).append(LINE_SEPARATOR);
    }

    if (subject != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[ 7] subject Name: ").append(LINE_SEPARATOR);
        buffer.append(subject.toString(depth + 4));
    }

    if (publicKeyDefinition != null) {
        if (publicKeyDefinition.getAlgorithm() != null) {
            FormattingUtils.indent(buffer, depth + 3).append("[ 8] pKAlgorithm OBJECT IDENTIFIER: ");
            buffer.append(publicKeyDefinition.getAlgorithm()).append(LINE_SEPARATOR);
        }

        if (publicKeyDefinition.getParameters() != null) {
            FormattingUtils.indent(buffer, depth + 3).append("[ 9] pKAlgParams OCTET STRING: ");
            buffer.append(Hex.toHexString(publicKeyDefinition.getParameters())).append(LINE_SEPARATOR);
        }
    }

    if (publicKey != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[10] pubKey OCTET STRING: ");
        buffer.append(Hex.toHexString(publicKey.getEncoded())).append(LINE_SEPARATOR);
    }

    if (authorityKeyIdentifier != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[11] authKeyId OCTET STRING: ")
                .append(LINE_SEPARATOR);
        buffer.append(authorityKeyIdentifier.toString(depth + 4)).append(LINE_SEPARATOR);
    }

    if (subjectKeyIdentifier != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[12] subjKeyId OCTET STRING: ");
        buffer.append(Hex.toHexString(subjectKeyIdentifier)).append(LINE_SEPARATOR);
    }

    if (keyUsage != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[13] keyUsage OCTET STRING: ");
        buffer.append(keyUsage.toString(depth + 4)).append(LINE_SEPARATOR);
    }

    if (basicConstraints != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[14] basicConstraints INTEGER: ");
        buffer.append(basicConstraints).append(LINE_SEPARATOR);
    }

    if (certificatePolicy != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[15] certificatePolicy OBJECT IDENTIFIER: ");
        buffer.append(certificatePolicy).append(LINE_SEPARATOR);
    }

    if (subjectAlternativeName != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[16] subjectAltName GeneralName: ");
        buffer.append(subjectAlternativeName.toString(depth + 4)).append(LINE_SEPARATOR);
    }

    if (issuerAlternativeName != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[17] issuerAltName GeneralName: ");
        buffer.append(issuerAlternativeName.toString(depth + 4)).append(LINE_SEPARATOR);
    }

    if (extendedKeyUsage != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[18] extendedKeyUsage OBJECT IDENTIFIER: ");
        buffer.append(extendedKeyUsage).append(LINE_SEPARATOR);
    }

    if (authenticationInfoAccessOcsp != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[19] authInfoAccess IA5String: ");
        buffer.append(authenticationInfoAccessOcsp.toString()).append(LINE_SEPARATOR);
    }

    if (crlDistributionPointUri != null) {
        FormattingUtils.indent(buffer, depth + 3).append("[20] cRLDistribPoint IA5String: ");
        buffer.append(crlDistributionPointUri.toString()).append(LINE_SEPARATOR);
    }

    if (!extensions.isEmpty()) {
        FormattingUtils.indent(buffer, depth + 3).append("[21] x509extensions:").append(LINE_SEPARATOR);
        FormattingUtils.indent(buffer, depth + 4).append("X509Extensions SEQUENCE {").append(LINE_SEPARATOR);

        for (int i = 0; i < extensions.size(); i++) {
            Extension e = extensions.get(i);

            FormattingUtils.indent(buffer, depth + 5).append("[").append(i).append("] Extension SEQUENCE {")
                    .append(LINE_SEPARATOR);
            FormattingUtils.indent(buffer, depth + 6).append("extnId OBJECT IDENTIFIER: ");
            buffer.append(e.oid).append(LINE_SEPARATOR);

            FormattingUtils.indent(buffer, depth + 6).append("criticality BOOLEAN: ");
            buffer.append((e.isCritical ? "TRUE" : "FALSE")).append(LINE_SEPARATOR);

            if (e.value != null) {
                FormattingUtils.indent(buffer, depth + 6).append("extnValue OCTET STRING: ");
                buffer.append(Hex.toHexString(e.value)).append(LINE_SEPARATOR);
            }

            FormattingUtils.indent(buffer, depth + 5).append("}").append(LINE_SEPARATOR);
        }

        FormattingUtils.indent(buffer, depth + 4).append("}").append(LINE_SEPARATOR);
    }

    if (caCalcValue != null) {
        ASN1Sequence caCalcValueSequence = null;
        // The caCalcValue is an ASN1Sequence for non-ECQV certificate but not for ECQV
        // certificate, so exception may be encountered
        try {
            caCalcValueSequence = ASN1Sequence.getInstance(caCalcValue);
        } catch (Exception e) {
            // Not an ASN1Sequence
            caCalcValueSequence = null;
        }

        if (caCalcValueSequence != null) {
            FormattingUtils.indent(buffer, depth + 1).append("[1] cACalcValue OCTET STRING representing: ")
                    .append(LINE_SEPARATOR);
            FormattingUtils.indent(buffer, depth + 2).append("SEQUENCE {").append(LINE_SEPARATOR);

            for (int i = 0; i < caCalcValueSequence.size(); i++) {
                try {
                    FormattingUtils.indent(buffer, depth + 3).append("INTEGER: ")
                            .append(Hex.toHexString(
                                    caCalcValueSequence.getObjectAt(i).toASN1Primitive().getEncoded()))
                            .append(LINE_SEPARATOR);
                } catch (IOException ex) {
                    // Do nothing.
                }
            }

            FormattingUtils.indent(buffer, depth + 2).append("}").append(LINE_SEPARATOR);
        } else {
            FormattingUtils.indent(buffer, depth + 1).append("[1] cACalcValue OCTET STRING: ");
            buffer.append(Hex.toHexString(caCalcValue)).append(LINE_SEPARATOR);
        }
    }

    FormattingUtils.indent(buffer, depth).append("}").append(LINE_SEPARATOR);

    return buffer.toString();
}

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 a2 s  . c om*/
 *
 * <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:com.aaasec.sigserv.cscommon.xmldsig.XMLSign.java

License:EUPL

public static EcdsaSigValue ecdsaSignDataWithSha256(byte[] data, PrivateKey privKey) {
    try {//from   ww  w  .ja  va  2s. c  om
        Signature ecdsaSigner = Signature.getInstance("SHA256/ECDSA", "BC");
        ecdsaSigner.initSign(privKey, new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes()));
        ecdsaSigner.update(data);
        byte[] asn1Signature = ecdsaSigner.sign();

        ASN1InputStream a1i = new ASN1InputStream(asn1Signature);
        ASN1Sequence a1s = ASN1Sequence.getInstance(a1i.readObject());
        EcdsaSigValue sigVal = new EcdsaSigValue(a1s);

        return sigVal;
    } catch (Exception ex) {
    }
    return null;
}

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();
    }// w  w w.  ja  v a2  s.  c o 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.aqnote.shared.cryptology.cert.gen.CertGenerator.java

License:Open Source License

public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair)
        throws Exception {
    SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance(ALG_RSA);
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() - DateConstant.ONE_DAY),
            new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
            .build(pKeyPair.getPrivate());
    X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
            .getCertificate(certBuilder.build(signer));
    signedCert.verify(pKeyPair.getPublic());

    return signedCert;
}

From source file:com.itextpdf.signatures.CertificateUtil.java

License:Open Source License

/**
 * Gets the URL of the TSA if it's available on the certificate
 * @param certificate   a certificate/*from w w  w .  ja  v a  2s .  c om*/
 * @return   a TSA URL
 * @throws IOException
 */
public static String getTSAURL(X509Certificate certificate) {
    byte[] der = SignUtils.getExtensionValueByOid(certificate, SecurityIDs.ID_TSA);
    if (der == null)
        return null;
    ASN1Primitive asn1obj;
    try {
        asn1obj = ASN1Primitive.fromByteArray(der);
        DEROctetString octets = (DEROctetString) asn1obj;
        asn1obj = ASN1Primitive.fromByteArray(octets.getOctets());
        ASN1Sequence asn1seq = ASN1Sequence.getInstance(asn1obj);
        return getStringFromGeneralName(asn1seq.getObjectAt(1).toASN1Primitive());
    } catch (IOException e) {
        return null;
    }
}

From source file:com.itextpdf.signatures.PdfPKCS7.java

License:Open Source License

/**
 * Use this constructor if you want to verify a signature.
 *
 * @param contentsKey   the /Contents key
 * @param filterSubtype the filtersubtype
 * @param provider      the provider or <code>null</code> for the default provider
 *///from w  w  w.  j ava2 s . co m
@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(PdfException.CannotDecodePkcs7SigneddataObject);
        }
        if (!(pkcs instanceof ASN1Sequence)) {
            throw new IllegalArgumentException(PdfException.NotAValidPkcs7ObjectNotASequence);
        }
        ASN1Sequence signedData = (ASN1Sequence) pkcs;
        ASN1ObjectIdentifier objId = (ASN1ObjectIdentifier) signedData.getObjectAt(0);
        if (!objId.getId().equals(SecurityIDs.ID_PKCS7_SIGNED_DATA))
            throw new IllegalArgumentException(PdfException.NotAValidPkcs7ObjectNotSignedData);
        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<>();
        Enumeration e = ((ASN1Set) content.getObjectAt(1)).getObjects();
        while (e.hasMoreElements()) {
            ASN1Sequence s = (ASN1Sequence) 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:
        */
        certs = SignUtils.readAllCerts(contentsKey);
        /*
                    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(
                    PdfException.ThisPkcs7ObjectHasMultipleSignerinfosOnlyOneIsSupportedAtThisTime);
        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 = SignUtils.getIssuerX509Name(issuerAndSerialNumber);
        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 PdfException(PdfException.CannotFindSigningCertificateWithSerial1)
                    .setMessageParams(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 = SignUtils.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 = SignUtils
                            .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(PdfException.AuthenticatedAttributeIsMissingTheDigest);
            ++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));
                org.bouncycastle.asn1.cms.ContentInfo contentInfo = org.bouncycastle.asn1.cms.ContentInfo
                        .getInstance(tokenSequence);
                this.timeStampToken = new TimeStampToken(contentInfo);
            }
        }
        if (isTsp) {
            org.bouncycastle.asn1.cms.ContentInfo contentInfoTsp = org.bouncycastle.asn1.cms.ContentInfo
                    .getInstance(signedData);
            this.timeStampToken = new TimeStampToken(contentInfoTsp);
            TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
            String algOID = info.getHashAlgorithm().getAlgorithm().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 PdfException(e);
    }
}

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

License:Open Source License

/**
 * Verifies a signature using the sub-filter adbe.pkcs7.detached or
 * adbe.pkcs7.sha1./*  w ww  .j  av  a2  s.c o  m*/
 * @param contentsKey the /Contents key
 * @param provider the provider or <code>null</code> for the default provider
 */
@SuppressWarnings("unchecked")
public PdfPKCS7(byte[] contentsKey, String provider) {
    try {
        this.provider = provider;
        ASN1InputStream din = new ASN1InputStream(new ByteArrayInputStream(contentsKey));

        //
        // Basic checks to make sure it's a PKCS#7 SignedData Object
        //
        DERObject 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;
        DERObjectIdentifier objId = (DERObjectIdentifier) signedData.getObjectAt(0);
        if (!objId.getId().equals(ID_PKCS7_SIGNED_DATA))
            throw new IllegalArgumentException(
                    MessageLocalization.getComposedMessage("not.a.valid.pkcs.7.object.not.signed.data"));
        ASN1Sequence content = (ASN1Sequence) ((DERTaggedObject) 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 = ((DERInteger) 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();
            DERObjectIdentifier o = (DERObjectIdentifier) s.getObjectAt(0);
            digestalgos.add(o.getId());
        }

        // the certificates
        X509CertParser cr = new X509CertParser();
        cr.engineInit(new ByteArrayInputStream(contentsKey));
        certs = cr.engineReadAll();

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

        // the signerInfos
        int next = 3;
        while (content.getObjectAt(next) instanceof DERTaggedObject)
            ++next;
        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 = ((DERInteger) signerInfo.getObjectAt(0)).getValue().intValue();
        // Get the signing certificate
        ASN1Sequence issuerAndSerialNumber = (ASN1Sequence) signerInfo.getObjectAt(1);
        X509Principal issuer = new X509Principal(
                issuerAndSerialNumber.getObjectAt(0).getDERObject().getEncoded());
        BigInteger serialNumber = ((DERInteger) issuerAndSerialNumber.getObjectAt(1)).getValue();
        for (Object element : certs) {
            X509Certificate cert = (X509Certificate) element;
            if (issuer.equals(cert.getIssuerDN()) && 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();
        digestAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(2)).getObjectAt(0))
                .getId();
        next = 3;
        if (signerInfo.getObjectAt(next) instanceof ASN1TaggedObject) {
            ASN1TaggedObject tagsig = (ASN1TaggedObject) signerInfo.getObjectAt(next);
            ASN1Set sseq = ASN1Set.getInstance(tagsig, false);
            sigAttr = sseq.getEncoded(ASN1Encodable.DER);

            for (int k = 0; k < sseq.size(); ++k) {
                ASN1Sequence seq2 = (ASN1Sequence) sseq.getObjectAt(k);
                if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(ID_MESSAGE_DIGEST)) {
                    ASN1Set set = (ASN1Set) seq2.getObjectAt(1);
                    digestAttr = ((DEROctetString) set.getObjectAt(0)).getOctets();
                } else if (((DERObjectIdentifier) seq2.getObjectAt(0)).getId().equals(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);
                        }
                    }
                }
            }
            if (digestAttr == null)
                throw new IllegalArgumentException(MessageLocalization
                        .getComposedMessage("authenticated.attribute.is.missing.the.digest"));
            ++next;
        }
        digestEncryptionAlgorithm = ((DERObjectIdentifier) ((ASN1Sequence) signerInfo.getObjectAt(next++))
                .getObjectAt(0)).getId();
        digest = ((DEROctetString) signerInfo.getObjectAt(next++)).getOctets();
        if (next < signerInfo.size() && signerInfo.getObjectAt(next) instanceof DERTaggedObject) {
            DERTaggedObject taggedObject = (DERTaggedObject) 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 (RSAdata != null || digestAttr != null) {
            if (provider == null || provider.startsWith("SunPKCS11"))
                messageDigest = MessageDigest.getInstance(getHashAlgorithm());
            else
                messageDigest = MessageDigest.getInstance(getHashAlgorithm(), provider);
        }
        if (provider == null)
            sig = Signature.getInstance(getDigestAlgorithm());
        else
            sig = Signature.getInstance(getDigestAlgorithm(), provider);
        sig.initVerify(signCert.getPublicKey());
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}