收到错误java.lang.ArrayIndexOutOfBoundsException:为RSA块数据太多太多、错误、数据、java

2023-09-07 23:30:15 作者:梦想快乐

我有私人PEM密钥文件,我使用签名的文件和数据加密。签名工作正常,我也能够验证另一个平台,但同时对数据进行加密,我收到以下错误:

I have private pem key file, I am using that file for signing and encrypting the data. Signing works fine and I am also able to verify on another platform, but while encrypting the data, I am getting the following the error:

04-04 09:55:51.821: E/AndroidRuntime(2725): FATAL EXCEPTION: Thread-102
04-04 09:55:51.821: E/AndroidRuntime(2725): java.lang.ArrayIndexOutOfBoundsException: too much data for RSA block
04-04 09:55:51.821: E/AndroidRuntime(2725):     at com.android.org.bouncycastle.jce.provider.JCERSACipher.engineDoFinal(JCERSACipher.java:457)
04-04 09:55:51.821: E/AndroidRuntime(2725):     at javax.crypto.Cipher.doFinal(Cipher.java:1106)
04-04 09:55:51.821: E/AndroidRuntime(2725):     at com.example.testsigning.MainActivity.rsaEncrypt(MainActivity.java:185)
04-04 09:55:51.821: E/AndroidRuntime(2725):     at com.example.testsigning.MainActivity$1.run(MainActivity.java:51)
04-04 09:55:51.821: E/AndroidRuntime(2725):     at java.lang.Thread.run(Thread.java:856)

以下是code片段中提取私人文件密钥:

Following is the code snippet to extract keys from private file:

// Read the file into string
String privKeyPEM = readFile("/mnt/sdcard/rsa_key");

privKeyPEM = privKeyPEM.replace("-----BEGIN RSA PRIVATE KEY-----", "");
privKeyPEM = privKeyPEM.replace("-----END RSA PRIVATE KEY-----", "");

// Base64 decode the data
byte[] encoded = Base64.decode(privKeyPEM, Base64.DEFAULT);

// PKCS8 decode the encoded RSA private key
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance("RSA");
mPrivKey = kf.generatePrivate(keySpec);

RSAPrivateCrtKey privk = (RSAPrivateCrtKey) mPrivKey;

RSAPublicKeySpec pubKeySpec = new java.security.spec.RSAPublicKeySpec(
        privk.getPublicExponent(), privk.getModulus());

mPubKey = kf.generatePublic(pubKeySpec);

和以下是code段加密数据:

And following is the code snippet to encrypt the data:

Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, mPubKey);
return cipher.doFinal("Hello World".getBytes()); // here is the problem

任何帮助解决这一问题将是非常美联社preciated。

Any help to resolve the issue would be highly appreciated.

问候,Yuvi

Regards, Yuvi

推荐答案

这个问题是从检索私有密钥的公共密钥,它应该是这样的:

The problem was in retrieving the public key from private key, It should be like this:

RSAPublicKeySpec pubKeySpec = new java.security.spec.RSAPublicKeySpec(
                privk.getModulus(), privk.getPublicExponent());

而不是:

RSAPublicKeySpec pubKeySpec = new java.security.spec.RSAPublicKeySpec(
        privk.getPublicExponent(), privk.getModulus());
 
精彩推荐
图片推荐