Search in sources :

Example 26 with GeneralSecurityException

use of java.security.GeneralSecurityException in project android_frameworks_base by DirtyUnicorns.

the class OSUManager method provisioningComplete.

public void provisioningComplete(OSUInfo osuInfo, MOData moData, Map<OSUCertType, List<X509Certificate>> certs, PrivateKey privateKey, Network osuNetwork) {
    synchronized (mWifiNetworkAdapter) {
        mProvisioningThread = null;
    }
    try {
        Log.d("ZXZ", "MOTree.toXML: " + moData.getMOTree().toXml());
        HomeSP homeSP = mWifiNetworkAdapter.addSP(moData.getMOTree());
        Integer spNwk = mWifiNetworkAdapter.addNetwork(homeSP, certs, privateKey, osuNetwork);
        if (spNwk == null) {
            notifyUser(OSUOperationStatus.ProvisioningFailure, "Failed to save network configuration", osuInfo.getName(LOCALE));
            mWifiNetworkAdapter.removeSP(homeSP.getFQDN());
        } else {
            Set<X509Certificate> rootCerts = OSUSocketFactory.getRootCerts(mKeyStore);
            X509Certificate remCert = getCert(certs, OSUCertType.Remediation);
            X509Certificate polCert = getCert(certs, OSUCertType.Policy);
            if (privateKey != null) {
                X509Certificate cltCert = getCert(certs, OSUCertType.Client);
                mKeyStore.setKeyEntry(CERT_CLT_KEY_ALIAS + homeSP, privateKey.getEncoded(), new X509Certificate[] { cltCert });
                mKeyStore.setCertificateEntry(CERT_CLT_CERT_ALIAS, cltCert);
            }
            boolean usingShared = false;
            int newCerts = 0;
            if (remCert != null) {
                if (!rootCerts.contains(remCert)) {
                    if (remCert.equals(polCert)) {
                        mKeyStore.setCertificateEntry(CERT_SHARED_ALIAS + homeSP.getFQDN(), remCert);
                        usingShared = true;
                        newCerts++;
                    } else {
                        mKeyStore.setCertificateEntry(CERT_REM_ALIAS + homeSP.getFQDN(), remCert);
                        newCerts++;
                    }
                }
            }
            if (!usingShared && polCert != null) {
                if (!rootCerts.contains(polCert)) {
                    mKeyStore.setCertificateEntry(CERT_POLICY_ALIAS + homeSP.getFQDN(), remCert);
                    newCerts++;
                }
            }
            if (newCerts > 0) {
                try (FileOutputStream out = new FileOutputStream(KEYSTORE_FILE)) {
                    mKeyStore.store(out, null);
                }
            }
            notifyUser(OSUOperationStatus.ProvisioningSuccess, null, osuInfo.getName(LOCALE));
            Log.d(TAG, "Provisioning complete.");
        }
    } catch (IOException | GeneralSecurityException | SAXException e) {
        Log.e(TAG, "Failed to provision: " + e, e);
        notifyUser(OSUOperationStatus.ProvisioningFailure, e.toString(), osuInfo.getName(LOCALE));
    }
}
Also used : HomeSP(com.android.hotspot2.pps.HomeSP) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FileOutputStream(java.io.FileOutputStream) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) SAXException(org.xml.sax.SAXException)

Example 27 with GeneralSecurityException

use of java.security.GeneralSecurityException in project OpenAM by OpenRock.

the class LocalLdapAuthModule method authenticate.

