Search in sources :

Example 11 with InvalidAlgorithmParameterException

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

the class AndroidKeyStoreKeyPairGeneratorSpi method initialize.

@SuppressWarnings("deprecation")
@Override
public void initialize(AlgorithmParameterSpec params, SecureRandom random) throws InvalidAlgorithmParameterException {
    resetAll();
    boolean success = false;
    try {
        if (params == null) {
            throw new InvalidAlgorithmParameterException("Must supply params of type " + KeyGenParameterSpec.class.getName() + " or " + KeyPairGeneratorSpec.class.getName());
        }
        KeyGenParameterSpec spec;
        boolean encryptionAtRestRequired = false;
        int keymasterAlgorithm = mOriginalKeymasterAlgorithm;
        if (params instanceof KeyGenParameterSpec) {
            spec = (KeyGenParameterSpec) params;
        } else if (params instanceof KeyPairGeneratorSpec) {
            // Legacy/deprecated spec
            KeyPairGeneratorSpec legacySpec = (KeyPairGeneratorSpec) params;
            try {
                KeyGenParameterSpec.Builder specBuilder;
                String specKeyAlgorithm = legacySpec.getKeyType();
                if (specKeyAlgorithm != null) {
                    // Spec overrides the generator's default key algorithm
                    try {
                        keymasterAlgorithm = KeyProperties.KeyAlgorithm.toKeymasterAsymmetricKeyAlgorithm(specKeyAlgorithm);
                    } catch (IllegalArgumentException e) {
                        throw new InvalidAlgorithmParameterException("Invalid key type in parameters", e);
                    }
                }
                switch(keymasterAlgorithm) {
                    case KeymasterDefs.KM_ALGORITHM_EC:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        // MD5 was never offered for Android Keystore for ECDSA.
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        break;
                    case KeymasterDefs.KM_ALGORITHM_RSA:
                        specBuilder = new KeyGenParameterSpec.Builder(legacySpec.getKeystoreAlias(), KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY);
                        // Authorized to be used with any digest (including no digest).
                        specBuilder.setDigests(KeyProperties.DIGEST_NONE, KeyProperties.DIGEST_MD5, KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA224, KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384, KeyProperties.DIGEST_SHA512);
                        // Authorized to be used with any encryption and signature padding
                        // schemes (including no padding).
                        specBuilder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE, KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1, KeyProperties.ENCRYPTION_PADDING_RSA_OAEP);
                        specBuilder.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1, KeyProperties.SIGNATURE_PADDING_RSA_PSS);
                        // Disable randomized encryption requirement to support encryption
                        // padding NONE above.
                        specBuilder.setRandomizedEncryptionRequired(false);
                        break;
                    default:
                        throw new ProviderException("Unsupported algorithm: " + mKeymasterAlgorithm);
                }
                if (legacySpec.getKeySize() != -1) {
                    specBuilder.setKeySize(legacySpec.getKeySize());
                }
                if (legacySpec.getAlgorithmParameterSpec() != null) {
                    specBuilder.setAlgorithmParameterSpec(legacySpec.getAlgorithmParameterSpec());
                }
                specBuilder.setCertificateSubject(legacySpec.getSubjectDN());
                specBuilder.setCertificateSerialNumber(legacySpec.getSerialNumber());
                specBuilder.setCertificateNotBefore(legacySpec.getStartDate());
                specBuilder.setCertificateNotAfter(legacySpec.getEndDate());
                encryptionAtRestRequired = legacySpec.isEncryptionRequired();
                specBuilder.setUserAuthenticationRequired(false);
                spec = specBuilder.build();
            } catch (NullPointerException | IllegalArgumentException e) {
                throw new InvalidAlgorithmParameterException(e);
            }
        } else {
            throw new InvalidAlgorithmParameterException("Unsupported params class: " + params.getClass().getName() + ". Supported: " + KeyGenParameterSpec.class.getName() + ", " + KeyPairGeneratorSpec.class.getName());
        }
        mEntryAlias = spec.getKeystoreAlias();
        mEntryUid = spec.getUid();
        mSpec = spec;
        mKeymasterAlgorithm = keymasterAlgorithm;
        mEncryptionAtRestRequired = encryptionAtRestRequired;
        mKeySizeBits = spec.getKeySize();
        initAlgorithmSpecificParameters();
        if (mKeySizeBits == -1) {
            mKeySizeBits = getDefaultKeySize(keymasterAlgorithm);
        }
        checkValidKeySize(keymasterAlgorithm, mKeySizeBits);
        if (spec.getKeystoreAlias() == null) {
            throw new InvalidAlgorithmParameterException("KeyStore entry alias not provided");
        }
        String jcaKeyAlgorithm;
        try {
            jcaKeyAlgorithm = KeyProperties.KeyAlgorithm.fromKeymasterAsymmetricKeyAlgorithm(keymasterAlgorithm);
            mKeymasterPurposes = KeyProperties.Purpose.allToKeymaster(spec.getPurposes());
            mKeymasterBlockModes = KeyProperties.BlockMode.allToKeymaster(spec.getBlockModes());
            mKeymasterEncryptionPaddings = KeyProperties.EncryptionPadding.allToKeymaster(spec.getEncryptionPaddings());
            if (((spec.getPurposes() & KeyProperties.PURPOSE_ENCRYPT) != 0) && (spec.isRandomizedEncryptionRequired())) {
                for (int keymasterPadding : mKeymasterEncryptionPaddings) {
                    if (!KeymasterUtils.isKeymasterPaddingSchemeIndCpaCompatibleWithAsymmetricCrypto(keymasterPadding)) {
                        throw new InvalidAlgorithmParameterException("Randomized encryption (IND-CPA) required but may be violated" + " by padding scheme: " + KeyProperties.EncryptionPadding.fromKeymaster(keymasterPadding) + ". See " + KeyGenParameterSpec.class.getName() + " documentation.");
                    }
                }
            }
            mKeymasterSignaturePaddings = KeyProperties.SignaturePadding.allToKeymaster(spec.getSignaturePaddings());
            if (spec.isDigestsSpecified()) {
                mKeymasterDigests = KeyProperties.Digest.allToKeymaster(spec.getDigests());
            } else {
                mKeymasterDigests = EmptyArray.INT;
            }
            // Check that user authentication related parameters are acceptable. This method
            // will throw an IllegalStateException if there are issues (e.g., secure lock screen
            // not set up).
            KeymasterUtils.addUserAuthArgs(new KeymasterArguments(), mSpec.isUserAuthenticationRequired(), mSpec.getUserAuthenticationValidityDurationSeconds(), mSpec.isUserAuthenticationValidWhileOnBody(), mSpec.isInvalidatedByBiometricEnrollment());
        } catch (IllegalArgumentException | IllegalStateException e) {
            throw new InvalidAlgorithmParameterException(e);
        }
        mJcaKeyAlgorithm = jcaKeyAlgorithm;
        mRng = random;
        mKeyStore = KeyStore.getInstance();
        success = true;
    } finally {
        if (!success) {
            resetAll();
        }
    }
}
Also used : KeyPairGeneratorSpec(android.security.KeyPairGeneratorSpec) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) KeymasterArguments(android.security.keymaster.KeymasterArguments) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) ProviderException(java.security.ProviderException) DERBitString(com.android.org.bouncycastle.asn1.DERBitString)

