Search in sources :

Example 61 with InvalidAlgorithmParameterException

use of java.security.InvalidAlgorithmParameterException in project platform_frameworks_base by android.

the class LockSettingsService method setLockPatternInternal.

private void setLockPatternInternal(String pattern, String savedCredential, int userId) throws RemoteException {
    byte[] currentHandle = getCurrentHandle(userId);
    if (pattern == null) {
        clearUserKeyProtection(userId);
        getGateKeeperService().clearSecureUserId(userId);
        mStorage.writePatternHash(null, userId);
        setKeystorePassword(null, userId);
        fixateNewestUserKeyAuth(userId);
        onUserLockChanged(userId);
        return;
    }
    if (isManagedProfileWithUnifiedLock(userId)) {
        // get credential from keystore when managed profile has unified lock
        try {
            savedCredential = getDecryptedPasswordForTiedProfile(userId);
        } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
            if (e instanceof FileNotFoundException) {
                Slog.i(TAG, "Child profile key not found");
            } else {
                Slog.e(TAG, "Failed to decrypt child profile key", e);
            }
        }
    } else {
        if (currentHandle == null) {
            if (savedCredential != null) {
                Slog.w(TAG, "Saved credential provided, but none stored");
            }
            savedCredential = null;
        }
    }
    byte[] enrolledHandle = enrollCredential(currentHandle, savedCredential, pattern, userId);
    if (enrolledHandle != null) {
        CredentialHash willStore = new CredentialHash(enrolledHandle, CredentialHash.VERSION_GATEKEEPER);
        setUserKeyProtection(userId, pattern, doVerifyPattern(pattern, willStore, true, 0, userId, null));
        mStorage.writePatternHash(enrolledHandle, userId);
        fixateNewestUserKeyAuth(userId);
        onUserLockChanged(userId);
    } else {
        throw new RemoteException("Failed to enroll pattern");
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CredentialHash(com.android.server.LockSettingsStorage.CredentialHash) FileNotFoundException(java.io.FileNotFoundException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) RemoteException(android.os.RemoteException)

Example 62 with InvalidAlgorithmParameterException

use of java.security.InvalidAlgorithmParameterException in project platform_frameworks_base by android.

the class ApkSignatureSchemeV2Verifier method verifySigner.

private static X509Certificate[] verifySigner(ByteBuffer signerBlock, Map<Integer, byte[]> contentDigests, CertificateFactory certFactory) throws SecurityException, IOException {
    ByteBuffer signedData = getLengthPrefixedSlice(signerBlock);
    ByteBuffer signatures = getLengthPrefixedSlice(signerBlock);
    byte[] publicKeyBytes = readLengthPrefixedByteArray(signerBlock);
    int signatureCount = 0;
    int bestSigAlgorithm = -1;
    byte[] bestSigAlgorithmSignatureBytes = null;
    List<Integer> signaturesSigAlgorithms = new ArrayList<>();
    while (signatures.hasRemaining()) {
        signatureCount++;
        try {
            ByteBuffer signature = getLengthPrefixedSlice(signatures);
            if (signature.remaining() < 8) {
                throw new SecurityException("Signature record too short");
            }
            int sigAlgorithm = signature.getInt();
            signaturesSigAlgorithms.add(sigAlgorithm);
            if (!isSupportedSignatureAlgorithm(sigAlgorithm)) {
                continue;
            }
            if ((bestSigAlgorithm == -1) || (compareSignatureAlgorithm(sigAlgorithm, bestSigAlgorithm) > 0)) {
                bestSigAlgorithm = sigAlgorithm;
                bestSigAlgorithmSignatureBytes = readLengthPrefixedByteArray(signature);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new SecurityException("Failed to parse signature record #" + signatureCount, e);
        }
    }
    if (bestSigAlgorithm == -1) {
        if (signatureCount == 0) {
            throw new SecurityException("No signatures found");
        } else {
            throw new SecurityException("No supported signatures found");
        }
    }
    String keyAlgorithm = getSignatureAlgorithmJcaKeyAlgorithm(bestSigAlgorithm);
    Pair<String, ? extends AlgorithmParameterSpec> signatureAlgorithmParams = getSignatureAlgorithmJcaSignatureAlgorithm(bestSigAlgorithm);
    String jcaSignatureAlgorithm = signatureAlgorithmParams.first;
    AlgorithmParameterSpec jcaSignatureAlgorithmParams = signatureAlgorithmParams.second;
    boolean sigVerified;
    try {
        PublicKey publicKey = KeyFactory.getInstance(keyAlgorithm).generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        Signature sig = Signature.getInstance(jcaSignatureAlgorithm);
        sig.initVerify(publicKey);
        if (jcaSignatureAlgorithmParams != null) {
            sig.setParameter(jcaSignatureAlgorithmParams);
        }
        sig.update(signedData);
        sigVerified = sig.verify(bestSigAlgorithmSignatureBytes);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException | InvalidAlgorithmParameterException | SignatureException e) {
        throw new SecurityException("Failed to verify " + jcaSignatureAlgorithm + " signature", e);
    }
    if (!sigVerified) {
        throw new SecurityException(jcaSignatureAlgorithm + " signature did not verify");
    }
    // Signature over signedData has verified.
    byte[] contentDigest = null;
    signedData.clear();
    ByteBuffer digests = getLengthPrefixedSlice(signedData);
    List<Integer> digestsSigAlgorithms = new ArrayList<>();
    int digestCount = 0;
    while (digests.hasRemaining()) {
        digestCount++;
        try {
            ByteBuffer digest = getLengthPrefixedSlice(digests);
            if (digest.remaining() < 8) {
                throw new IOException("Record too short");
            }
            int sigAlgorithm = digest.getInt();
            digestsSigAlgorithms.add(sigAlgorithm);
            if (sigAlgorithm == bestSigAlgorithm) {
                contentDigest = readLengthPrefixedByteArray(digest);
            }
        } catch (IOException | BufferUnderflowException e) {
            throw new IOException("Failed to parse digest record #" + digestCount, e);
        }
    }
    if (!signaturesSigAlgorithms.equals(digestsSigAlgorithms)) {
        throw new SecurityException("Signature algorithms don't match between digests and signatures records");
    }
    int digestAlgorithm = getSignatureAlgorithmContentDigestAlgorithm(bestSigAlgorithm);
    byte[] previousSignerDigest = contentDigests.put(digestAlgorithm, contentDigest);
    if ((previousSignerDigest != null) && (!MessageDigest.isEqual(previousSignerDigest, contentDigest))) {
        throw new SecurityException(getContentDigestAlgorithmJcaDigestAlgorithm(digestAlgorithm) + " contents digest does not match the digest specified by a preceding signer");
    }
    ByteBuffer certificates = getLengthPrefixedSlice(signedData);
    List<X509Certificate> certs = new ArrayList<>();
    int certificateCount = 0;
    while (certificates.hasRemaining()) {
        certificateCount++;
        byte[] encodedCert = readLengthPrefixedByteArray(certificates);
        X509Certificate certificate;
        try {
            certificate = (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(encodedCert));
        } catch (CertificateException e) {
            throw new SecurityException("Failed to decode certificate #" + certificateCount, e);
        }
        certificate = new VerbatimX509Certificate(certificate, encodedCert);
        certs.add(certificate);
    }
    if (certs.isEmpty()) {
        throw new SecurityException("No certificates listed");
    }
    X509Certificate mainCertificate = certs.get(0);
    byte[] certificatePublicKeyBytes = mainCertificate.getPublicKey().getEncoded();
    if (!Arrays.equals(publicKeyBytes, certificatePublicKeyBytes)) {
        throw new SecurityException("Public key mismatch between certificate and signature record");
    }
    return certs.toArray(new X509Certificate[certs.size()]);
}
Also used : ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) BufferUnderflowException(java.nio.BufferUnderflowException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) PublicKey(java.security.PublicKey) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) DirectByteBuffer(java.nio.DirectByteBuffer) ByteBuffer(java.nio.ByteBuffer) X509Certificate(java.security.cert.X509Certificate) BigInteger(java.math.BigInteger) ByteArrayInputStream(java.io.ByteArrayInputStream) Signature(java.security.Signature) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 63 with InvalidAlgorithmParameterException

