Search in sources :

Example 11 with GeneralSecurityException

use of java.security.GeneralSecurityException in project java-apns by notnoop.

the class SSLContextBuilder method build.

public SSLContext build() throws InvalidSSLConfig {
    if (keyManagerFactory == null) {
        throw new InvalidSSLConfig("Missing KeyManagerFactory");
    }
    if (trustManagers == null) {
        throw new InvalidSSLConfig("Missing TrustManagers");
    }
    try {
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, null);
        return sslContext;
    } catch (GeneralSecurityException e) {
        throw new InvalidSSLConfig(e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) InvalidSSLConfig(com.notnoop.exceptions.InvalidSSLConfig) SSLContext(javax.net.ssl.SSLContext)

Example 12 with GeneralSecurityException

use of java.security.GeneralSecurityException in project java-apns by notnoop.

the class SSLContextBuilder method withDefaultTrustKeyStore.

public SSLContextBuilder withDefaultTrustKeyStore() throws InvalidSSLConfig {
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
        trustManagerFactory.init((KeyStore) null);
        trustManagers = trustManagerFactory.getTrustManagers();
        return this;
    } catch (GeneralSecurityException e) {
        throw new InvalidSSLConfig(e);
    }
}
Also used : TrustManagerFactory(javax.net.ssl.TrustManagerFactory) GeneralSecurityException(java.security.GeneralSecurityException) InvalidSSLConfig(com.notnoop.exceptions.InvalidSSLConfig)

Example 13 with GeneralSecurityException

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

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 14 with GeneralSecurityException

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

the class AndroidKeyStoreCipherSpiBase method ensureKeystoreOperationInitialized.

private void ensureKeystoreOperationInitialized() throws InvalidKeyException, InvalidAlgorithmParameterException {
    if (mMainDataStreamer != null) {
        return;
    }
    if (mCachedException != null) {
        return;
    }
    if (mKey == null) {
        throw new IllegalStateException("Not initialized");
    }
    KeymasterArguments keymasterInputArgs = new KeymasterArguments();
    addAlgorithmSpecificParametersToBegin(keymasterInputArgs);
    byte[] additionalEntropy = KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng(mRng, getAdditionalEntropyAmountForBegin());
    int purpose;
    if (mKeymasterPurposeOverride != -1) {
        purpose = mKeymasterPurposeOverride;
    } else {
        purpose = mEncrypting ? KeymasterDefs.KM_PURPOSE_ENCRYPT : KeymasterDefs.KM_PURPOSE_DECRYPT;
    }
    OperationResult opResult = mKeyStore.begin(mKey.getAlias(), purpose, // permit aborting this operation if keystore runs out of resources
    true, keymasterInputArgs, additionalEntropy, mKey.getUid());
    if (opResult == null) {
        throw new KeyStoreConnectException();
    }
    // Store operation token and handle regardless of the error code returned by KeyStore to
    // ensure that the operation gets aborted immediately if the code below throws an exception.
    mOperationToken = opResult.token;
    mOperationHandle = opResult.operationHandle;
    // If necessary, throw an exception due to KeyStore operation having failed.
    GeneralSecurityException e = KeyStoreCryptoOperationUtils.getExceptionForCipherInit(mKeyStore, mKey, opResult.resultCode);
    if (e != null) {
        if (e instanceof InvalidKeyException) {
            throw (InvalidKeyException) e;
        } else if (e instanceof InvalidAlgorithmParameterException) {
            throw (InvalidAlgorithmParameterException) e;
        } else {
            throw new ProviderException("Unexpected exception type", e);
        }
    }
    if (mOperationToken == null) {
        throw new ProviderException("Keystore returned null operation token");
    }
    if (mOperationHandle == 0) {
        throw new ProviderException("Keystore returned invalid operation handle");
    }
    loadAlgorithmSpecificParametersFromBeginResult(opResult.outParams);
    mMainDataStreamer = createMainDataStreamer(mKeyStore, opResult.token);
    mAdditionalAuthenticationDataStreamer = createAdditionalAuthenticationDataStreamer(mKeyStore, opResult.token);
    mAdditionalAuthenticationDataStreamerClosed = false;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeymasterArguments(android.security.keymaster.KeymasterArguments) ProviderException(java.security.ProviderException) GeneralSecurityException(java.security.GeneralSecurityException) OperationResult(android.security.keymaster.OperationResult) InvalidKeyException(java.security.InvalidKeyException)

Example 15 with GeneralSecurityException

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

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)

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