Java RSA解密-BadPaddingException:数据必须以零开头

Java RSA解密-BadPaddingException:数据必须以零开头,java,encryption,rsa,private-key,Java,Encryption,Rsa,Private Key,我正在写RSA加密/解密。 这是密码。 但当我使用私钥解密时,我得到了一个异常 public class RSACrypto { private static SecureRandom sr = new SecureRandom(); /** * @param rsabits * @return keyPair * @throws NoSuchAlgorithmException */ public static KeyPair

我正在写RSA加密/解密。 这是密码。 但当我使用私钥解密时,我得到了一个异常

public class RSACrypto {

    private static SecureRandom sr = new SecureRandom();

    /**
     * @param rsabits
     * @return keyPair
     * @throws NoSuchAlgorithmException
     */
    public static KeyPair newKeyPair(int rsabits) throws NoSuchAlgorithmException {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(rsabits, sr);
        return generator.generateKeyPair();
    }

    /**
     * @param key
     * @return key
     */
    public static byte[] pubKeyToBytes(PublicKey key) {
        return key.getEncoded(); // X509 for a public key
    }

    /**
     * @param key
     * @return key
     */
    public static byte[] privKeyToBytes(PrivateKey key) {
        return key.getEncoded(); // PKCS8 for a private key
    }

    /**
     * @param bytes
     * @return key
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     */
    public static PublicKey bytesToPubKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));
    }

    /**
     * @param bytes
     * @return key
     * @throws InvalidKeySpecException
     * @throws NoSuchAlgorithmException
     */
    public static PrivateKey bytesToPrivKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException {
        return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(bytes));
    }

    /**
     * @param input
     * @param key
     * @return encryptedText
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     */
    public static byte[] encryptWithPubKey(byte[] input, PublicKey key) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(input);
    }

    /**
     * @param input
     * @param key
     * @return decryptedText
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     */
    public static byte[] decryptWithPrivKey(byte[] input, PrivateKey key) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(input);
    }

    /**
     * @param plainText
     * @return encryptedText
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws NoSuchAlgorithmException
     * @throws NoSuchPaddingException
     * @throws UnsupportedEncodingException
     */
    public static String encrypt(String plainText) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException,
            UnsupportedEncodingException {
        KeyPair kp = newKeyPair(1 << 11); // 2048 bit RSA; might take a second to generate keys
        PublicKey pubKey = kp.getPublic();
        PrivateKey priKey = kp.getPrivate();
        System.out.println("Private Key: " + new BASE64Encoder().encode(privKeyToBytes(priKey)));
        byte[] cipherText = encryptWithPubKey(plainText.getBytes("UTF-8"), pubKey);
        return new BASE64Encoder().encode(cipherText);
    }

    /**
     * @param encrypted
     * @param privateKey
     * @return decryptedText
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     * @throws IOException
     * @throws InvalidKeyException
     * @throws IllegalBlockSizeException
     * @throws BadPaddingException
     * @throws NoSuchPaddingException
     */
    public static String decrypt(String encrypted, String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, InvalidKeyException, IllegalBlockSizeException,
            BadPaddingException, NoSuchPaddingException {
        PrivateKey privateKeyValue = bytesToPrivKey(new BASE64Decoder().decodeBuffer(privateKey));
        return new String(decryptWithPrivKey(new BASE64Decoder().decodeBuffer(encrypted), privateKeyValue), "UTF-8");
    }
}
有什么想法,请帮忙

更新

我是从不同班级打来的

String encryptedText = RSACrypto.encrypt("PLAIN TEXT"));

String privateKey = ""; //During encryption, it will print privatekey value, assigning the same here
String plaintext = RSACrypto.decrypt(encryptedText , privateKey);
在做了一点工作之后,我尝试不编码和解码Base64。很好用


我把base64搞砸了?没有得到任何线索

你的复制/粘贴肯定出错了。我编辑了你的代码,生成了一个不需要复制粘贴的(丑陋的)SSCE。改变的方法是:

public static StringPair encrypt(String plainText) 
    throws GeneralSecurityException, UnsupportedEncodingException {

  // Note: this is a very confusing way to say 2048
  KeyPair kp = newKeyPair(1 << 11); 

  PublicKey pubKey = kp.getPublic();
  PrivateKey priKey = kp.getPrivate();
  byte[] cipherText = encryptWithPubKey(plainText.getBytes("UTF-8"), pubKey);

  // Here I return both items, to remove copy/paste problems
  StringPair result = new StringPair();
  result.encryptedText = new BASE64Encoder().encode(cipherText);
  result.key = new BASE64Encoder().encode(privKeyToBytes(priKey));
  return result;
}


private static class StringPair {
  public String encryptedText;
  public String key;
}


public static void main(String[] args) throws Exception {
  StringPair result = RSACrypto.encrypt("PLAIN TEXT");    
  System.out.println(RSACrypto.decrypt(result.encryptedText, result.key));       
}  
公共静态字符串对加密(字符串明文)
抛出GeneralSecurityException,UnsupportedEncodingException{
//注意:这是一个非常令人困惑的说法2048

KeyPair kp=newKeyPair(1)你能把你的代码转换成一个演示问题的代码吗?我想我已经做了同样的事情。简单的代码看起来没什么。在解密时,我发现生成的私钥和加密文本有错误。无法调试,最后寻求帮助。thanksIt不清楚如何将各种方法结合使用。如果你添加一个TLE <代码>主< /代码>方法到您所提供的代码中,然后我们可以执行该代码并查看相同的异常。然后我们可以帮助解决您的问题。1)考虑使用OAEP填充。PKCSα1 V1.5填充被破坏。2)RSA只能加密短文本,因此您可能需要混合加密。
public static StringPair encrypt(String plainText) 
    throws GeneralSecurityException, UnsupportedEncodingException {

  // Note: this is a very confusing way to say 2048
  KeyPair kp = newKeyPair(1 << 11); 

  PublicKey pubKey = kp.getPublic();
  PrivateKey priKey = kp.getPrivate();
  byte[] cipherText = encryptWithPubKey(plainText.getBytes("UTF-8"), pubKey);

  // Here I return both items, to remove copy/paste problems
  StringPair result = new StringPair();
  result.encryptedText = new BASE64Encoder().encode(cipherText);
  result.key = new BASE64Encoder().encode(privKeyToBytes(priKey));
  return result;
}


private static class StringPair {
  public String encryptedText;
  public String key;
}


public static void main(String[] args) throws Exception {
  StringPair result = RSACrypto.encrypt("PLAIN TEXT");    
  System.out.println(RSACrypto.decrypt(result.encryptedText, result.key));       
}