Search in sources :

Example 11 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project XobotOS by xamarin.

the class MiscPEMGenerator method createPemObject.

private PemObject createPemObject(Object o) throws IOException {
    String type;
    byte[] encoding;
    if (o instanceof PemObject) {
        return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
        return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509Certificate) {
        type = "CERTIFICATE";
        try {
            encoding = ((X509Certificate) o).getEncoded();
        } catch (CertificateEncodingException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof X509CRL) {
        type = "X509 CRL";
        try {
            encoding = ((X509CRL) o).getEncoded();
        } catch (CRLException e) {
            throw new PemGenerationException("Cannot encode object: " + e.toString());
        }
    } else if (o instanceof KeyPair) {
        return createPemObject(((KeyPair) o).getPrivate());
    } else if (o instanceof PrivateKey) {
        PrivateKeyInfo info = new PrivateKeyInfo((ASN1Sequence) ASN1Object.fromByteArray(((Key) o).getEncoded()));
        if (o instanceof RSAPrivateKey) {
            type = "RSA PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else if (o instanceof DSAPrivateKey) {
            type = "DSA PRIVATE KEY";
            DSAParameter p = DSAParameter.getInstance(info.getAlgorithmId().getParameters());
            ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERInteger(0));
            v.add(new DERInteger(p.getP()));
            v.add(new DERInteger(p.getQ()));
            v.add(new DERInteger(p.getG()));
            BigInteger x = ((DSAPrivateKey) o).getX();
            BigInteger y = p.getG().modPow(x, p.getP());
            v.add(new DERInteger(y));
            v.add(new DERInteger(x));
            encoding = new DERSequence(v).getEncoded();
        } else if (((PrivateKey) o).getAlgorithm().equals("ECDSA")) {
            type = "EC PRIVATE KEY";
            encoding = info.getPrivateKey().getEncoded();
        } else {
            throw new IOException("Cannot identify private key");
        }
    } else if (o instanceof PublicKey) {
        type = "PUBLIC KEY";
        encoding = ((PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) {
        type = "ATTRIBUTE CERTIFICATE";
        encoding = ((X509V2AttributeCertificate) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
        type = "CERTIFICATE REQUEST";
        encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
        type = "PKCS7";
        encoding = ((ContentInfo) o).getEncoded();
    } else {
        throw new PemGenerationException("unknown object passed - can't encode.");
    }
    return new PemObject(type, encoding);
}
Also used : X509CRL(java.security.cert.X509CRL) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKey(java.security.PrivateKey) X509AttributeCertificate(org.bouncycastle.x509.X509AttributeCertificate) DERInteger(org.bouncycastle.asn1.DERInteger) PemObjectGenerator(org.bouncycastle.util.io.pem.PemObjectGenerator) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) CRLException(java.security.cert.CRLException) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPair(java.security.KeyPair) PemGenerationException(org.bouncycastle.util.io.pem.PemGenerationException) PublicKey(java.security.PublicKey) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) X509V2AttributeCertificate(org.bouncycastle.x509.X509V2AttributeCertificate) X509Certificate(java.security.cert.X509Certificate) PemObject(org.bouncycastle.util.io.pem.PemObject) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) BigInteger(java.math.BigInteger) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PrivateKeyInfo(org.bouncycastle.asn1.pkcs.PrivateKeyInfo) DSAPrivateKey(java.security.interfaces.DSAPrivateKey) RSAPrivateKey(java.security.interfaces.RSAPrivateKey) PublicKey(java.security.PublicKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) RSAPrivateCrtKey(java.security.interfaces.RSAPrivateCrtKey)

Example 12 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project XobotOS by xamarin.

the class ContentInfo method toASN1Object.

/**
     * Produce an object suitable for an ASN1OutputStream.
     * <pre>
     * ContentInfo ::= SEQUENCE {
     *          contentType ContentType,
     *          content
     *          [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL }
     * </pre>
     */
public DERObject toASN1Object() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(contentType);
    if (content != null) {
        v.add(new BERTaggedObject(0, content));
    }
    return new BERSequence(v);
}
Also used : BERSequence(org.bouncycastle.asn1.BERSequence) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) BERTaggedObject(org.bouncycastle.asn1.BERTaggedObject)

Example 13 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project robovm by robovm.

the class PKCS12KeyStoreSpi method doStore.

