Search in sources :

Example 81 with BadPaddingException

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

the class AndroidKeyStoreCipherSpiBase method engineDoFinal.

@Override
protected final byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException {
    if (mCachedException != null) {
        throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(mCachedException);
    }
    try {
        ensureKeystoreOperationInitialized();
    } catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
        throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
    }
    byte[] output;
    try {
        flushAAD();
        byte[] additionalEntropy = KeyStoreCryptoOperationUtils.getRandomBytesToMixIntoKeystoreRng(mRng, getAdditionalEntropyAmountForFinish());
        output = mMainDataStreamer.doFinal(input, inputOffset, inputLen, // no signature involved
        null, additionalEntropy);
    } catch (KeyStoreException e) {
        switch(e.getErrorCode()) {
            case KeymasterDefs.KM_ERROR_INVALID_INPUT_LENGTH:
                throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
            case KeymasterDefs.KM_ERROR_INVALID_ARGUMENT:
                throw (BadPaddingException) new BadPaddingException().initCause(e);
            case KeymasterDefs.KM_ERROR_VERIFICATION_FAILED:
                throw (AEADBadTagException) new AEADBadTagException().initCause(e);
            default:
                throw (IllegalBlockSizeException) new IllegalBlockSizeException().initCause(e);
        }
    }
    resetWhilePreservingInitState();
    return output;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) KeyStoreException(android.security.KeyStoreException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) AEADBadTagException(javax.crypto.AEADBadTagException)

Example 82 with BadPaddingException

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

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 83 with BadPaddingException

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

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 84 with BadPaddingException

use of javax.crypto.BadPaddingException in project mobile-center-sdk-android by Microsoft.

the class CryptoTest method failsToEncrypt.

@Test
public void failsToEncrypt() throws Exception {
    CryptoUtils cryptoUtils = new CryptoUtils(mContext, mCryptoFactory, Build.VERSION_CODES.KITKAT);
    when(mCipher.doFinal(any(byte[].class))).thenThrow(new BadPaddingException());
    String data = "anythingThatWouldMakeTheCipherFailForSomeReason";
    String encryptedData = cryptoUtils.encrypt(data);
    assertEquals(data, encryptedData);
    CryptoUtils.DecryptedData decryptedData = cryptoUtils.decrypt(encryptedData);
    assertEquals(data, decryptedData.getDecryptedData());
    assertNull(decryptedData.getNewEncryptedData());
}
Also used : BadPaddingException(javax.crypto.BadPaddingException) Matchers.anyString(org.mockito.Matchers.anyString) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 85 with BadPaddingException

use of javax.crypto.BadPaddingException in project GNS by MobilityFirst.

the class CryptoUtils method signDigestOfMessageSecretKey.

/**
     * @param guidEntry
     * @param message
     * @return Signature encoded as a hex string
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws SignatureException
     * @throws UnsupportedEncodingException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws NoSuchPaddingException
     */
public static String signDigestOfMessageSecretKey(GuidEntry guidEntry, String message) throws ClientException {
    try {
        SecretKey secretKey = SessionKeys.getOrGenerateSecretKey(guidEntry.getPublicKey(), guidEntry.getPrivateKey());
        MessageDigest md = getMessageDigestInstance();
        byte[] digest;
        // FIXME: The reason why we use CHARSET should be more throughly documented here.
        // This might be important for folks writing clients in other languages.
        byte[] body = message.getBytes(GNSProtocol.CHARSET.toString());
        synchronized (md) {
            digest = md.digest(body);
        }
        assert (digest != null);
        Cipher cipher = getCipherInstance();
        byte[] signature;
        synchronized (cipher) {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            signature = cipher.doFinal(digest);
        }
        SessionKeys.SecretKeyCertificate skCert = SessionKeys.getSecretKeyCertificate(guidEntry.getPublicKey());
        byte[] encodedSKCert = skCert.getEncoded(false);
        // arun: Combining them like this because the rest of the GNS code seems
        // poorly organized to add more signature related fields in a systematic
        // manner.
        byte[] combined = new byte[Short.BYTES + signature.length + Short.BYTES + encodedSKCert.length];
        ByteBuffer.wrap(combined).putShort((short) signature.length).put(signature).putShort((short) encodedSKCert.length).put(encodedSKCert);
        // FIXME: The reason why we use CHARSET should be more throughly documented here.
        return new String(combined, GNSProtocol.CHARSET.toString());
    } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchPaddingException | BadPaddingException | UnsupportedEncodingException | IllegalBlockSizeException e) {
        throw new ClientException("Error encoding message message (using secretkey)", e);
    }
}
Also used : SessionKeys(edu.umass.cs.utils.SessionKeys) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) Cipher(javax.crypto.Cipher) ClientException(edu.umass.cs.gnscommon.exceptions.client.ClientException) MessageDigest(java.security.MessageDigest)

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