Search in sources :

Example 61 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project keystore-explorer by kaikramer.

the class Pkcs10Util method generateCsr.

/**
 * Create a PKCS #10 certificate signing request (CSR) using the supplied
 * certificate, private key and signature algorithm.
 *
 * @param cert
 *            The certificate
 * @param privateKey
 *            The private key
 * @param signatureType
 *            Signature
 * @param challenge
 *            Challenge, optional, pass null if not required
 * @param unstructuredName
 *            An optional company name, pass null if not required
 * @param useExtensions
 *            Use extensions from cert for extensionRequest attribute?
 * @throws CryptoException
 *             If there was a problem generating the CSR
 * @return The CSR
 */
public static PKCS10CertificationRequest generateCsr(X509Certificate cert, PrivateKey privateKey, SignatureType signatureType, String challenge, String unstructuredName, boolean useExtensions, Provider provider) throws CryptoException {
    try {
        JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(cert.getSubjectX500Principal(), cert.getPublicKey());
        // add challenge attribute
        if (challenge != null) {
            // PKCS#9 2.0: SHOULD use UTF8String encoding
            csrBuilder.addAttribute(pkcs_9_at_challengePassword, new DERUTF8String(challenge));
        }
        if (unstructuredName != null) {
            csrBuilder.addAttribute(pkcs_9_at_unstructuredName, new DERUTF8String(unstructuredName));
        }
        if (useExtensions) {
            // add extensionRequest attribute with all extensions from the certificate
            Certificate certificate = Certificate.getInstance(cert.getEncoded());
            Extensions extensions = certificate.getTBSCertificate().getExtensions();
            if (extensions != null) {
                csrBuilder.addAttribute(pkcs_9_at_extensionRequest, extensions.toASN1Primitive());
            }
        }
        // fall back to bouncy castle provider if given provider does not support the requested algorithm
        if (provider != null && provider.getService("Signature", signatureType.jce()) == null) {
            provider = new BouncyCastleProvider();
        }
        ContentSigner contentSigner = null;
        if (provider == null) {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).build(privateKey);
        } else {
            contentSigner = new JcaContentSignerBuilder(signatureType.jce()).setProvider(provider).build(privateKey);
        }
        PKCS10CertificationRequest csr = csrBuilder.build(contentSigner);
        if (!verifyCsr(csr)) {
            throw new CryptoException(res.getString("NoVerifyGenPkcs10Csr.exception.message"));
        }
        return csr;
    } catch (CertificateEncodingException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    } catch (OperatorCreationException e) {
        throw new CryptoException(res.getString("NoGeneratePkcs10Csr.exception.message"), e);
    }
}
Also used : PKCS10CertificationRequest(org.bouncycastle.pkcs.PKCS10CertificationRequest) JcaPKCS10CertificationRequest(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) JcaPKCS10CertificationRequestBuilder(org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequestBuilder) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) ContentSigner(org.bouncycastle.operator.ContentSigner) CertificateEncodingException(java.security.cert.CertificateEncodingException) Extensions(org.bouncycastle.asn1.x509.Extensions) CryptoException(org.kse.crypto.CryptoException) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(org.bouncycastle.asn1.x509.Certificate) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 62 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project android_packages_apps_Settings by SudaMod.

the class CertInstallerHelper method installCertificate.

/**
 * Extract certificate from the given file, and install it to keystore
 * @param name certificate name
 * @param certFile .p12 file which includes certificates
 * @param password password to extract the .p12 file
 */
public void installCertificate(VpnProfile profile, String certFile, String password) {
    // extract private keys, certificates from the provided file
    extractCertificate(certFile, password);
    // install certificate to the keystore
    int flags = KeyStore.FLAG_ENCRYPTED;
    try {
        if (mUserKey != null) {
            Log.v(TAG, "has private key");
            String key = Credentials.USER_PRIVATE_KEY + profile.ipsecUserCert;
            byte[] value = mUserKey.getEncoded();
            if (!mKeyStore.importKey(key, value, mUid, flags)) {
                Log.e(TAG, "Failed to install " + key + " as user " + mUid);
                return;
            }
            Log.v(TAG, "install " + key + " as user " + mUid + " is successful");
        }
        if (mUserCert != null) {
            String certName = Credentials.USER_CERTIFICATE + profile.ipsecUserCert;
            byte[] certData = Credentials.convertToPem(mUserCert);
            if (!mKeyStore.put(certName, certData, mUid, flags)) {
                Log.e(TAG, "Failed to install " + certName + " as user " + mUid);
                return;
            }
            Log.v(TAG, "install " + certName + " as user" + mUid + " is successful.");
        }
        if (!mCaCerts.isEmpty()) {
            String caListName = Credentials.CA_CERTIFICATE + profile.ipsecCaCert;
            X509Certificate[] caCerts = mCaCerts.toArray(new X509Certificate[mCaCerts.size()]);
            byte[] caListData = Credentials.convertToPem(caCerts);
            if (!mKeyStore.put(caListName, caListData, mUid, flags)) {
                Log.e(TAG, "Failed to install " + caListName + " as user " + mUid);
                return;
            }
            Log.v(TAG, " install " + caListName + " as user " + mUid + " is successful");
        }
    } catch (CertificateEncodingException e) {
        Log.e(TAG, "Exception while convert certificates to pem " + e);
        throw new AssertionError(e);
    } catch (IOException e) {
        Log.e(TAG, "IOException while convert to pem: " + e);
    }
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) DEROctetString(com.android.org.bouncycastle.asn1.DEROctetString) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate)