private boolean authenticate(String dn, String passwd) throws LoginException {
    // LDAP connection used for authentication
    Connection localConn = null;
    String host;
    int port;
    Options ldapOptions = Options.defaultOptions();
    // Check if organization is present in options
    String orgUrl = (String) options.get(LoginContext.ORGNAME);
    if ((orgUrl == null) || (orgUrl.equals(LoginContext.LDAP_AUTH_URL)) || (orgUrl.equals(LoginContext.LDAPS_AUTH_URL)) || !(orgUrl.startsWith(LoginContext.LDAP_AUTH_URL) || orgUrl.startsWith(LoginContext.LDAPS_AUTH_URL))) {
        try {
            DSConfigMgr dscm = DSConfigMgr.getDSConfigMgr();
            // We need a handle on server instance so we can know the
            // Connection type. If it is SSL, the connection needs to be
            // accordingly created. Note: The user type does not make
            // a difference, as the connection type is Server group based,
            // so passing any user type for the second argument.
            ServerInstance si = dscm.getServerInstance(DSConfigMgr.DEFAULT, LDAPUser.Type.AUTH_BASIC);
            String hostName = dscm.getHostName(DSConfigMgr.DEFAULT);
            if (si.getConnectionType() == Server.Type.CONN_SSL) {
                try {
                    ldapOptions.set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
                } catch (GeneralSecurityException e) {
                    debug.error("getConnection.JSSESocketFactory", e);
                    throw new LDAPServiceException(AuthI18n.authI18n.getString(IUMSConstants.DSCFG_JSSSFFAIL));
                }
            }
            if (dn != null && passwd != null) {
                // The 389 port number passed is overridden by the
                // hostName:port
                // constructed by the getHostName method. So, this is not
                // a hardcoded port number.
                host = hostName;
                port = 389;
            } else {
                // Throw LoginException
                throw new LoginException(AuthI18n.authI18n.getString(IUMSConstants.DSCFG_CONNECTFAIL));
            }
        } catch (LDAPServiceException ex) {
            debug.error("Authenticate failed: " + ex);
            throw new LoginException(ex.getMessage());
        }
    } else {
        try {
            if (debug.messageEnabled()) {
                debug.message("authenticate(): orgUrl= " + orgUrl);
            }
            // Get hostname
            int start;
            boolean useSSL = false;
            if (orgUrl.startsWith(LoginContext.LDAPS_AUTH_URL)) {
                start = LoginContext.LDAPS_AUTH_URL.length();
                useSSL = true;
            } else {
                start = LoginContext.LDAP_AUTH_URL.length();
            }
            int end = orgUrl.indexOf(':', start);
            if (end == -1) {
                end = orgUrl.indexOf('/', start);
                if (end == -1)
                    end = orgUrl.length();
            }
            String hostName = orgUrl.substring(start, end);
            // Get port number
            String portNumber = "389";
            start = end + 1;
            if (start < orgUrl.length()) {
                end = orgUrl.indexOf('/', start);
                if (end == -1)
                    end = orgUrl.length();
                portNumber = orgUrl.substring(start, end);
            }
            if (useSSL) {
                try {
                    ldapOptions.set(LDAPConnectionFactory.SSL_CONTEXT, new SSLContextBuilder().getSSLContext());
                } catch (GeneralSecurityException e) {
                    debug.error("authentication().JSSESocketFactory()", e);
                    throw (new LoginException(e.getMessage()));
                }
            }
            if (debug.messageEnabled()) {
                debug.message("before connect(), hostName=" + hostName + ",port=" + portNumber);
            }
            host = hostName;
            port = Integer.parseInt(portNumber);
        } catch (Exception e) {
            debug.error("authentication", e);
            throw (new LoginException(e.getMessage()));
        }
    }
    try (ConnectionFactory factory = LDAPUtils.createFailoverConnectionFactory(host, port, dn, passwd, ldapOptions);
        Connection conn = factory.getConnection()) {
        return true;
    } catch (LdapException e) {
        throw new LoginException(e.getMessage());
    }
}
Also used : Options(org.forgerock.util.Options) GeneralSecurityException(java.security.GeneralSecurityException) Connection(org.forgerock.opendj.ldap.Connection) DSConfigMgr(com.iplanet.services.ldap.DSConfigMgr) LoginException(javax.security.auth.login.LoginException) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) LdapException(org.forgerock.opendj.ldap.LdapException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) LoginException(javax.security.auth.login.LoginException) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) ServerInstance(com.iplanet.services.ldap.ServerInstance) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder) LdapException(org.forgerock.opendj.ldap.LdapException)

Example 28 with GeneralSecurityException

use of java.security.GeneralSecurityException in project android_frameworks_base by DirtyUnicorns.