private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) throws IOException {
    if (password == null) {
        throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
    }
    //
    // handle the key
    //
    ASN1EncodableVector keyS = new ASN1EncodableVector();
    Enumeration ks = keys.keys();
    while (ks.hasMoreElements()) {
        byte[] kSalt = new byte[SALT_SIZE];
        random.nextBytes(kSalt);
        String name = (String) ks.nextElement();
        PrivateKey privKey = (PrivateKey) keys.get(name);
        PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS);
        byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password);
        AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.toASN1Primitive());
        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes);
        boolean attrSet = false;
        ASN1EncodableVector kName = new ASN1EncodableVector();
        if (privKey instanceof PKCS12BagAttributeCarrier) {
            PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) privKey;
            //
            // make sure we are using the local alias on store
            //
            DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
            if (nm == null || !nm.getString().equals(name)) {
                bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
            }
            //
            if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                Certificate ct = engineGetCertificate(name);
                bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey()));
            }
            Enumeration e = bagAttrs.getBagAttributeKeys();
            while (e.hasMoreElements()) {
                ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                ASN1EncodableVector kSeq = new ASN1EncodableVector();
                kSeq.add(oid);
                kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                attrSet = true;
                kName.add(new DERSequence(kSeq));
            }
        }
        if (!attrSet) {
            //
            // set a default friendly name (from the key id) and local id
            //
            ASN1EncodableVector kSeq = new ASN1EncodableVector();
            Certificate ct = engineGetCertificate(name);
            kSeq.add(pkcs_9_at_localKeyId);
            kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey())));
            kName.add(new DERSequence(kSeq));
            kSeq = new ASN1EncodableVector();
            kSeq.add(pkcs_9_at_friendlyName);
            kSeq.add(new DERSet(new DERBMPString(name)));
            kName.add(new DERSequence(kSeq));
        }
        SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.toASN1Primitive(), new DERSet(kName));
        keyS.add(kBag);
    }
    byte[] keySEncoded = new DERSequence(keyS).getEncoded(ASN1Encoding.DER);
    BEROctetString keyString = new BEROctetString(keySEncoded);
    //
    // certificate processing
    //
    byte[] cSalt = new byte[SALT_SIZE];
    random.nextBytes(cSalt);
    ASN1EncodableVector certSeq = new ASN1EncodableVector();
    PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS);
    AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.toASN1Primitive());
    Hashtable doneCerts = new Hashtable();
    Enumeration cs = keys.keys();
    while (cs.hasMoreElements()) {
        try {
            String name = (String) cs.nextElement();
            Certificate cert = engineGetCertificate(name);
            boolean cAttrSet = false;
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(name)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
                }
                //
                if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                    bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey()));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_localKeyId);
                fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey())));
                fName.add(new DERSequence(fSeq));
                fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(name)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = certs.keys();
    while (cs.hasMoreElements()) {
        try {
            String certId = (String) cs.nextElement();
            Certificate cert = (Certificate) certs.get(certId);
            boolean cAttrSet = false;
            if (keys.get(certId) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(certId)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(certId)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = chainCerts.keys();
    while (cs.hasMoreElements()) {
        try {
            CertId certId = (CertId) cs.nextElement();
            Certificate cert = (Certificate) chainCerts.get(certId);
            if (doneCerts.get(cert) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                }
            }
            SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
            certSeq.add(sBag);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    byte[] certSeqEncoded = new DERSequence(certSeq).getEncoded(ASN1Encoding.DER);
    byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded);
    EncryptedData cInfo = new EncryptedData(data, cAlgId, new BEROctetString(certBytes));
    ContentInfo[] info = new ContentInfo[] { new ContentInfo(data, keyString), new ContentInfo(encryptedData, cInfo.toASN1Primitive()) };
    AuthenticatedSafe auth = new AuthenticatedSafe(info);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream asn1Out;
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(bOut);
    } else {
        asn1Out = new BEROutputStream(bOut);
    }
    asn1Out.writeObject(auth);
    byte[] pkg = bOut.toByteArray();
    ContentInfo mainInfo = new ContentInfo(data, new BEROctetString(pkg));
    //
    // create the mac
    //
    byte[] mSalt = new byte[20];
    int itCount = MIN_ITERATIONS;
    random.nextBytes(mSalt);
    byte[] data = ((ASN1OctetString) mainInfo.getContent()).getOctets();
    MacData mData;
    try {
        byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data);
        AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE);
        DigestInfo dInfo = new DigestInfo(algId, res);
        mData = new MacData(dInfo, mSalt, itCount);
    } catch (Exception e) {
        throw new IOException("error constructing MAC: " + e.toString());
    }
    //
    // output the Pfx
    //
    Pfx pfx = new Pfx(mainInfo, mData);
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(stream);
    } else {
        asn1Out = new BEROutputStream(stream);
    }
    asn1Out.writeObject(pfx);
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PrivateKey(java.security.PrivateKey) AuthenticatedSafe(org.bouncycastle.asn1.pkcs.AuthenticatedSafe) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DEROctetString(org.bouncycastle.asn1.DEROctetString) BEROctetString(org.bouncycastle.asn1.BEROctetString) DERSet(org.bouncycastle.asn1.DERSet) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) BEROctetString(org.bouncycastle.asn1.BEROctetString) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) EncryptedData(org.bouncycastle.asn1.pkcs.EncryptedData) MacData(org.bouncycastle.asn1.pkcs.MacData) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) Pfx(org.bouncycastle.asn1.pkcs.Pfx) Hashtable(java.util.Hashtable) BEROutputStream(org.bouncycastle.asn1.BEROutputStream) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SafeBag(org.bouncycastle.asn1.pkcs.SafeBag) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) CertBag(org.bouncycastle.asn1.pkcs.CertBag) PKCS12PBEParams(org.bouncycastle.asn1.pkcs.PKCS12PBEParams) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) DEROutputStream(org.bouncycastle.asn1.DEROutputStream)

