"javax.crypto.BadPaddingException:数据必须从零开始"异常

spe*_*lly -2 java rsa

我在解密字符串时遇到了上述异常.

以下是我的代码:

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;

public class EncryptAndDecrypt {

    public static Cipher createCipher () throws Exception{

            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

            return cipher;
    }
    public static KeyPair generateKey () throws  NoSuchAlgorithmException{

            KeyPairGenerator keyGen = KeyPairGenerator.getInstance ("RSA");
            keyGen.initialize(1024);
            KeyPair key = keyGen.generateKeyPair();

            return key;
    }
    public static byte [] encrypt (String  str, Cipher cip, KeyPair key) {

        byte [] cipherText = null;
        try {

            byte [] plainText = str.getBytes("UTF8");
            cip.init(Cipher.ENCRYPT_MODE, key.getPublic());
            cipherText = cip.doFinal(plainText);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherText;
    }
    public static String decrypt (byte [] c, Cipher cip, KeyPair key) throws Exception {

        cip.init(Cipher.DECRYPT_MODE, key.getPrivate());

        byte [] decryptedPlainText = cip.doFinal (c);// exception occurred here
        String decryptedPlainStr = new String (decryptedPlainText);

        return decryptedPlainStr;
    }
}


//separate class below to use the encrypt method

public class EncryptionApp {

    public static void main (String [] args) {

        getEncrypted();
    }
    public static byte [] getEncrypted () {

        byte [] encyptedByte = null;
        try {
            String plainText = "der";
            Cipher cip = Safety.createCipher();
            KeyPair key = Safety.generateKey();
            encyptedByte = Safety.useRSA(plainText, cip, key);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

         return encyptedByte;
    }
}

// Another class to use the decrypt method 

public class DecryptionApp {

    public static void main(String[] args) {
        System.out.println (useDecrypted () );
    }
    public static byte[] useDecrypted () {

        byte [] decryptedText = null;
        try {
            Cipher cip = EncryptAndDecrypt.createCipher();
            KeyPair key = EncryptAndDecrypt.generateKey();
            decryptedText = EncryptAndDecrypt.decrypt(EncryptionApp.getEncrypted(),cip,key);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    return decryptedText;
    }
}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 8

您已经在"javax.crypto.BadPaddingException:数据必须从零开始"异常中询问了相同的问题,我给出了答案:您使用了两个不同的密钥对:一个用于加密,另一个用于解密.那不行.我甚至给了你一个代码示例,显示如果使用相同的密钥对,一切运行正常.

KeyPairGenerator.generateKeyPair()生成密钥对.两次调用此方法将获得两个不同的密钥对:它在内部使用随机数生成器来生成始终不同的密钥对.

您必须生成一次密钥对,将其存储在变量中,并使用此变量进行加密和解密.

您应该阅读您正在使用的类和方法的文档.generateKeyPair文档说:

这将在每次调用时生成一个新的密钥对.