java - Android:无法解密值

标签 java android encryption rijndael

成功获得正确的加密值,但在解密该值(已加密)时遇到问题。

:123456

加密:ncSzDj4j8l44iM5qgaqHgA==

为什么我得到 java.lang.Exception: [decrypt] Invalid int: "Bo"?

是否有任何解决方案/建议,我们将不胜感激。谢谢

主 Activity .java

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;

    import java.net.URLDecoder;

    public class MainActivity extends AppCompatActivity {
        ApiCrypter3 apiCrypter;

    //123456
    //ncSzDj4j8l44iM5qgaqHgA==

      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            apiCrypter = new ApiCrypter3();
            try {
                byte[] encryptedRequest = this.apiCrypter.encrypt(value);
                String EncryptStr = new String(encryptedRequest, "UTF-8");
                Log.e("ENCRYPTION: ", EncryptStr.toString());

                String res = new String(this.apiCrypter.decrypt(EncryptStr), "UTF-8");
                res = URLDecoder.decode(res, "UTF-8");
                Log.e("DECRYPTION: ", res.toString());

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

ApiCrypter3.java

  package <your package name>;

    import android.util.Base64;
    import java.security.NoSuchAlgorithmException;
    import javax.crypto.Cipher;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;

    public class ApiCrypter3 {

    private byte[] sessionKey = {your 16 character key}; //Where you get this from is beyond the scope of this post
    private byte[] iv = {your 16 character value}; //Ditto
    private IvParameterSpec ivspec;
    private SecretKeySpec keyspec;
    private Cipher cipher;

    public ApiCrypter3()
    {
        ivspec = new IvParameterSpec(iv);
        keyspec = new SecretKeySpec(sessionKey, "AES");

        try {
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
    }

    public byte[] 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 =  Base64.encode(cipher.doFinal(text.getBytes("UTF-8")), Base64.DEFAULT);
        }
        catch (Exception e) {
            throw new Exception("[encrypt] " + e.getMessage());
        }
        return encrypted;
    }

    public byte[] 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 = Base64.decode(cipher.doFinal(code.getBytes()),Base64.DEFAULT);
            decrypted = Base64.decode(cipher.doFinal(hexToBytes(code)),Base64.DEFAULT);
        }
        catch (Exception e) {
            throw new Exception("[decrypt] " + e.getMessage());
        }
        return decrypted;
    }

    public static 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++) {
                //No effect
                //buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
                buffer[i]=Integer.valueOf(str.substring(i*2,i*2+2),16).byteValue();
                }
            return buffer;
        }
    }
}

日志:

04-29 16:51:26.399 10918-10918/com.test.com.encrytiondecryption E/ENCRYPTION:: ncSzDj4j8l44iM5qgaqHgA==
04-29 16:51:26.399 10918-10918/com.test.com.encrytiondecryption W/System.err: java.lang.Exception: [decrypt] Invalid int: "nc"
04-29 16:51:26.399 10918-10918/com.test.com.encrytiondecryption W/System.err:     at com.test.com.encrytiondecryption.ApiCrypter3.decrypt(ApiCrypter3.java:64)
04-29 16:51:26.399 10918-10918/com.test.com.encrytiondecryption W/System.err:     at com.test.com.encrytiondecryption.MainActivity.onCreate(MainActivity.java:41)

最佳答案

看起来异常是由 hexToBytes 函数中的这一行抛出的,然后在 decrypt 中捕获并重新抛出:

buffer[i]=Integer.valueOf(str.substring(i*2,i*2+2),16).byteValue();

问题是您传递给 hexToBytes 函数的字符串是 Base64 编码的,它不是十六进制字符串,因此将前两个字符作为整数读取会导致异常。

将 decrypt 中的行更改为:

decrypted = cipher.doFinal(Base64.decode(code,Base64.DEFAULT)); 

当你加密时,你先加密,然后再进行 Base64 编码,因此当你解密时,你应该按相反的顺序进行:Base64 解码,然后解密。

关于java - Android:无法解密值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36937917/

相关文章:

java - JVM 如何通过 JIT 运行 Java 应用程序生成的机器代码?

android - 我们如何创建动态 TextView ?

java - 如何通过 listView 中按下的按钮访问主 Activity 中的数据?

java - 用于加密/解密属性文件中的密码的安全解决方案

java - Apache Tomcat 上的应用程序抛出 HTTP 405 错误

java - 如何使用maven构建aspectj项目?

java - JSONObject 和 JSONArray 的区别

java - 正确处理 Intents 以修复 ActivityNotFoundException

java - BCrypt:有没有办法在数据库中插入已经加密的密码?

encryption - java.lang.IllegalArgumentException : bad base-64 when decrypting string