RSA加密Android中的Android和解密:javax.crypto.BadPaddingException:解密错误

时间:2016-03-29 19:32:17

标签: java android encryption cryptography rsa

我有一个Android应用程序,它使用RSA 2048位密钥加密文本。

加密和解密在应用程序上正常运行。

我的问题是我正在尝试对应用程序进行加密,然后将密码发送到外部Java程序进行解密。

以下是如何完成的:

public static PrivateKey getPrivateKey(String key) {
    try {
        /* Add PKCS#8 formatting */
        byte[] byteKey = Base64.getDecoder().decode(key.getBytes());
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new ASN1Integer(0));
        ASN1EncodableVector v2 = new ASN1EncodableVector();
        v2.add(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.rsaEncryption.getId()));
        v2.add(DERNull.INSTANCE);
        v.add(new DERSequence(v2));
        v.add(new DEROctetString(byteKey));
        ASN1Sequence seq = new DERSequence(v);
        byte[] privKey = seq.getEncoded("DER");

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(keySpec);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

public static String decrypt(String cipherString,PrivateKey privateKey){
    try{
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] plainByte = cipher.doFinal(Base64.getDecoder().decode(cipherString));
        return Base64.getEncoder().encodeToString(plainByte);
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

但是当我试图解密密码时,我收到了错误:

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 RSA.decrypt(RSA.java:94)
    at RSA.main(RSA.java:116)

我错过了什么?

更新 我在Java中重新生成了一对新密钥,并摆脱了部分:

/* Add PKCS#8 formatting */
byte[] byteKey = Base64.getDecoder().decode(key.getBytes());
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(new ASN1Integer(0));
ASN1EncodableVector v2 = new ASN1EncodableVector();
v2.add(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.rsaEncryption.getId()));
v2.add(DERNull.INSTANCE);
v.add(new DERSequence(v2));
v.add(new DEROctetString(byteKey));
ASN1Sequence seq = new DERSequence(v);
byte[] privKey = seq.getEncoded("DER");

但我遇到了同样的错误!

1 个答案:

答案 0 :(得分:3)

您的填充未设置或设置错误。

尝试将Cipher cipher = Cipher.getInstance("RSA");更改为Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

如果这不起作用,您可以看到here用于其他填充模式。

相关问题