我有私人 pem 密钥文件,我正在使用该文件对数据进行签名和加密。签名工作正常,我也可以在另一个平台上进行验证,但是在加密数据时,我收到以下错误:
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)
以下是从私有文件中提取密钥的代码片段:
// 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);
以下是加密数据的代码片段:
Cipher cipher = Cipher.getInstance("RSA/None/OAEPWithSHA1AndMGF1Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, mPubKey);
return cipher.doFinal("Hello World".getBytes()); // here is the problem
任何解决该问题的帮助将不胜感激。
问候, 尤维