the class HTTPHandler method httpExchange.

private HTTPResponse httpExchange(URL url, String message, HTTPMessage.Method method, String contentType) throws IOException {
    HTTPRequest request = new HTTPRequest(message, mCharset, method, url, contentType, false);
    request.send(mOut);
    HTTPResponse response = new HTTPResponse(mIn);
    Log.d(OSUManager.TAG, "HTTP code " + response.getStatusCode() + ", user " + mUser + ", pw " + (mPassword != null ? '\'' + new String(mPassword) + '\'' : "-"));
    if (response.getStatusCode() == 401) {
        if (mUser == null) {
            throw new IOException("Missing user name for HTTP authentication");
        }
        try {
            request = new HTTPRequest(message, StandardCharsets.ISO_8859_1, method, url, contentType, true);
            request.doAuthenticate(response, mUser, mPassword, url, sSequence.incrementAndGet());
            request.send(mOut);
            mHTTPAuthPerformed = true;
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse);
        }
        response = new HTTPResponse(mIn);
    }
    return response;
}
Also used : HTTPRequest(com.android.hotspot2.utils.HTTPRequest) HTTPResponse(com.android.hotspot2.utils.HTTPResponse) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException)

Example 29 with GeneralSecurityException

use of java.security.GeneralSecurityException in project android_frameworks_base by DirtyUnicorns.

the class StrictJarVerifier method verifyCertificate.

/**
     * @param certFile
     */
private void verifyCertificate(String certFile) {
    // Found Digital Sig, .SF should already have been read
    String signatureFile = certFile.substring(0, certFile.lastIndexOf('.')) + ".SF";
    byte[] sfBytes = metaEntries.get(signatureFile);
    if (sfBytes == null) {
        return;
    }
    byte[] manifestBytes = metaEntries.get(JarFile.MANIFEST_NAME);
    // Manifest entry is required for any verifications.
    if (manifestBytes == null) {
        return;
    }
    byte[] sBlockBytes = metaEntries.get(certFile);
    try {
        Certificate[] signerCertChain = verifyBytes(sBlockBytes, sfBytes);
        if (signerCertChain != null) {
            certificates.put(signatureFile, signerCertChain);
        }
    } catch (GeneralSecurityException e) {
        throw failedVerification(jarName, signatureFile, e);
    }
    // Verify manifest hash in .sf file
    Attributes attributes = new Attributes();
    HashMap<String, Attributes> entries = new HashMap<String, Attributes>();
    try {
        StrictJarManifestReader im = new StrictJarManifestReader(sfBytes, attributes);
        im.readEntries(entries, null);
    } catch (IOException e) {
        return;
    }
    // If requested, check whether APK Signature Scheme v2 signature was stripped.
    if (signatureSchemeRollbackProtectionsEnforced) {
        String apkSignatureSchemeIdList = attributes.getValue(ApkSignatureSchemeV2Verifier.SF_ATTRIBUTE_ANDROID_APK_SIGNED_NAME);
        if (apkSignatureSchemeIdList != null) {
            // This field contains a comma-separated list of APK signature scheme IDs which
            // were used to sign this APK. If an ID is known to us, it means signatures of that
            // scheme were stripped from the APK because otherwise we wouldn't have fallen back
            // to verifying the APK using the JAR signature scheme.
            boolean v2SignatureGenerated = false;
            StringTokenizer tokenizer = new StringTokenizer(apkSignatureSchemeIdList, ",");
            while (tokenizer.hasMoreTokens()) {
                String idText = tokenizer.nextToken().trim();
                if (idText.isEmpty()) {
                    continue;
                }
                int id;
                try {
                    id = Integer.parseInt(idText);
                } catch (Exception ignored) {
                    continue;
                }
                if (id == ApkSignatureSchemeV2Verifier.SF_ATTRIBUTE_ANDROID_APK_SIGNED_ID) {
                    // This APK was supposed to be signed with APK Signature Scheme v2 but no
                    // such signature was found.
                    v2SignatureGenerated = true;
                    break;
                }
            }
            if (v2SignatureGenerated) {
                throw new SecurityException(signatureFile + " indicates " + jarName + " is signed using APK Signature Scheme v2, but no such signature was" + " found. Signature stripped?");
            }
        }
    }
    // Do we actually have any signatures to look at?
    if (attributes.get(Attributes.Name.SIGNATURE_VERSION) == null) {
        return;
    }
    boolean createdBySigntool = false;
    String createdBy = attributes.getValue("Created-By");
    if (createdBy != null) {
        createdBySigntool = createdBy.indexOf("signtool") != -1;
    }
    // such verification.
    if (mainAttributesEnd > 0 && !createdBySigntool) {
        String digestAttribute = "-Digest-Manifest-Main-Attributes";
        if (!verify(attributes, digestAttribute, manifestBytes, 0, mainAttributesEnd, false, true)) {
            throw failedVerification(jarName, signatureFile);
        }
    }
    // Use .SF to verify the whole manifest.
    String digestAttribute = createdBySigntool ? "-Digest" : "-Digest-Manifest";
    if (!verify(attributes, digestAttribute, manifestBytes, 0, manifestBytes.length, false, false)) {
        Iterator<Map.Entry<String, Attributes>> it = entries.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Attributes> entry = it.next();
            StrictJarManifest.Chunk chunk = manifest.getChunk(entry.getKey());
            if (chunk == null) {
                return;
            }
            if (!verify(entry.getValue(), "-Digest", manifestBytes, chunk.start, chunk.end, createdBySigntool, false)) {
                throw invalidDigest(signatureFile, entry.getKey(), jarName);
            }
        }
    }
    metaEntries.put(signatureFile, null);
    signatures.put(signatureFile, entries);
}
Also used : HashMap(java.util.HashMap) GeneralSecurityException(java.security.GeneralSecurityException) Attributes(java.util.jar.Attributes) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) StringTokenizer(java.util.StringTokenizer) HashMap(java.util.HashMap) Map(java.util.Map) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 30 with GeneralSecurityException

