2013-11-28 215 views
1

如何解决以下问题。javax.servlet.ServletException:javax.crypto.IllegalBlockSizeException:使用填充密码解密时,输入长度必须是16的倍数

action.java

byte[] decValue = c.doFinal(decordedValue); 
account_bean fromBean = (account_bean) form; 
String account_name = fromBean.getName(); 
String encrypted_password = fromBean.getPassword(); 
String account_password = AESencrp.decrypt(encrypted_password.toString().trim()); 

AESencrp.java

import java.security.*; 
import javax.crypto.*; 
import javax.crypto.spec.SecretKeySpec; 
import sun.misc.*; 
public class AESencrp 
{ 
private static final String ALGO = "AES"; 
private static final byte[] keyValue = 
    new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't', 
'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' }; 
public static String encrypt(String Data) throws Exception 
{ 
    Key key = generateKey(); 
    Cipher c = Cipher.getInstance(ALGO); 
    c.init(Cipher.ENCRYPT_MODE, key); 
    byte[] encVal = c.doFinal(Data.getBytes()); 
    String encryptedValue = new BASE64Encoder().encode(encVal); 
    return encryptedValue.toString().trim(); 
} 
public static String decrypt(String encryptedData) throws Exception 
{ 
    Key key = generateKey(); 
    Cipher c = Cipher.getInstance(ALGO); 
    c.init(Cipher.DECRYPT_MODE, key); 
    byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData); 
    byte[] decValue = c.doFinal(decordedValue); 
    String decryptedValue = new String(decValue); 
    return decryptedValue.toString().trim(); 
} 
private static Key generateKey() throws Exception 
{ 
    Key key = new SecretKeySpec(keyValue, ALGO); 
    return key; 
} 
} 

错误:

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

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

Apache Tomcat/7.0.27 
+0

从未加密密码进入数据库,因为它们可以decripted。用单向哈希算法对它们进行哈希处理,然后对用户提供的哈希算法进行哈希处理,并检查它们是否相同:http://stackoverflow.com/a/14683668/1654265 –

回答

0

使用UTF8字符集对字符串进行编码/解码。

编码

Data.getBytes("UTF8") 

解码

new String(decValue, "UTF8") 
相关问题