use of java.security.InvalidAlgorithmParameterException in project platform_frameworks_base by android.

the class AndroidKeyStoreKeyPairGeneratorSpi method initAlgorithmSpecificParameters.

private void initAlgorithmSpecificParameters() throws InvalidAlgorithmParameterException {
    AlgorithmParameterSpec algSpecificSpec = mSpec.getAlgorithmParameterSpec();
    switch(mKeymasterAlgorithm) {
        case KeymasterDefs.KM_ALGORITHM_RSA:
            {
                BigInteger publicExponent = null;
                if (algSpecificSpec instanceof RSAKeyGenParameterSpec) {
                    RSAKeyGenParameterSpec rsaSpec = (RSAKeyGenParameterSpec) algSpecificSpec;
                    if (mKeySizeBits == -1) {
                        mKeySizeBits = rsaSpec.getKeysize();
                    } else if (mKeySizeBits != rsaSpec.getKeysize()) {
                        throw new InvalidAlgorithmParameterException("RSA key size must match " + " between " + mSpec + " and " + algSpecificSpec + ": " + mKeySizeBits + " vs " + rsaSpec.getKeysize());
                    }
                    publicExponent = rsaSpec.getPublicExponent();
                } else if (algSpecificSpec != null) {
                    throw new InvalidAlgorithmParameterException("RSA may only use RSAKeyGenParameterSpec");
                }
                if (publicExponent == null) {
                    publicExponent = RSAKeyGenParameterSpec.F4;
                }
                if (publicExponent.compareTo(BigInteger.ZERO) < 1) {
                    throw new InvalidAlgorithmParameterException("RSA public exponent must be positive: " + publicExponent);
                }
                if (publicExponent.compareTo(KeymasterArguments.UINT64_MAX_VALUE) > 0) {
                    throw new InvalidAlgorithmParameterException("Unsupported RSA public exponent: " + publicExponent + ". Maximum supported value: " + KeymasterArguments.UINT64_MAX_VALUE);
                }
                mRSAPublicExponent = publicExponent;
                break;
            }
        case KeymasterDefs.KM_ALGORITHM_EC:
            if (algSpecificSpec instanceof ECGenParameterSpec) {
                ECGenParameterSpec ecSpec = (ECGenParameterSpec) algSpecificSpec;
                String curveName = ecSpec.getName();
                Integer ecSpecKeySizeBits = SUPPORTED_EC_NIST_CURVE_NAME_TO_SIZE.get(curveName.toLowerCase(Locale.US));
                if (ecSpecKeySizeBits == null) {
                    throw new InvalidAlgorithmParameterException("Unsupported EC curve name: " + curveName + ". Supported: " + SUPPORTED_EC_NIST_CURVE_NAMES);
                }
                if (mKeySizeBits == -1) {
                    mKeySizeBits = ecSpecKeySizeBits;
                } else if (mKeySizeBits != ecSpecKeySizeBits) {
                    throw new InvalidAlgorithmParameterException("EC key size must match " + " between " + mSpec + " and " + algSpecificSpec + ": " + mKeySizeBits + " vs " + ecSpecKeySizeBits);
                }
            } else if (algSpecificSpec != null) {
                throw new InvalidAlgorithmParameterException("EC may only use ECGenParameterSpec");
            }
            break;
        default:
            throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm);
    }
}
Also used : BigInteger(java.math.BigInteger) ASN1Integer(com.android.org.bouncycastle.asn1.ASN1Integer) DERInteger(com.android.org.bouncycastle.asn1.DERInteger) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) ProviderException(java.security.ProviderException) ECGenParameterSpec(java.security.spec.ECGenParameterSpec) BigInteger(java.math.BigInteger) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec)

