Search in sources :

Example 86 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project OA4MP by ncsa.

the class TransactionConverter method toMap.

@Override
public void toMap(V t, ConversionMap<String, Object> map) {
    super.toMap(t, map);
    if (t.getCertReq() == null) {
        map.put(getDSTK().certReq(), null);
    } else {
        map.put(getDSTK().certReq(), CertUtil.fromCertReqToString(t.getCertReq()));
    }
    MyX509Certificates myCert = (MyX509Certificates) t.getProtectedAsset();
    if (myCert == null || myCert.getX509Certificates() == null || myCert.getX509Certificates().length == 0) {
        map.put(getDSTK().cert(), null);
    } else {
        try {
            map.put(getDSTK().cert(), myCert.getX509CertificatesPEM());
        } catch (CertificateEncodingException e) {
            throw new GeneralException("Error: could not encode certificate", e);
        }
    }
    if (t.getClient() == null) {
        map.put(getDSTK().clientKey(), null);
    } else {
        map.put(getDSTK().clientKey(), t.getClient().getIdentifier());
    }
    if (t.getUsername() == null) {
        map.put(getDSTK().username(), null);
    } else {
        map.put(getDSTK().username(), t.getUsername());
    }
    if (t.getMyproxyUsername() == null) {
        map.put(getDSTK().myproxyUsername(), null);
    } else {
        map.put(getDSTK().myproxyUsername(), t.getMyproxyUsername());
    }
}
Also used : GeneralException(edu.uiuc.ncsa.security.core.exceptions.GeneralException) CertificateEncodingException(java.security.cert.CertificateEncodingException) MyX509Certificates(edu.uiuc.ncsa.security.delegation.token.MyX509Certificates)

Example 87 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project remote-desktop-clients by iiordanov.

the class RemoteCanvas method validateX509Cert.

/**
 * If there is a saved cert, checks the one given against it. If a signature was passed in
 * and no saved cert, then check that signature. Otherwise, presents the
 * given cert's signature to the user for approval.
 * <p>
 * The saved data must always win over any passed-in URI data
 *
 * @param cert the given cert.
 */
@SuppressLint("StringFormatInvalid")
private void validateX509Cert(final X509Certificate cert) {
    boolean certMismatch = false;
    int hashAlg = connection.getIdHashAlgorithm();
    byte[] certData = null;
    boolean isSigEqual = false;
    try {
        certData = cert.getEncoded();
        isSigEqual = SecureTunnel.isSignatureEqual(hashAlg, connection.getIdHash(), certData);
    } catch (Exception ex) {
        ex.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
        return;
    }
    // check the signature and save the cert if the signature matches.
    if (connection.getSshHostKey().equals("")) {
        if (!connection.getIdHash().equals("")) {
            if (isSigEqual) {
                Log.i(TAG, "Certificate validated from URI data.");
                saveAndAcceptCert(cert);
                return;
            } else {
                certMismatch = true;
            }
        }
    // If there is a saved cert, check against it.
    } else if (connection.getSshHostKey().equals(Base64.encodeToString(certData, Base64.DEFAULT))) {
        Log.i(TAG, "Certificate validated from saved key.");
        saveAndAcceptCert(cert);
        return;
    } else {
        certMismatch = true;
    }
    // Show a dialog with the key signature for approval.
    DialogInterface.OnClickListener signatureNo = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            // We were told not to continue, so stop the activity
            Log.i(TAG, "Certificate rejected by user.");
            closeConnection();
            ((Activity) getContext()).finish();
        }
    };
    DialogInterface.OnClickListener signatureYes = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Log.i(TAG, "Certificate accepted by user.");
            saveAndAcceptCert(cert);
        }
    };
    // Display dialog to user with cert info and hash.
    try {
        // First build the message. If there was a mismatch, prepend a warning about it.
        String message = "";
        if (certMismatch) {
            message = getContext().getString(R.string.warning_cert_does_not_match) + "\n\n";
        }
        byte[] certBytes = cert.getEncoded();
        String certIdHash = SecureTunnel.computeSignatureByAlgorithm(hashAlg, certBytes);
        String certInfo = String.format(Locale.US, getContext().getString(R.string.info_cert_tunnel), certIdHash, cert.getSubjectX500Principal().getName(), cert.getIssuerX500Principal().getName(), cert.getNotBefore(), cert.getNotAfter());
        certInfo = message + certInfo.replace(",", "\n");
        // Actually display the message
        Utils.showYesNoPrompt(getContext(), getContext().getString(R.string.info_continue_connecting) + connection.getAddress() + "?", certInfo, signatureYes, signatureNo);
    } catch (NoSuchAlgorithmException e2) {
        e2.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_signature));
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        showFatalMessageAndQuit(getContext().getString(R.string.error_x509_could_not_generate_encoding));
    }
}
Also used : DialogInterface(android.content.DialogInterface) FragmentActivity(android.support.v4.app.FragmentActivity) Activity(android.app.Activity) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SuppressLint(android.annotation.SuppressLint) AnonCipherUnsupportedException(com.iiordanov.bVNC.exceptions.AnonCipherUnsupportedException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) SuppressLint(android.annotation.SuppressLint)

