Search in sources :

Example 96 with BadPaddingException

use of javax.crypto.BadPaddingException in project android_frameworks_base by ResurrectionRemix.

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)

Example 97 with BadPaddingException

use of javax.crypto.BadPaddingException in project android_frameworks_base by ResurrectionRemix.

the class LockSettingsService method resetKeyStore.

@Override
public void resetKeyStore(int userId) throws RemoteException {
    checkWritePermission(userId);
    if (DEBUG)
        Slog.v(TAG, "Reset keystore for user: " + userId);
    int managedUserId = -1;
    String managedUserDecryptedPassword = null;
    final List<UserInfo> profiles = mUserManager.getProfiles(userId);
    for (UserInfo pi : profiles) {
        // Unlock managed profile with unified lock
        if (pi.isManagedProfile() && !mLockPatternUtils.isSeparateProfileChallengeEnabled(pi.id) && mStorage.hasChildProfileLock(pi.id)) {
            try {
                if (managedUserId == -1) {
                    managedUserDecryptedPassword = getDecryptedPasswordForTiedProfile(pi.id);
                    managedUserId = pi.id;
                } else {
                    // Should not happen
                    Slog.e(TAG, "More than one managed profile, uid1:" + managedUserId + ", uid2:" + pi.id);
                }
            } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
                Slog.e(TAG, "Failed to decrypt child profile key", e);
            }
        }
    }
    try {
        // Clear all the users credentials could have been installed in for this user.
        for (int profileId : mUserManager.getProfileIdsWithDisabled(userId)) {
            for (int uid : SYSTEM_CREDENTIAL_UIDS) {
                mKeyStore.clearUid(UserHandle.getUid(profileId, uid));
            }
        }
    } finally {
        if (managedUserId != -1 && managedUserDecryptedPassword != null) {
            if (DEBUG)
                Slog.v(TAG, "Restore tied profile lock");
            tieProfileLockToParent(managedUserId, managedUserDecryptedPassword);
        }
    }
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) UserInfo(android.content.pm.UserInfo) 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)

Example 98 with BadPaddingException

use of javax.crypto.BadPaddingException in project android_frameworks_base by ResurrectionRemix.

the class LockSettingsService method setLockPasswordInternal.

