如何在RSA算法中修复BadPaddingException

时间:2019-05-06 17:02:05

标签: java android rsa

我对Android中的RSA算法有疑问。我试图用公开密钥在Android Studio中加密一个密码,然后我想用Netbean的私有密钥解密该密码,但是我遇到了错误。

Android中的代码:

try {

       rsa.setPublicKeyString(...);
} catch ()
       ...      
}

String secure =null;

try {
       secure = rsa.Encrypt(password);
} catch ()
       ...
}
user = new User(name, secure);

netbean中的代码:

try {
    rsa.setPrivateKeyString(".....");
} catch (){
       ...
}

try {
   String g = rsa.Decrypt("....");

} catch (){
      ...
}

方法:

public String Encrypt(String plain) throws NoSuchAlgorithmException,NoSuchPaddingException, InvalidKeyException,IllegalBlockSizeException, BadPaddingException, InvalidKeySpecException, UnsupportedEncodingException, NoSuchProviderException {

        byte[] encryptedBytes; 

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, this.PublicKey);
        encryptedBytes = cipher.doFinal(plain.getBytes());

        return bytesToString(encryptedBytes);

    }

public String Decrypt(String result) throws NoSuchAlgorithmException,NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

        byte[] decryptedBytes;

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, this.PrivateKey);
        decryptedBytes = cipher.doFinal(stringToBytes(result));
        return new String(decryptedBytes);
    }

Netbean错误:

javax.crypto.BadPaddingException: Decryption error
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at org.ieselrincon.convalidaciones.bd.RSA.Decrypt(RSA.java:101)
    at org.ieselrincon.convalidaciones.bd.main.main(main.java:30)

如果我将代码放在同一文件中,则它可以正常工作,这意味着,如果加密和解密步骤在同一文件中,则它在Netbean和Android中也可以正常工作。问题是,如果我将Netbean代码放在​​Android Studio中,而将Android Studio代码放在Netbean中,则可以正常工作,但输出却像“ a56DFGs6dgf8d6659hsd2nb8tgsd2nhG5H55h2njgmydqqb29nRESULT”这样的奇怪输出。解密后的密码显示在一个很大的字符串的末尾。

0 个答案:

没有答案