簡體   English   中英

Java解密

[英]Java Decryption

我有一個問題

javax.crypto.Cipher

當我寫這行代碼時

    Cipher cipher;
    byte[] bytes = null;

    try
    {
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, generateAESKey128b(key));
        bytes = cipher.doFinal(input.getBytes("UTF-8"));
    }
    catch (NoSuchAlgorithmException e)
    {
        e.printStackTrace();
    }
    catch (NoSuchPaddingException e)
    {
        e.printStackTrace();
    }
    catch (InvalidKeyException e)
    {
        e.printStackTrace();
    }
    catch (UnsupportedEncodingException e)
    {
        e.printStackTrace();
    }
    catch (IllegalBlockSizeException e)
    {
        e.printStackTrace();
    }
    catch (BadPaddingException e)
    {
        e.printStackTrace();
    }

控制台給我這個錯誤

javax.crypto.IllegalBlockSizeException 
Input length must be multiple of 16 when    
decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at it.unitn.se.gym.backend.utils.Security.AES128Decode(Security.java:109)
at it.unitn.se.gym.backend.utils.Security.decode_AES128_Base64(Security.java:96)
at it.unitn.se.gym.backend.WebService.main(WebService.java:42)
Exception in thread "main" java.lang.NullPointerException
at it.unitn.se.gym.backend.utils.Security.decode_AES128_Base64(Security.java:97)
at it.unitn.se.gym.backend.WebService.main(WebService.java:42)

前兩行代碼是正確的,但是當我將byte []類型的屬性“ text”傳遞給doFinal函數時,它給了我錯誤。

有人可以告訴我為什么嗎?

解決了:

好,問題解決了

byte[] encrypted = UniversalBase64Encoder.decode(input);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, generateAESKey128b(key));
byte[] originalBytes = cipher.doFinal(encrypted);

這是我編寫的正確代碼

問題是您試圖解密未加密的字符串,並且這樣做違反了解密算法的假設(其輸入大小始終為16的倍數)。

這是一段代碼,它先加密然后解密一個字符串。 請注意,當打印加密的字符串時,它的長度為16個字節,即使輸入的字符串不是。 加密算法將輸入字符串填充出來,使其在加密之前為16字節的倍數。 現在,該16字節長的加密字符串是解密的有效輸入。

這種假設(加密的結果將是偶數大小)是非常標准的。 它不僅使解密/加密算法更易於編寫,而且還阻止了攻擊者知道您加密的事物的長度。

byte[] keyBytes = new byte[16];
keyBytes[0] = 1;
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
String input = "hello";
Cipher cipher;
byte[] bytes = null;
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
bytes = cipher.doFinal(input.getBytes("UTF-8"));

System.out.println("Encoded: "+Arrays.toString(bytes));

cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decoded = cipher.doFinal(bytes);

System.out.println("Decoded: "+new String(decoded, "UTF-8"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM