Android中的AES-256-CBC加密

时间:2017-06-16 11:17:59

标签: java android encryption cryptography aes

使用库https://github.com/fukata/AES-256-CBC-Example进行加密和解密并在Issue with key and iv on AES 256-CBC的帮助下。解密工作正常。 但是在加密的情况下会发生此错误

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.vinu.aessamble/com.example.vinu.aessamble.MainActivity}: java.lang.RuntimeException: javax.crypto.IllegalBlockSizeException:error:1e06c06a:Cipher functions:EVP_EncryptFinal_ex:DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH

我正在使用

String encrypted = AESUtil.encrypt("My PlainText to encrypt");

在AESUtils中

public static String encrypt(String src) {
    try {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, makeKey(), makeIv());
        return Base64.encodeBytes(cipher.doFinal(src.getBytes()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

将此用于PKCS5Padding加密正在运行,但无法使用该方法解密。使用NoPadding进行加密时,会显示上述错误。

public static String decrypt(String src) {
        String decrypted = "";
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
            byte[] array= Base64.decode(src);
            byte[] ivData=Arrays.copyOfRange(array,0,16);
            byte[] encrypted = Arrays.copyOfRange(array, 16, array.length);
            // Init the cipher with decrypt mode, key, and IV bytes array (no more hardcoded)
            cipher.init(Cipher.DECRYPT_MODE, makeKey(), new IvParameterSpec(ivData));
            // Decrypt same old way
            decrypted = new String(cipher.doFinal(encrypted));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return decrypted;
    }

makeIv()

static AlgorithmParameterSpec makeIv() {
        try {
            return new IvParameterSpec(sha256digest16(ENCRYPTION_IV));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

makeKey()

 static Key makeKey() {
        try {
            byte[] key = ENCRYPTION_KEY.getBytes("UTF-8");
            return new SecretKeySpec(key, "AES");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

Iv和关键是

private static final String ENCRYPTION_KEY = qwertyuiopasdfghjklzxcvbnmqwerty";
    private static final String ENCRYPTION_IV = "qbmocwtttkttpqvv";

帮我加密。

0 个答案:

没有答案