Search in sources :

Example 51 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project cxf by apache.

the class XmlEncOutInterceptor method createKeyInfoElement.

private Element createKeyInfoElement(Document encryptedDataDoc, X509Certificate remoteCert) throws Exception {
    Element keyInfoElement = encryptedDataDoc.createElementNS(SIG_NS, SIG_PREFIX + ":KeyInfo");
    String keyIdType = encProps.getEncryptionKeyIdType() == null ? RSSecurityUtils.X509_CERT : encProps.getEncryptionKeyIdType();
    Node keyIdentifierNode = null;
    if (keyIdType.equals(RSSecurityUtils.X509_CERT)) {
        byte[] data = null;
        try {
            data = remoteCert.getEncoded();
        } catch (CertificateEncodingException e) {
            throw new WSSecurityException(WSSecurityException.ErrorCode.SECURITY_TOKEN_UNAVAILABLE, e, "encodeError");
        }
        Text text = encryptedDataDoc.createTextNode(Base64.getMimeEncoder().encodeToString(data));
        Element cert = encryptedDataDoc.createElementNS(SIG_NS, SIG_PREFIX + ":X509Certificate");
        cert.appendChild(text);
        Element x509Data = encryptedDataDoc.createElementNS(SIG_NS, SIG_PREFIX + ":X509Data");
        x509Data.appendChild(cert);
        keyIdentifierNode = x509Data;
    } else if (keyIdType.equals(RSSecurityUtils.X509_ISSUER_SERIAL)) {
        String issuer = remoteCert.getIssuerDN().getName();
        java.math.BigInteger serialNumber = remoteCert.getSerialNumber();
        DOMX509IssuerSerial domIssuerSerial = new DOMX509IssuerSerial(encryptedDataDoc, issuer, serialNumber);
        DOMX509Data domX509Data = new DOMX509Data(encryptedDataDoc, domIssuerSerial);
        keyIdentifierNode = domX509Data.getElement();
    } else {
        throw new Exception("Unsupported key identifier:" + keyIdType);
    }
    keyInfoElement.appendChild(keyIdentifierNode);
    return keyInfoElement;
}
Also used : Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) CertificateEncodingException(java.security.cert.CertificateEncodingException) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) Text(org.w3c.dom.Text) DOMX509IssuerSerial(org.apache.wss4j.common.token.DOMX509IssuerSerial) DOMX509Data(org.apache.wss4j.common.token.DOMX509Data) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) BadPaddingException(javax.crypto.BadPaddingException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 52 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project cxf by apache.

the class KeyManagementUtils method getCertificateFromThumbprint.

public static X509Certificate getCertificateFromThumbprint(String thumbprint, String digestAlgorithm, Message m, Properties props) {
    KeyStore ks = loadPersistKeyStore(m, props);
    if (ks == null || thumbprint == null) {
        return null;
    }
    try {
        byte[] decodedThumbprint = Base64UrlUtility.decode(thumbprint);
        for (Enumeration<String> e = ks.aliases(); e.hasMoreElements(); ) {
            String alias = e.nextElement();
            Certificate[] certs = ks.getCertificateChain(alias);
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                Certificate cert = ks.getCertificate(alias);
                if (cert != null) {
                    certs = new Certificate[] { cert };
                }
            }
            if (certs != null && certs.length > 0 && certs[0] instanceof X509Certificate) {
                X509Certificate x509cert = (X509Certificate) certs[0];
                byte[] data = MessageDigestUtils.createDigest(x509cert.getEncoded(), digestAlgorithm);
                if (Arrays.equals(data, decodedThumbprint)) {
                    return x509cert;
                }
            }
        }
    } catch (KeyStoreException e) {
        LOG.log(Level.WARNING, "X509Certificate can not be loaded: ", e);
        throw new JoseException(e);
    } catch (CertificateEncodingException e) {
        LOG.log(Level.WARNING, "X509Certificate can not be loaded: ", e);
        throw new JoseException(e);
    } catch (NoSuchAlgorithmException e) {
        LOG.log(Level.WARNING, "X509Certificate can not be loaded: ", e);
        throw new JoseException(e);
    } catch (Base64Exception e) {
        LOG.log(Level.WARNING, "X509Certificate can not be loaded: ", e);
        throw new JoseException(e);
    }
    return null;
}
Also used : Base64Exception(org.apache.cxf.common.util.Base64Exception) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 53 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project cxf by apache.

the class ValidatorCRLTest method prepareValidateXKMSRequest.

/*
     * Method is taken from {@link org.apache.cxf.xkms.client.XKMSInvoker}.
     */
private ValidateRequestType prepareValidateXKMSRequest(X509Certificate cert) {
    JAXBElement<byte[]> x509Cert;
    try {
        x509Cert = DSIG_OF.createX509DataTypeX509Certificate(cert.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new IllegalArgumentException(e);
    }
    X509DataType x509DataType = DSIG_OF.createX509DataType();
    x509DataType.getX509IssuerSerialOrX509SKIOrX509SubjectName().add(x509Cert);
    JAXBElement<X509DataType> x509Data = DSIG_OF.createX509Data(x509DataType);
    KeyInfoType keyInfoType = DSIG_OF.createKeyInfoType();
    keyInfoType.getContent().add(x509Data);
    QueryKeyBindingType queryKeyBindingType = XKMS_OF.createQueryKeyBindingType();
    queryKeyBindingType.setKeyInfo(keyInfoType);
    ValidateRequestType validateRequestType = XKMS_OF.createValidateRequestType();
    setGenericRequestParams(validateRequestType);
    validateRequestType.setQueryKeyBinding(queryKeyBindingType);
    // temporary
    validateRequestType.setId(cert.getSubjectDN().toString());
    return validateRequestType;
}
Also used : X509DataType(org.apache.cxf.xkms.model.xmldsig.X509DataType) QueryKeyBindingType(org.apache.cxf.xkms.model.xkms.QueryKeyBindingType) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyInfoType(org.apache.cxf.xkms.model.xmldsig.KeyInfoType) ValidateRequestType(org.apache.cxf.xkms.model.xkms.ValidateRequestType)

Example 54 with CertificateEncodingException

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

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 55 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project baseio by generallycloud.

the class SelfSignedCertificate method generate.

public void generate(String fileRoot, int bits) throws CertificateEncodingException {
    final KeyPair keypair;
    try {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(bits, random);
        keypair = keyGen.generateKeyPair();
    } catch (NoSuchAlgorithmException e) {
        // have RSA key pair generator.
        throw new Error(e);
    }
    File[] files;
    try {
        // Try the OpenJDK's proprietary implementation.
        files = generate(fileRoot, fqdn, keypair, random, notBefore, notAfter);
    } catch (Exception t) {
        logger.debug("Failed to generate a self-signed X.509 certificate using sun.security.x509:", t);
        throw new Error(t);
    }
    certificate = files[0];
    privateKey = files[1];
    key = keypair.getPrivate();
    FileInputStream certificateInput = null;
    try {
        certificateInput = new FileInputStream(certificate);
        cert = (X509Certificate) CertificateFactory.getInstance("X509").generateCertificate(certificateInput);
    } catch (Exception e) {
        throw new CertificateEncodingException(e);
    } finally {
        if (certificateInput != null) {
            try {
                certificateInput.close();
            } catch (IOException e) {
                logger.error("Failed to close a file: " + certificate, e);
            }
        }
    }
}
Also used : KeyPair(java.security.KeyPair) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) File(java.io.File) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) FileInputStream(java.io.FileInputStream)

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