use of java.security.GeneralSecurityException in project jdk8u_jdk by JetBrains.

the class RSAEncryptDecrypt method main.

public static void main(String[] args) throws Exception {
    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SunMSCAPI");
    KeyPair keyPair = generator.generateKeyPair();
    Key publicKey = keyPair.getPublic();
    Key privateKey = keyPair.getPrivate();
    Cipher cipher = null;
    try {
        cipher = Cipher.getInstance("RSA", "SunMSCAPI");
    } catch (GeneralSecurityException e) {
        System.out.println("Cipher not supported by provider, skipping...");
        return;
    }
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    displayBytes("Plaintext data:", PLAINTEXT);
    byte[] data = cipher.doFinal(PLAINTEXT);
    displayBytes("Encrypted data:", data);
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    data = cipher.doFinal(data);
    displayBytes("Decrypted data:", data);
}
Also used : KeyPair(java.security.KeyPair) GeneralSecurityException(java.security.GeneralSecurityException) KeyPairGenerator(java.security.KeyPairGenerator) Cipher(javax.crypto.Cipher) Key(java.security.Key)

Aggregations

GeneralSecurityException (java.security.GeneralSecurityException)1197 IOException (java.io.IOException)448 Cipher (javax.crypto.Cipher)148 Test (org.junit.Test)136 X509Certificate (java.security.cert.X509Certificate)130 KeyStore (java.security.KeyStore)98 SSLContext (javax.net.ssl.SSLContext)86 SecretKeySpec (javax.crypto.spec.SecretKeySpec)82 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)77 ArrayList (java.util.ArrayList)75 File (java.io.File)64 InputStream (java.io.InputStream)63 Certificate (java.security.cert.Certificate)61 PublicKey (java.security.PublicKey)56 FileInputStream (java.io.FileInputStream)54 PrivateKey (java.security.PrivateKey)51 BigInteger (java.math.BigInteger)50 SecretKey (javax.crypto.SecretKey)48 IvParameterSpec (javax.crypto.spec.IvParameterSpec)47 KeyPair (java.security.KeyPair)45