Search in sources :

Example 21 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project LuaViewSDK by alibaba.

the class DecryptUtil method aes.

/**
     * 使用aes256进行解密
     *
     * @param encrypted
     * @return
     */
public static byte[] aes(final byte[] keys, final byte[] encrypted) {
    try {
        //get cipher
        Cipher cipher = AppCache.getCache(CACHE_PUBLIC_KEY).get(Constants.PUBLIC_KEY_PATH_CIPHER);
        if (cipher == null) {
            final SecretKeySpec skeySpec = new SecretKeySpec(keys, ALGORITHM_AES);
            final IvParameterSpec ivParameterSpec = new IvParameterSpec(cIv);
            cipher = Cipher.getInstance(ALGORITHM_AES);
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
            //cache cipher
            AppCache.getCache(CACHE_PUBLIC_KEY).put(Constants.PUBLIC_KEY_PATH_CIPHER, cipher);
        }
        return cipher.doFinal(encrypted);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException)

Example 22 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project Openfire by igniterealtime.

the class AesEncryptor method cipher.

/**
	 * Symmetric encrypt/decrypt routine.
	 *
	 * @param attribute The value to be converted
	 * @param key The encryption key
	 * @param mode The cipher mode (encrypt or decrypt)
	 * @return The converted attribute, or null if conversion fails
	 */
private byte[] cipher(byte[] attribute, byte[] key, int mode) {
    byte[] result = null;
    try {
        // Create AES encryption key
        Key aesKey = new SecretKeySpec(key, "AES");
        // Create AES Cipher
        Cipher aesCipher = Cipher.getInstance(ALGORITHM);
        // Initialize AES Cipher and convert
        aesCipher.init(mode, aesKey, new IvParameterSpec(INIT_PARM));
        result = aesCipher.doFinal(attribute);
    } catch (Exception e) {
        log.error("AES cipher failed", e);
    }
    return result;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) Key(java.security.Key)

Example 23 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project Android-Terminal-Emulator by jackpal.

the class ShortcutEncryption method decrypt.

/**
     * Decrypts a string encrypted using this algorithm and verifies that the
     * contents have not been tampered with.
     *
     * @param encrypted The string to decrypt, in the format described above.
     * @param keys The keys to verify and decrypt with.
     * @return The decrypted data.
     *
     * @throws GeneralSecurityException if the data is invalid, verification fails, or an error occurs during decryption.
     */
public static String decrypt(String encrypted, Keys keys) throws GeneralSecurityException {
    Cipher cipher = Cipher.getInstance(ENC_SYSTEM);
    String[] data = COLON.split(encrypted);
    if (data.length != 3) {
        throw new GeneralSecurityException("Invalid encrypted data!");
    }
    String mac = data[0];
    String iv = data[1];
    String cipherText = data[2];
    // Verify that the ciphertext and IV haven't been tampered with first
    String dataToAuth = iv + ":" + cipherText;
    if (!computeMac(dataToAuth, keys.getMacKey()).equals(mac)) {
        throw new GeneralSecurityException("Incorrect MAC!");
    }
    // Decrypt the ciphertext
    byte[] ivBytes = decodeBase64(iv);
    cipher.init(Cipher.DECRYPT_MODE, keys.getEncKey(), new IvParameterSpec(ivBytes));
    byte[] bytes = cipher.doFinal(decodeBase64(cipherText));
    // Decode the plaintext bytes into a String
    CharsetDecoder decoder = Charset.defaultCharset().newDecoder();
    decoder.onMalformedInput(CodingErrorAction.REPORT);
    decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
    /*
         * We are coding UTF-8 (guaranteed to be the default charset on
         * Android) to Java chars (UTF-16, 2 bytes per char).  For valid UTF-8
         * sequences, then:
         *     1 byte in UTF-8 (US-ASCII) -> 1 char in UTF-16
         *     2-3 bytes in UTF-8 (BMP)   -> 1 char in UTF-16
         *     4 bytes in UTF-8 (non-BMP) -> 2 chars in UTF-16 (surrogate pair)
         * The decoded output is therefore guaranteed to fit into a char
         * array the same length as the input byte array.
         */
    CharBuffer out = CharBuffer.allocate(bytes.length);
    CoderResult result = decoder.decode(ByteBuffer.wrap(bytes), out, true);
    if (result.isError()) {
        /* The input was supposed to be the result of encrypting a String,
             * so something is very wrong if it cannot be decoded into one! */
        throw new GeneralSecurityException("Corrupt decrypted data!");
    }
    decoder.flush(out);
    return out.flip().toString();
}
Also used : CharsetDecoder(java.nio.charset.CharsetDecoder) GeneralSecurityException(java.security.GeneralSecurityException) CharBuffer(java.nio.CharBuffer) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) CoderResult(java.nio.charset.CoderResult)

