加密数据时出错

时间:2017-12-18 10:09:57

标签: android encryption

尝试通过以下代码加密和解密数据:

    public class MCrypt {


   // private String iv = "";
    private IvParameterSpec ivspec;
    private SecretKeySpec keyspec;
    private Cipher cipher;

    //private String SecretKey = "";
Context context;
    public MCrypt(Context context)
    {
        this.context=context;
        ivspec = new IvParameterSpec(context.getString(R.string.iv).getBytes());
        keyspec = new SecretKeySpec(context.getString(R.string.secretkey).getBytes(), "AES");
        try {
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public MCrypt(Context context, String key)
    {
        this.context=context;
        ivspec = new IvParameterSpec(context.getString(R.string.iv).getBytes());

        keyspec = new SecretKeySpec(key.getBytes(), "AES");

        try {
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public String encrypt(String text) throws Exception
    {
        if(text == null || text.length() == 0)
            throw new Exception("Empty string");

        byte[] encrypted = null;

        try {
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);

            encrypted = cipher.doFinal(padString(text).getBytes());
        } catch (Exception e)
        {
            throw new Exception("[encrypt] " + e.getMessage());
        }

        return bytesToHex(encrypted);
    }

    public String decrypt(String code) throws Exception
    {
        if(code == null || code.length() == 0)
            throw new Exception("Empty string");

        byte[] decrypted = null;

        try {
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);

            decrypted = cipher.doFinal(hexToBytes(code));
        } catch (Exception e)
        {
            e.printStackTrace();
            throw new Exception("[decrypt] " + e.getMessage());
        }
        return Html.fromHtml(new String(decrypted)).toString().trim();
    }



    public String bytesToHex(byte[] data)
    {
        if (data==null)
        {
            return null;
        }

        int len = data.length;
        String str = "";
        for (int i=0; i<len; i++) {
            if ((data[i]&0xFF)<16)
                str = str + "0" + Integer.toHexString(data[i]&0xFF);
            else
                str = str + Integer.toHexString(data[i]&0xFF);
        }
        return str;
    }


    public static byte[] hexToBytes(String str) {
        if (str==null) {
            return null;
        } else if (str.length() < 2) {
            return null;
        } else {
            int len = str.length() / 2;
            byte[] buffer = new byte[len];
            for (int i=0; i<len; i++) {
                buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
            }
            return buffer;
        }
    }



    private static String padString(String source)
    {
        char paddingChar = ' ';
        int size = 16;
        int x = source.length() % size;
        int padLength = size - x;

        for (int i = 0; i < padLength; i++)
        {
            source += paddingChar;
        }

        return source;
    }
}

现在,当我使用少量字符串时,它就像一个魅力。但现在突然间它因为这个错误而停止了大字符串的工作:

   java.lang.Exception: [encrypt] error:0607F08A:digital envelope routines:EVP_EncryptFinal_ex:data not multiple of block length
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at com.app.aspire_pd.Other.MCrypt.encrypt(MCrypt.java:75)
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at com.app.aspire_pd.AsyncTask.APIHit.HitAPI(APIHit.java:320)
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at com.app.aspire_pd.AsyncTask.HitAPI.doInBackground(HitAPI.java:98)
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at com.app.aspire_pd.AsyncTask.HitAPI.doInBackground(HitAPI.java:24)
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-18 15:32:42.057 21834-22054/com.app.aspire_pd W/System.err:     at java.lang.Thread.run(Thread.java:818)

看到here将我的加密线更改为

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

正在工作。

1 个答案:

答案 0 :(得分:0)

更改您的代码

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding","SC");