安卓棒棒糖系统下的RSA解密

7

我在使用RSA解密时遇到了错误。 这段代码在安卓4.4 KitKat上可以运行,但是同样的应用在安卓5.0 Lollipop上无法工作。

KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulusBytes), new BigInteger(exponentBytes));
RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);

byte[] decrypted = null;
try {
    // get an RSA cipher object and print the provider
    final Cipher cipher = Cipher.getInstance("RSA/None/NoPadding");

    // decrypt the text using the public key
    cipher.init(Cipher.DECRYPT_MODE, publicKey);
    decrypted = cipher.doFinal(area_fissa_byte);

} catch (Exception ex) {
    ex.printStackTrace();
    Log.d("error","error");
}

错误信息为:java.security.SignatureException: error:04067084:rsa routines:RSA_EAY_PUBLIC_DECRYPT:data too large for modulus
我的SDK目标版本是: <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" /> 适用于Android 4.4。
您知道问题出在哪里吗?
编辑: 我注意到我有两个不同长度的公钥!!! Android 5:我有382/383位(太小了) Android 4.4:我有384位(可以)
编辑2: 我发现在TLS/SSL方面,Android 5.0存在差异:https://developer.android.com/about/versions/android-5.0-changes.html 但我不知道如何解决这个问题。

我在某处读到,一些旧版本的安卓存在SSL初始化不正确的问题,但已经得到修复,所以这是否可能与此有关? - Yazan
@Yazan 我不知道。我发现可能的提供程序是不同的(Provider[] providers = Security.getProviders();),但应用程序始终使用“AndroidOpenSSL”。区别在于对于Android 4.4,提供程序的大小为127,而对于Android 5,则为143。那么我有两个不同的密钥大小。您是否知道在Android 5上是否有一种方法可以使用与Android 4.4相同的KeyFactory呢? - invisibleProgrammer
1个回答

1

有一个错误是您创建RSAPublicKeySpec的方式:

new RSAPublicKeySpec(new BigInteger(modulusBytes), new BigInteger(exponentBytes));

如果modulusBytes或exponentBytes的第一位为1,则该数字将被解释为负值。

在使用RSA数字和BigInteger时,始终使用构造函数BigInteger(int signum,byte [] magnitude),并使用signum = 1指定数字为正数:

new RSAPublicKeySpec(new BigInteger(1, modulusBytes), new BigInteger(1, exponentBytes));


非常感谢!这解决了问题!@Robert 但我不明白为什么在Android KitKat上可以正常工作...无论如何,谢谢! - invisibleProgrammer
第一个比特位为1的概率为50%。也许在KitKat上,您有一个RSA密钥,模数和指数的第一个比特位设置为0?在这种情况下,您的代码将正常工作。 - Robert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接