猿问

给定最终块未正确填充

我正在尝试实现基于密码的加密算法,但出现此异常:


javax.crypto.BadPaddingException:给定最终块,未正确填充


可能是什么问题?(我是Java新手。)


这是我的代码:


public class PasswordCrypter {


    private Key key;


    public PasswordCrypter(String password)  {

        try{

            KeyGenerator generator;

            generator = KeyGenerator.getInstance("DES");

            SecureRandom sec = new SecureRandom(password.getBytes());

            generator.init(sec);

            key = generator.generateKey();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }



    public byte[] encrypt(byte[] array) throws CrypterException {

        try{

            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

            cipher.init(Cipher.ENCRYPT_MODE, key);


            return cipher.doFinal(array);

        } catch (Exception e) { 

            e.printStackTrace();

        }

        return null;

    }


    public byte[] decrypt(byte[] array) throws CrypterException{

        try{

            Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

            cipher.init(Cipher.DECRYPT_MODE, key);


            return cipher.doFinal(array);

        } catch(Exception e ){

            e.printStackTrace();

        }

        return null;

    }

}

(JUnit测试)


public class PasswordCrypterTest {


    private static final byte[] MESSAGE = "Alpacas are awesome!".getBytes();

    private PasswordCrypter[] passwordCrypters;

    private byte[][] encryptedMessages;


    @Before

    public void setUp() {

        passwordCrypters = new PasswordCrypter[] {

            new PasswordCrypter("passwd"),

            new PasswordCrypter("passwd"),

            new PasswordCrypter("otherPasswd")

        };


        encryptedMessages = new byte[passwordCrypters.length][];

        for (int i = 0; i < passwordCrypters.length; i++) {

            encryptedMessages[i] = passwordCrypters[i].encrypt(MESSAGE);

        }

    }

慕容3067478
浏览 733回答 3
3回答
随时随地看视频慕课网APP
我要回答