Search in sources :

Example 1 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project remusic by aa112901.

the class AESTools method encrpty.

public static String encrpty(String paramString) {
    MessageDigest messageDigest = null;
    try {
        messageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    messageDigest.update(INPUT.getBytes());
    byte[] stringBytes = messageDigest.digest();
    StringBuilder stringBuilder = new StringBuilder(stringBytes.length * 2);
    for (int i = 0; i < stringBytes.length; i++) {
        stringBuilder.append(CHARS[((stringBytes[i] & 0xF0) >>> 4)]);
        stringBuilder.append(CHARS[(stringBytes[i] & 0xF)]);
    }
    String str = stringBuilder.toString();
    SecretKeySpec localSecretKeySpec = new SecretKeySpec(str.substring(str.length() / 2).getBytes(), "AES");
    Cipher localCipher;
    try {
        localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        localCipher.init(1, localSecretKeySpec, new IvParameterSpec(IV.getBytes()));
        return URLEncoder.encode(new String(BytesHandler.getChars(localCipher.doFinal(paramString.getBytes()))), "utf-8");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (InvalidAlgorithmParameterException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }
    return "";
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) MessageDigest(java.security.MessageDigest)

Example 2 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException in project OpenAM by OpenRock.

the class DataEncryptor method encryptWithAsymmetricKey.

/**
     * Encrypts the given data with an asymmetric key. The asymmetric 
     * encryption uses symmetric secret key for data encryption and sends
     * the secret key to the recipient by encrypting the same with given
     * transport key (publick key). 
     * @param data the data to be encrypted.
     * @param encryptionAlgorithm the encryption algorithm to be used.
     *        The encryption algorithm must be one of the supported
     *        algorithm by the underlying JCE encryption provider.
     *        Examples of encryption algorithms are "DES", "AES" etc. 
     * @param encryptionStrength the encryption strength for a given
     *                           encryption algorithm.
     * @param encKey the encryption key to be used. For PKI, this
     *               key should be public key of the intended recipient.  
     * @return the encrypted data in Base64 encoded format.
     */
public static String encryptWithAsymmetricKey(String data, String encryptionAlgorithm, int encryptionStrength, Key encKey) throws Exception {
    try {
        KeyGenerator keygen = KeyGenerator.getInstance(encryptionAlgorithm);
        if (encryptionStrength != 0) {
            keygen.init(encryptionStrength);
        }
        SecretKey sKey = keygen.generateKey();
        Cipher cipher = Cipher.getInstance(encryptionAlgorithm);
        cipher.init(Cipher.ENCRYPT_MODE, sKey);
        byte[] encData = cipher.doFinal(data.getBytes("UTF-8"));
        cipher = Cipher.getInstance(encKey.getAlgorithm());
        cipher.init(Cipher.WRAP_MODE, encKey);
        byte[] keyWrap = cipher.wrap(sKey);
        byte[] encDataPad = wrapKeyWithEncryptedData(encData, keyWrap);
        return Base64.encode(encDataPad);
    } catch (NoSuchAlgorithmException nse) {
        throw new Exception(nse.getMessage());
    } catch (NoSuchPaddingException npe) {
        throw new Exception(npe.getMessage());
    } catch (InvalidKeyException ike) {
        throw new Exception(ike.getMessage());
    } catch (UnsupportedEncodingException uae) {
        throw new Exception(uae.getMessage());
    }
}
Also used : SecretKey(javax.crypto.SecretKey) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) KeyGenerator(javax.crypto.KeyGenerator) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 3 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException 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 4 with NoSuchPaddingException

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

the class TestNonexpanding method runTest.

public void runTest(String algo, String mo, String pad) throws Exception {
    Cipher ci = null;
    SecretKey key = null;
    try {
        // Initialization
        Random rdm = new Random();
        byte[] plainText = new byte[128];
        rdm.nextBytes(plainText);
        ci = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
        KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
        kg.init(KEY_LENGTH);
        key = kg.generateKey();
        // encrypt
        ci.init(Cipher.ENCRYPT_MODE, key);
        byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
        int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
        ci.doFinal(cipherText, offset);
        // Comparison
        if (!(plainText.length == cipherText.length)) {
            // authentication tag and cipher text.
            if (mo.equalsIgnoreCase("GCM")) {
                GCMParameterSpec spec = ci.getParameters().getParameterSpec(GCMParameterSpec.class);
                int cipherTextLength = cipherText.length - spec.getTLen() / 8;
                if (plainText.length == cipherTextLength) {
                    return;
                }
            }
            System.out.println("Original length: " + plainText.length);
            System.out.println("Cipher text length: " + cipherText.length);
            throw new RuntimeException("Test failed!");
        }
    } catch (NoSuchAlgorithmException e) {
        //CFB7 and OFB150 are for negative testing
        if (!mo.equalsIgnoreCase("CFB7") && !mo.equalsIgnoreCase("OFB150")) {
            System.out.println("Unexpected NoSuchAlgorithmException with mode: " + mo);
            throw new RuntimeException("Test failed!");
        }
    } catch (NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | InvalidParameterSpecException | ShortBufferException | IllegalBlockSizeException | BadPaddingException e) {
        System.out.println("Test failed!");
        throw e;
    }
}
Also used : NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) GCMParameterSpec(javax.crypto.spec.GCMParameterSpec) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) Random(java.util.Random) ShortBufferException(javax.crypto.ShortBufferException) Cipher(javax.crypto.Cipher) InvalidParameterSpecException(java.security.spec.InvalidParameterSpecException) NoSuchProviderException(java.security.NoSuchProviderException) KeyGenerator(javax.crypto.KeyGenerator)

Example 5 with NoSuchPaddingException

use of javax.crypto.NoSuchPaddingException 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

NoSuchPaddingException (javax.crypto.NoSuchPaddingException)258 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)236 InvalidKeyException (java.security.InvalidKeyException)215 Cipher (javax.crypto.Cipher)186 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)180 BadPaddingException (javax.crypto.BadPaddingException)179 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)119 SecretKeySpec (javax.crypto.spec.SecretKeySpec)90 IOException (java.io.IOException)83 IvParameterSpec (javax.crypto.spec.IvParameterSpec)66 SecretKey (javax.crypto.SecretKey)45 KeyStoreException (java.security.KeyStoreException)40 CertificateException (java.security.cert.CertificateException)40 UnrecoverableKeyException (java.security.UnrecoverableKeyException)35 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)30 NoSuchProviderException (java.security.NoSuchProviderException)27 UnsupportedEncodingException (java.io.UnsupportedEncodingException)26 GCMParameterSpec (javax.crypto.spec.GCMParameterSpec)18 FileNotFoundException (java.io.FileNotFoundException)16 SecureRandom (java.security.SecureRandom)16