Example 63 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project xades4j by luisgoncalves.

the class DataGenBaseCertRefs method generate.

protected PropertyDataObject generate(Collection<X509Certificate> certs, BaseCertRefsData certRefsData, QualifyingProperty prop) throws PropertyDataGenerationException {
    if (null == certs) {
        throw new PropertyDataGenerationException(prop, "certificates not provided");
    }
    try {
        String digestAlgUri = this.algorithmsProvider.getDigestAlgorithmForReferenceProperties();
        MessageDigest messageDigest = this.messageDigestProvider.getEngine(digestAlgUri);
        for (X509Certificate cert : certs) {
            // "DigestValue contains the base-64 encoded value of the digest
            // computed on the DER-encoded certificate."
            // The base-64 encoding is done by JAXB with the configured
            // adapter (Base64XmlAdapter).
            // For X509 certificates the encoded form return by getEncoded is DER.
            byte[] digestValue = messageDigest.digest(cert.getEncoded());
            certRefsData.addCertRef(new CertRef(cert.getIssuerX500Principal().getName(), cert.getSerialNumber(), digestAlgUri, digestValue));
        }
        return certRefsData;
    } catch (UnsupportedAlgorithmException ex) {
        throw new PropertyDataGenerationException(prop, ex.getMessage(), ex);
    } catch (CertificateEncodingException ex) {
        throw new PropertyDataGenerationException(prop, "cannot get encoded certificate", ex);
    }
}
Also used : UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) CertRef(xades4j.properties.data.CertRef) CertificateEncodingException(java.security.cert.CertificateEncodingException) MessageDigest(java.security.MessageDigest) X509Certificate(java.security.cert.X509Certificate)

Example 64 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project xades4j by luisgoncalves.

the class CertRefUtils method checkCertRef.

static void checkCertRef(CertRef certRef, X509Certificate cert, MessageDigestEngineProvider messageDigestProvider) throws InvalidCertRefException {
    MessageDigest messageDigest;
    Throwable t = null;
    try {
        messageDigest = messageDigestProvider.getEngine(certRef.digestAlgUri);
        byte[] actualDigest = messageDigest.digest(cert.getEncoded());
        if (!Arrays.equals(certRef.digestValue, actualDigest))
            throw new InvalidCertRefException("digests mismatch");
        return;
    } catch (UnsupportedAlgorithmException ex) {
        t = ex;
    } catch (CertificateEncodingException ex) {
        t = ex;
    }
    throw new InvalidCertRefException(t.getMessage());
}
Also used : UnsupportedAlgorithmException(xades4j.UnsupportedAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) MessageDigest(java.security.MessageDigest)

Example 65 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project xipki by xipki.

the class X509Util method buildCertPath.

/**
 * Build the certificate path. Cross certificate will not be considered.
 * @param cert certificate for which the certificate path will be built
 * @param certs collection of certificates.
 * @return the certificate path
 */
public static X509Certificate[] buildCertPath(X509Certificate cert, Set<? extends Certificate> certs) {
    ParamUtil.requireNonNull("cert", cert);
    List<X509Certificate> certChain = new LinkedList<>();
    certChain.add(cert);
    try {
        if (certs != null && !isSelfSigned(cert)) {
            while (true) {
                X509Certificate caCert = getCaCertOf(certChain.get(certChain.size() - 1), certs);
                if (caCert == null) {
                    break;
                }
                certChain.add(caCert);
                if (isSelfSigned(caCert)) {
                    // reaches root self-signed certificate
                    break;
                }
            }
        }
    } catch (CertificateEncodingException ex) {
        LOG.warn("CertificateEncodingException: {}", ex.getMessage());
    }
    final int n = certChain.size();
    int len = n;
    if (n > 1) {
        for (int i = 1; i < n; i++) {
            int pathLen = certChain.get(i).getBasicConstraints();
            if (pathLen < 0 || pathLen < i) {
                len = i;
                break;
            }
        }
    }
    if (len == n) {
        return certChain.toArray(new X509Certificate[0]);
    } else {
        X509Certificate[] ret = new X509Certificate[len];
        for (int i = 0; i < len; i++) {
            ret[i] = certChain.get(i);
        }
        return ret;
    }
}
Also used : CertificateEncodingException(java.security.cert.CertificateEncodingException) X509Certificate(java.security.cert.X509Certificate) LinkedList(java.util.LinkedList)

Aggregations

CertificateEncodingException (java.security.cert.CertificateEncodingException)210 X509Certificate (java.security.cert.X509Certificate)94 IOException (java.io.IOException)76 Certificate (java.security.cert.Certificate)29 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)27 KeyStoreException (java.security.KeyStoreException)19 MessageDigest (java.security.MessageDigest)19 ArrayList (java.util.ArrayList)19 X500Name (org.bouncycastle.asn1.x500.X500Name)16 CertificateException (java.security.cert.CertificateException)14 BigInteger (java.math.BigInteger)11 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)10 Bundle (android.os.Bundle)9 PublicKey (java.security.PublicKey)9 Date (java.util.Date)9 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)9 ByteArrayOutputStream (java.io.ByteArrayOutputStream)8 File (java.io.File)8 PrivateKey (java.security.PrivateKey)8 DEROctetString (org.bouncycastle.asn1.DEROctetString)8