Example 14 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project keystore-explorer by kaikramer.

the class CryptoFileUtil method detectKeyStoreType.

/**
 * Detect the KeyStore type contained in the supplied file.
 *
 * @param is
 *            Input stream to detect type for
 * @return KeyStore type or null if none matched
 * @throws IOException
 *             If an I/O problem occurred
 */
public static KeyStoreType detectKeyStoreType(InputStream is) throws IOException {
    byte[] contents = ReadUtil.readFully(is);
    try (DataInputStream dis = new DataInputStream(new ByteArrayInputStream(contents))) {
        // If less than 4 bytes are available it isn't a KeyStore
        if (dis.available() < 4) {
            return null;
        }
        // Read first integer (4 bytes)
        int i1 = dis.readInt();
        // Test for JKS - starts with appropriate magic number
        if (i1 == JKS_MAGIC_NUMBER) {
            return JKS;
        }
        // Test for JCEKS - starts with appropriate magic number
        if (i1 == JCEKS_MAGIC_NUMBER) {
            return JCEKS;
        }
        // Both start with a version number of 0, 1 or 2
        if ((i1 == 0) || (i1 == 1) || (i1 == 2)) {
            if (contents.length < 26) {
                // Insufficient bytes to be BKS or UBER
                return null;
            }
            // Skip to 21st from last byte (file length minus 21 and the 4 bytes already read)
            dis.skip(contents.length - 25);
            // Read what may be the null byte
            if (dis.readByte() == 0) {
                // Found null byte - BKS/BKS-V1
                if (i1 == 1) {
                    return BKS_V1;
                } else {
                    return BKS;
                }
            } else {
                // No null byte - UBER
                return UBER;
            }
        }
    }
    // @formatter:off
    /*
		 * Test for PKCS #12. ASN.1 should look like this:
		 *
		 * PFX ::= ASN1Sequence { version ASN1Integer {v3(3)}(v3,...), authSafe
		 * ContentInfo, macData MacData OPTIONAL
		 */
    // @formatter:on
    ASN1Primitive pfx = null;
    try {
        pfx = ASN1Primitive.fromByteArray(contents);
    } catch (IOException e) {
        // if it cannot be parsed as ASN1, it is certainly not a pfx key store
        return null;
    }
    // Is a sequence...
    if ((pfx != null) && (pfx instanceof ASN1Sequence)) {
        // Has two or three components...
        ASN1Sequence sequence = (ASN1Sequence) pfx;
        if ((sequence.size() == 2) || (sequence.size() == 3)) {
            // ...the first of which is a version of 3
            ASN1Encodable firstComponent = sequence.getObjectAt(0);
            if (firstComponent instanceof ASN1Integer) {
                ASN1Integer version = (ASN1Integer) firstComponent;
                if (version.getValue().intValue() == 3) {
                    return PKCS12;
                }
            }
        }
    }
    // KeyStore type not recognised
    return null;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) DataInputStream(java.io.DataInputStream) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive)

Example 15 with ContentInfo