Example 24 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project Openfire by igniterealtime.

the class K method A.

byte[] A(byte[] abyte0, int i, int j) {
    if (C == null)
        return abyte0;
    try {
        byte[] abyte1 = new byte[16];
        IvParameterSpec ivparameterspec = new IvParameterSpec(abyte1);
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        if (E == Encryption.ENCRYPT)
            cipher.init(1, C, ivparameterspec);
        if (E == Encryption.DECRYPT)
            cipher.init(2, C, ivparameterspec);
        return cipher.doFinal(abyte0, i, j);
    } catch (NoSuchAlgorithmException nosuchalgorithmexception) {
        D.error(nosuchalgorithmexception.getMessage(), nosuchalgorithmexception);
    } catch (NoSuchPaddingException nosuchpaddingexception) {
        D.error(nosuchpaddingexception.getMessage(), nosuchpaddingexception);
    } catch (InvalidKeyException invalidkeyexception) {
        D.error(invalidkeyexception.getMessage(), invalidkeyexception);
    } catch (BadPaddingException badpaddingexception) {
        D.error(badpaddingexception.getMessage(), badpaddingexception);
    } catch (IllegalBlockSizeException illegalblocksizeexception) {
        D.error(illegalblocksizeexception.getMessage(), illegalblocksizeexception);
    } catch (InvalidAlgorithmParameterException invalidalgorithmparameterexception) {
        D.error(invalidalgorithmparameterexception.getMessage(), invalidalgorithmparameterexception);
    }
    return null;
}
Also used : IvParameterSpec(javax.crypto.spec.IvParameterSpec)

Example 25 with IvParameterSpec

use of javax.crypto.spec.IvParameterSpec in project android-pbe by nelenkov.

the class Crypto method encrypt.

public static String encrypt(String plaintext, SecretKey key, byte[] salt) {
    try {
        Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
        byte[] iv = generateIv(cipher.getBlockSize());
        Log.d(TAG, "IV: " + toHex(iv));
        IvParameterSpec ivParams = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, key, ivParams);
        Log.d(TAG, "Cipher IV: " + (cipher.getIV() == null ? null : toHex(cipher.getIV())));
        byte[] cipherText = cipher.doFinal(plaintext.getBytes("UTF-8"));
        if (salt != null) {
            return String.format("%s%s%s%s%s", toBase64(salt), DELIMITER, toBase64(iv), DELIMITER, toBase64(cipherText));
        }
        return String.format("%s%s%s", toBase64(iv), DELIMITER, toBase64(cipherText));
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
Also used : GeneralSecurityException(java.security.GeneralSecurityException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher)

Aggregations

IvParameterSpec (javax.crypto.spec.IvParameterSpec)202 Cipher (javax.crypto.Cipher)130 SecretKeySpec (javax.crypto.spec.SecretKeySpec)96 SecretKey (javax.crypto.SecretKey)45 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)44 InvalidKeyException (java.security.InvalidKeyException)40 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)37 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)36 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)29 BadPaddingException (javax.crypto.BadPaddingException)27 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)23 KeyGenerator (javax.crypto.KeyGenerator)19 Key (java.security.Key)18 SecureRandom (java.security.SecureRandom)17 IOException (java.io.IOException)15 MyCipher (org.apache.harmony.crypto.tests.support.MyCipher)15 GeneralSecurityException (java.security.GeneralSecurityException)13 PBEParameterSpec (javax.crypto.spec.PBEParameterSpec)13 KeyParameter (org.bouncycastle.crypto.params.KeyParameter)13 UnsupportedEncodingException (java.io.UnsupportedEncodingException)11