Example 64 with InvalidAlgorithmParameterException

use of java.security.InvalidAlgorithmParameterException in project j2objc by google.

the class Cipher method chooseProvider.

private void chooseProvider(InitType initType, int opmode, Key key, AlgorithmParameterSpec paramSpec, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException {
    try {
        final InitParams initParams = new InitParams(initType, opmode, key, random, paramSpec, params);
        spiAndProviderUpdater.updateAndGetSpiAndProvider(initParams, spi, provider);
    } catch (Exception lastException) {
        // no working provider found, fail
        if (lastException instanceof InvalidKeyException) {
            throw (InvalidKeyException) lastException;
        }
        if (lastException instanceof InvalidAlgorithmParameterException) {
            throw (InvalidAlgorithmParameterException) lastException;
        }
        if (lastException instanceof RuntimeException) {
            throw (RuntimeException) lastException;
        }
        String kName = (key != null) ? key.getClass().getName() : "(null)";
        throw new InvalidKeyException("No installed provider supports this key: " + kName, lastException);
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) InvalidKeyException(java.security.InvalidKeyException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) InvalidParameterException(java.security.InvalidParameterException) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) NoSuchElementException(java.util.NoSuchElementException) ProviderException(java.security.ProviderException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchProviderException(java.security.NoSuchProviderException) ReadOnlyBufferException(java.nio.ReadOnlyBufferException)

Example 65 with InvalidAlgorithmParameterException

use of java.security.InvalidAlgorithmParameterException in project ExoPlayer by google.

the class CachedContentIndex method writeFile.

private void writeFile() throws CacheException {
    DataOutputStream output = null;
    try {
        OutputStream outputStream = atomicFile.startWrite();
        if (bufferedOutputStream == null) {
            bufferedOutputStream = new ReusableBufferedOutputStream(outputStream);
        } else {
            bufferedOutputStream.reset(outputStream);
        }
        output = new DataOutputStream(bufferedOutputStream);
        output.writeInt(VERSION);
        int flags = cipher != null ? FLAG_ENCRYPTED_INDEX : 0;
        output.writeInt(flags);
        if (cipher != null) {
            byte[] initializationVector = new byte[16];
            new Random().nextBytes(initializationVector);
            output.write(initializationVector);
            IvParameterSpec ivParameterSpec = new IvParameterSpec(initializationVector);
            try {
                cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
            } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
                // Should never happen.
                throw new IllegalStateException(e);
            }
            output.flush();
            output = new DataOutputStream(new CipherOutputStream(bufferedOutputStream, cipher));
        }
        output.writeInt(keyToContent.size());
        int hashCode = 0;
        for (CachedContent cachedContent : keyToContent.values()) {
            cachedContent.writeToStream(output);
            hashCode += cachedContent.headerHashCode();
        }
        output.writeInt(hashCode);
        atomicFile.endWrite(output);
        // Avoid calling close twice. Duplicate CipherOutputStream.close calls did
        // not used to be no-ops: https://android-review.googlesource.com/#/c/272799/
        output = null;
    } catch (IOException e) {
        throw new CacheException(e);
    } finally {
        Util.closeQuietly(output);
    }
}
Also used : ReusableBufferedOutputStream(com.google.android.exoplayer2.util.ReusableBufferedOutputStream) CipherOutputStream(javax.crypto.CipherOutputStream) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CacheException(com.google.android.exoplayer2.upstream.cache.Cache.CacheException) DataOutputStream(java.io.DataOutputStream) ReusableBufferedOutputStream(com.google.android.exoplayer2.util.ReusableBufferedOutputStream) DataOutputStream(java.io.DataOutputStream) CipherOutputStream(javax.crypto.CipherOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) Random(java.util.Random) IvParameterSpec(javax.crypto.spec.IvParameterSpec)

Aggregations

InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)394 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)216 InvalidKeyException (java.security.InvalidKeyException)206 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)130 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)114 BadPaddingException (javax.crypto.BadPaddingException)112 Cipher (javax.crypto.Cipher)101 IvParameterSpec (javax.crypto.spec.IvParameterSpec)100 IOException (java.io.IOException)74 SecretKeySpec (javax.crypto.spec.SecretKeySpec)58 NoSuchProviderException (java.security.NoSuchProviderException)56 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)49 CertificateException (java.security.cert.CertificateException)45 KeyStoreException (java.security.KeyStoreException)43 SecureRandom (java.security.SecureRandom)37 SecretKey (javax.crypto.SecretKey)34 BigInteger (java.math.BigInteger)31 KeyPairGenerator (java.security.KeyPairGenerator)27 UnrecoverableKeyException (java.security.UnrecoverableKeyException)27 X509Certificate (java.security.cert.X509Certificate)27