Example 88 with CertificateEncodingException

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

the class CertUtil method loadPrivateKey.

/**
 *  Get a single Private Key from an input stream.
 *  Does NOT close the stream.
 *
 *  @return non-null, non-empty, throws on all errors including certificate invalid
 *  @since 0.9.25
 */
public static PrivateKey loadPrivateKey(InputStream in) throws IOException, GeneralSecurityException {
    try {
        String line;
        while ((line = DataHelper.readLine(in)) != null) {
            if (line.startsWith("---") && line.contains("BEGIN") && line.contains("PRIVATE"))
                break;
        }
        if (line == null)
            throw new IOException("no private key found");
        StringBuilder buf = new StringBuilder(128);
        while ((line = DataHelper.readLine(in)) != null) {
            if (line.startsWith("---"))
                break;
            buf.append(line.trim());
        }
        if (buf.length() <= 0)
            throw new IOException("no private key found");
        byte[] data = Base64.decode(buf.toString(), true);
        if (data == null)
            throw new CertificateEncodingException("bad base64 cert");
        PrivateKey rv = null;
        // try all the types
        for (SigAlgo algo : EnumSet.allOf(SigAlgo.class)) {
            try {
                KeySpec ks = new PKCS8EncodedKeySpec(data);
                String alg = algo.getName();
                KeyFactory kf = KeyFactory.getInstance(alg);
                rv = kf.generatePrivate(ks);
                break;
            } catch (GeneralSecurityException gse) {
            // gse.printStackTrace();
            }
        }
        if (rv == null)
            throw new InvalidKeyException("unsupported key type");
        return rv;
    } catch (IllegalArgumentException iae) {
        // at java.util.Base64$Decoder.decode0(Base64.java:704)
        throw new GeneralSecurityException("key error", iae);
    }
}
Also used : PrivateKey(java.security.PrivateKey) KeySpec(java.security.spec.KeySpec) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) GeneralSecurityException(java.security.GeneralSecurityException) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyFactory(java.security.KeyFactory)

Example 89 with CertificateEncodingException

use of java.security.cert.CertificateEncodingException in project platform_packages_apps_Settings by BlissRoms.

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

use of java.security.cert.CertificateEncodingException in project cosmic by MissionCriticalCloud.

the class CertificateHelper method generateFingerPrint.

public static String generateFingerPrint(final Certificate cert) {
    final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    final StringBuilder buffer = new StringBuilder(60);
    try {
        final MessageDigest md = MessageDigest.getInstance("SHA-1");
        final byte[] data = md.digest(cert.getEncoded());
        for (int i = 0; i < data.length; i++) {
            if (buffer.length() > 0) {
                buffer.append(":");
            }
            buffer.append(HEX[(0xF0 & data[i]) >>> 4]);
            buffer.append(HEX[0x0F & data[i]]);
        }
    } catch (final CertificateEncodingException e) {
        throw new CloudRuntimeException("Bad certificate encoding");
    } catch (final NoSuchAlgorithmException e) {
        throw new CloudRuntimeException("Bad certificate algorithm");
    }
    return buffer.toString();
}
Also used : CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) CertificateEncodingException(java.security.cert.CertificateEncodingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest)

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