尝试解密时,我收到非法块大小异常

时间:2013-04-23 09:39:07

标签: java android exception encryption

我正在尝试使用DES加密/解密字符串,并且我成功加密了字符串,现在遇到解密字符串的问题。

这是我的代码:

public class DesEncryptor {
private static Key key;
private static Cipher cipher;

public static void keyGenerate() throws NoSuchAlgorithmException, NoSuchPaddingException{
    // get a DES cipher object and print the provider
    cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    KeyGenerator keyGen = KeyGenerator.getInstance("DES");
    keyGen.init(64);
    key = keyGen.generateKey();

}

public static String encryptSms(String sms) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, 
IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{



    //System.out.println( "\n" + cipher.getProvider().getInfo() );
    // encrypt using the key and the plaintext
    //  System.out.println( "\nStart encryption" );
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] cipherText = cipher.doFinal(sms.getBytes("UTF8"));
    // System.out.println( "Finish encryption: " );
    return( new String(cipherText, "UTF8") );
}

public static String decryptSms(String smsEncrypted) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, 
UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException
{
    // decrypt the ciphertext using the same key
    //System.out.println( "\nStart decryption" );

    cipher.init(Cipher.DECRYPT_MODE, key);
    byte[] newPlainText = cipher.doFinal(smsEncrypted.getBytes());
    //System.out.println( "Finish decryption: " );

    return( new String(newPlainText, "UTF8") );
}

}

首先,我调用第一个静态方法keyGenerate(),然后加密/解密数据。

我在尝试解密时获得illegalBlockSizeException,并且消息最后一个块在解密时未完成

0 个答案:

没有答案
相关问题