private void setLockPasswordInternal(String password, String savedCredential, int userId) throws RemoteException {
    byte[] currentHandle = getCurrentHandle(userId);
    if (password == null) {
        clearUserKeyProtection(userId);
        getGateKeeperService().clearSecureUserId(userId);
        mStorage.writePasswordHash(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 (FileNotFoundException e) {
            Slog.i(TAG, "Child profile key not found");
        } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | CertificateException | IOException e) {
            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, password, userId);
    if (enrolledHandle != null) {
        CredentialHash willStore = new CredentialHash(enrolledHandle, CredentialHash.VERSION_GATEKEEPER);
        setUserKeyProtection(userId, password, doVerifyPassword(password, willStore, true, 0, userId, null));
        mStorage.writePasswordHash(enrolledHandle, userId);
        fixateNewestUserKeyAuth(userId);
        onUserLockChanged(userId);
    } else {
        throw new RemoteException("Failed to enroll password");
    }
}
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 99 with BadPaddingException

use of javax.crypto.BadPaddingException in project jdk8u_jdk by JetBrains.

the class EngineInputRecord method decrypt.

/*
     * Pass the data down if it's internally cached, otherwise
     * do it here.
     *
     * If internal data, data is decrypted internally.
     *
     * If external data(app), return a new ByteBuffer with data to
     * process.
     */
ByteBuffer decrypt(Authenticator authenticator, CipherBox box, ByteBuffer bb) throws BadPaddingException {
    if (internalData) {
        // MAC is checked during decryption
        decrypt(authenticator, box);
        return tmpBB;
    }
    BadPaddingException reservedBPE = null;
    int tagLen = (authenticator instanceof MAC) ? ((MAC) authenticator).MAClen() : 0;
    int cipheredLength = bb.remaining();
    if (!box.isNullCipher()) {
        try {
            // apply explicit nonce for AEAD/CBC cipher suites if needed
            int nonceSize = box.applyExplicitNonce(authenticator, contentType(), bb);
            // decrypt the content
            if (box.isAEADMode()) {
                // DON'T encrypt the nonce_explicit for AEAD mode
                bb.position(bb.position() + nonceSize);
            }
            // The explicit IV for CBC mode can be decrypted.
            // Note that the CipherBox.decrypt() does not change
            // the capacity of the buffer.
            box.decrypt(bb, tagLen);
            // We don't actually remove the nonce.
            bb.position(nonceSize);
        } catch (BadPaddingException bpe) {
            // RFC 2246 states that decryption_failed should be used
            // for this purpose. However, that allows certain attacks,
            // so we just send bad record MAC. We also need to make
            // sure to always check the MAC to avoid a timing attack
            // for the same issue. See paper by Vaudenay et al and the
            // update in RFC 4346/5246.
            //
            // Failover to message authentication code checking.
            reservedBPE = bpe;
        }
    }
    // cipher suites.
    if ((authenticator instanceof MAC) && (tagLen != 0)) {
        MAC signer = (MAC) authenticator;
        int macOffset = bb.limit() - tagLen;
        // cipher and CBC block cipher.
        if (bb.remaining() < tagLen) {
            // negative data length, something is wrong
            if (reservedBPE == null) {
                reservedBPE = new BadPaddingException("bad record");
            }
            // set offset of the dummy MAC
            macOffset = cipheredLength - tagLen;
            bb.limit(cipheredLength);
        }
        // Run MAC computation and comparison on the payload.
        if (checkMacTags(contentType(), bb, signer, false)) {
            if (reservedBPE == null) {
                reservedBPE = new BadPaddingException("bad record MAC");
            }
        }
        // constant time of MAC computation and comparison on each record.
        if (box.isCBCMode()) {
            int remainingLen = calculateRemainingLen(signer, cipheredLength, macOffset);
            // we use small buffer size in the future.
            if (remainingLen > buf.length) {
                // unlikely to happen, just a placehold
                throw new RuntimeException("Internal buffer capacity error");
            }
            // Won't need to worry about the result on the remainder. And
            // then we won't need to worry about what's actual data to
            // check MAC tag on.  We start the check from the header of the
            // buffer so that we don't need to construct a new byte buffer.
            checkMacTags(contentType(), buf, 0, remainingLen, signer, true);
        }
        bb.limit(macOffset);
    }
    // Is it a failover?
    if (reservedBPE != null) {
        throw reservedBPE;
    }
    return bb.slice();
}
Also used : BadPaddingException(javax.crypto.BadPaddingException)

Example 100 with BadPaddingException

use of javax.crypto.BadPaddingException in project jdk8u_jdk by JetBrains.

the class RSACore method crtCrypt.

/**
     * RSA private key operations with CRT. Algorithm and variable naming
     * are taken from PKCS#1 v2.1, section 5.1.2.
     */
private static byte[] crtCrypt(byte[] msg, RSAPrivateCrtKey key, boolean verify) throws BadPaddingException {
    BigInteger n = key.getModulus();
    BigInteger c0 = parseMsg(msg, n);
    BigInteger c = c0;
    BigInteger p = key.getPrimeP();
    BigInteger q = key.getPrimeQ();
    BigInteger dP = key.getPrimeExponentP();
    BigInteger dQ = key.getPrimeExponentQ();
    BigInteger qInv = key.getCrtCoefficient();
    BigInteger e = key.getPublicExponent();
    BigInteger d = key.getPrivateExponent();
    BlindingRandomPair brp;
    if (ENABLE_BLINDING) {
        brp = getBlindingRandomPair(e, d, n);
        c = c.multiply(brp.u).mod(n);
    }
    // m1 = c ^ dP mod p
    BigInteger m1 = c.modPow(dP, p);
    // m2 = c ^ dQ mod q
    BigInteger m2 = c.modPow(dQ, q);
    // h = (m1 - m2) * qInv mod p
    BigInteger mtmp = m1.subtract(m2);
    if (mtmp.signum() < 0) {
        mtmp = mtmp.add(p);
    }
    BigInteger h = mtmp.multiply(qInv).mod(p);
    // m = m2 + q * h
    BigInteger m = h.multiply(q).add(m2);
    if (ENABLE_BLINDING) {
        m = m.multiply(brp.v).mod(n);
    }
    if (verify && !c0.equals(m.modPow(e, n))) {
        throw new BadPaddingException("RSA private key operation failed");
    }
    return toByteArray(m, getByteLength(n));
}
Also used : BigInteger(java.math.BigInteger) BadPaddingException(javax.crypto.BadPaddingException)

Aggregations

BadPaddingException (javax.crypto.BadPaddingException)120 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)103 InvalidKeyException (java.security.InvalidKeyException)80 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)70 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)69 Cipher (javax.crypto.Cipher)53 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)45 IOException (java.io.IOException)39 KeyStoreException (java.security.KeyStoreException)25 UnrecoverableKeyException (java.security.UnrecoverableKeyException)25 CertificateException (java.security.cert.CertificateException)25 SecretKey (javax.crypto.SecretKey)25 IvParameterSpec (javax.crypto.spec.IvParameterSpec)25 SecretKeySpec (javax.crypto.spec.SecretKeySpec)23 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)17 RemoteException (android.os.RemoteException)15 ShortBufferException (javax.crypto.ShortBufferException)14 KeyGenerator (javax.crypto.KeyGenerator)13 UnsupportedEncodingException (java.io.UnsupportedEncodingException)12 FileNotFoundException (java.io.FileNotFoundException)11