use of org.bouncycastle.asn1.pkcs.ContentInfo in project xades4j by luisgoncalves.

the class DefaultTimeStampVerificationProvider method verifyToken.

@Override
public Date verifyToken(byte[] timeStampToken, byte[] tsDigestInput) throws TimeStampTokenVerificationException {
    TimeStampToken tsToken;
    try {
        ASN1InputStream asn1is = new ASN1InputStream(timeStampToken);
        ContentInfo tsContentInfo = ContentInfo.getInstance(asn1is.readObject());
        asn1is.close();
        tsToken = new TimeStampToken(tsContentInfo);
    } catch (IOException ex) {
        throw new TimeStampTokenStructureException("Error parsing encoded token", ex);
    } catch (TSPException ex) {
        throw new TimeStampTokenStructureException("Invalid token", ex);
    }
    X509Certificate tsaCert = null;
    try {
        /* Validate the TSA certificate */
        LinkedList<X509Certificate> certs = new LinkedList<X509Certificate>();
        for (Object certHolder : tsToken.getCertificates().getMatches(new AllCertificatesSelector())) {
            certs.add(this.x509CertificateConverter.getCertificate((X509CertificateHolder) certHolder));
        }
        ValidationData vData = this.certificateValidationProvider.validate(x509CertSelectorConverter.getCertSelector(tsToken.getSID()), tsToken.getTimeStampInfo().getGenTime(), certs);
        tsaCert = vData.getCerts().get(0);
    } catch (CertificateException ex) {
        throw new TimeStampTokenVerificationException(ex.getMessage(), ex);
    } catch (XAdES4jException ex) {
        throw new TimeStampTokenTSACertException("cannot validate TSA certificate", ex);
    }
    try {
        tsToken.validate(this.signerInfoVerifierBuilder.build(tsaCert));
    } catch (TSPValidationException ex) {
        throw new TimeStampTokenSignatureException("Invalid token signature or certificate", ex);
    } catch (Exception ex) {
        throw new TimeStampTokenVerificationException("Error when verifying the token signature", ex);
    }
    org.bouncycastle.tsp.TimeStampTokenInfo tsTokenInfo = tsToken.getTimeStampInfo();
    try {
        String digestAlgUri = uriForDigest(tsTokenInfo.getMessageImprintAlgOID());
        MessageDigest md = messageDigestProvider.getEngine(digestAlgUri);
        if (!Arrays.equals(md.digest(tsDigestInput), tsTokenInfo.getMessageImprintDigest())) {
            throw new TimeStampTokenDigestException();
        }
    } catch (UnsupportedAlgorithmException ex) {
        throw new TimeStampTokenVerificationException("The token's digest algorithm is not supported", ex);
    }
    return tsTokenInfo.getGenTime();
}
Also used : CertificateException(java.security.cert.CertificateException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) MessageDigest(java.security.MessageDigest) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList) TSPValidationException(org.bouncycastle.tsp.TSPValidationException) XAdES4jException(xades4j.XAdES4jException) TimeStampTokenTSACertException(xades4j.providers.TimeStampTokenTSACertException) TimeStampTokenStructureException(xades4j.providers.TimeStampTokenStructureException) TSPException(org.bouncycastle.tsp.TSPException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TimeStampTokenDigestException(xades4j.providers.TimeStampTokenDigestException) TimeStampTokenVerificationException(xades4j.providers.TimeStampTokenVerificationException) TimeStampTokenSignatureException(xades4j.providers.TimeStampTokenSignatureException) ValidationData(xades4j.providers.ValidationData) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken)

Aggregations

ContentInfo (org.bouncycastle.asn1.cms.ContentInfo)24 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)22 IOException (java.io.IOException)20 X509Certificate (java.security.cert.X509Certificate)18 CMSSignedData (org.bouncycastle.cms.CMSSignedData)14 CertificateException (java.security.cert.CertificateException)12 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)12 BERSequence (org.bouncycastle.asn1.BERSequence)12 CertificateEncodingException (java.security.cert.CertificateEncodingException)11 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)9 ASN1Set (org.bouncycastle.asn1.ASN1Set)9 SignedData (org.bouncycastle.asn1.cms.SignedData)9 CMSException (org.bouncycastle.cms.CMSException)9 PrivateKey (java.security.PrivateKey)8 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)8 DERSet (org.bouncycastle.asn1.DERSet)8 ContentInfo (org.bouncycastle.asn1.pkcs.ContentInfo)8 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)6