Getting javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher?

后端 未结 4 1545
猫巷女王i
猫巷女王i 2020-12-01 16:25

Using tomcat, I have two web-applications i.e app1 and app2. I sent url from app1 in encrypted form (using below code) to app2 . Then at app2 I decrypted this encrypted url

4条回答
  •  孤城傲影
    2020-12-01 16:42

    I would suggest instead of working with Strings work with byte[] itself. I am guessing some bytes are modified when you convert it into a String. Following code works for me -

    public static final String ENC_KEY = "abcdefghijklmnop";
    public static final String DATA = "Hello World";
    
    public static void test(){
    
        try {
            Cipher c = Cipher.getInstance("AES");
    
            SecretKeySpec secretKeySpec = new SecretKeySpec(ENC_KEY.getBytes("UTF-8"), "AES");
    
            c.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encBytes = c.doFinal(DATA.getBytes("UTF-8"));
            String encStr =  new String(encBytes, "UTF-8");
            System.out.println("Encrypted String: " + encStr);
    
            c.init(Cipher.DECRYPT_MODE, secretKeySpec);
            String decStr = new String(c.doFinal(encBytes),"UTF-8");
            System.out.println("Decrypted String: " + decStr);
    
        } catch (Exception ex) {
            System.out.println("Error in encrypting data");
            ex.printStackTrace();
        }
    }
    

    but if you change it to -

    public static void test(){
    
        try {
            Cipher c = Cipher.getInstance("AES");
    
            SecretKeySpec secretKeySpec = new SecretKeySpec(ENC_KEY.getBytes("UTF-8"), "AES");
    
            c.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encBytes = c.doFinal(DATA.getBytes("UTF-8"));
            String encStr =  new String(encBytes, "UTF-8");
            System.out.println("Encrypted String: " + encStr);
    
            c.init(Cipher.DECRYPT_MODE, secretKeySpec);
            String decStr = new String(c.doFinal(encStr.getBytes("UTF-8")),"UTF-8");
            System.out.println("Decrypted String: " + decStr);
    
        } catch (Exception ex) {
            System.out.println("Error in encrypting data");
            ex.printStackTrace();
        }
    }
    

    You will get

    javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:936) at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847) at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446) at javax.crypto.Cipher.doFinal(Cipher.java:2164) at com.osfg.HelloWorld.test(HelloWorld.java:38) at com.osfg.HelloWorld.main(HelloWorld.java:22)

    Notice

    String decStr = new String(c.doFinal(encBytes),"UTF-8");
    VRS
    String decStr = new String(c.doFinal(encStr.getBytes("UTF-8")),"UTF-8");
    

提交回复
热议问题