Example 12 with InvalidAlgorithmParameterException

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

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);
        notifyActivePasswordMetricsAvailable(null, 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 13 with InvalidAlgorithmParameterException

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

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

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

the class SpecTest method main.

public static void main(String[] args) {
    int failCount = 0;
    // Test key size.
    int size = Integer.parseInt(args[0]);
    try {
        KeyPairGenerator kpg1 = KeyPairGenerator.getInstance(KEYALG, PROVIDER);
        kpg1.initialize(new RSAKeyGenParameterSpec(size, RSAKeyGenParameterSpec.F4));
        if (!specTest(kpg1.generateKeyPair(), RSAKeyGenParameterSpec.F4)) {
            failCount++;
        }
        KeyPairGenerator kpg2 = KeyPairGenerator.getInstance(KEYALG, PROVIDER);
        kpg2.initialize(new RSAKeyGenParameterSpec(size, RSAKeyGenParameterSpec.F0));
        if (!specTest(kpg2.generateKeyPair(), RSAKeyGenParameterSpec.F0)) {
            failCount++;
        }
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException ex) {
        ex.printStackTrace(System.err);
        failCount++;
    }
    if (failCount != 0) {
        throw new RuntimeException("There are " + failCount + " tests failed.");
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) RSAKeyGenParameterSpec(java.security.spec.RSAKeyGenParameterSpec) KeyPairGenerator(java.security.KeyPairGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException)

Example 15 with InvalidAlgorithmParameterException

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

the class LockSettingsService method verifyTiedProfileChallenge.

@Override
public VerifyCredentialResponse verifyTiedProfileChallenge(String password, boolean isPattern, long challenge, int userId) throws RemoteException {
    checkPasswordReadPermission(userId);
    if (!isManagedProfileWithUnifiedLock(userId)) {
        throw new RemoteException("User id must be managed profile with unified lock");
    }
    final int parentProfileId = mUserManager.getProfileParent(userId).id;
    // Unlock parent by using parent's challenge
    final VerifyCredentialResponse parentResponse = isPattern ? doVerifyPattern(password, true, challenge, parentProfileId, null) : doVerifyPassword(password, true, challenge, parentProfileId, null);
    if (parentResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
        // Failed, just return parent's response
        return parentResponse;
    }
    try {
        // Unlock work profile, and work profile with unified lock must use password only
        return doVerifyPassword(getDecryptedPasswordForTiedProfile(userId), true, challenge, userId, null);
    } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
        Slog.e(TAG, "Failed to decrypt child profile key", e);
        throw new RemoteException("Unable to get tied profile token");
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) VerifyCredentialResponse(com.android.internal.widget.VerifyCredentialResponse) 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)

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