如何在android中的文本加密/解密中正确地将String转换为byte []? (错误 - WRONG_FINAL_BLOCK_LENGTH和IllegalBlockSizeException)

时间:2017-02-11 16:52:48

标签: java android encryption cryptography

您好我正在寻找堆栈溢出的答案。但任何一个都不行。请你帮助我好吗。

我想在android中加密和解密文本。我喜欢尽我所能做到这一点。首先我在java eclipse中编写了一些代码。它工作正常,但如果我将它转移到Android Studio有几个错误。

我必须将bytes []传递给String,因为我使用的是Firebase,这不支持使用bytes []

存储类对象

我尝试与this hint和其他许多人合作,但我只是失败了。

generateKey()

private static SecretKey generateKey() throws Exception
    {

        SecretKey  key = new SecretKeySpec(org.apache.commons.codec.binary.Hex.decodeHex(klucz.toCharArray()), "AES");         

        return key;
    }

加密(MSG)

public String encrypt(String messageText)
{
    try
    {
        byte[] data = messageText.getBytes("UTF-8");


        IvParameterSpec iv = new IvParameterSpec(iv_.getBytes("UTF-8"));
        SecretKeySpec key = (SecretKeySpec) generateKey();

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);


        byte[] textBytes = cipher.doFinal(messageText.getBytes("UTF-8"));
        String textString = Base64.encodeToString(textBytes, Base64.DEFAULT);

        return  textString;


    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

    return null;
}

解密(MSG)

   public String decrypt(String msgText)
    {
        try
        {
            byte[] data = msgText.getBytes("UTF-8");

            IvParameterSpec iv = new IvParameterSpec(iv_.getBytes("UTF-8"));
            SecretKeySpec skeySpec = (SecretKeySpec) generateKey();

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);


            byte[] original = cipher.doFinal(data);
            String textString = new String(original, "UTF-8");
            return textString;


        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

        return null;
    }

当我这样做时,我得到了错误:

  

WRONG_FINAL_BLOCK_LENGTH

当我尝试使用

将其更改为简单的AES时
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);

我收到了错误:

  

IllegalBlockSizeException:

1 个答案:

答案 0 :(得分:0)

您在加密后已在base64中对密文进行编码,但在解密之前尚未对其进行解码

删除decrypt()此代码

  byte[] data = msgText.getBytes("UTF-8");

并添加

byte[] data = Base64.decode(msgText, Base64.DEFAULT);

注意:请勿在{{1​​}}中使用AES。使用特定模式以避免Android中的意外结果