RSA 加密:Java 和 Android 的区别 [英] RSA Encryption: Difference between Java and Android
问题描述
我在 Android 上使用 RSA 加密用户名和密码,并在服务器(tomcat 6,java 1.6)上解密它们.安卓加密:
I am using RSA to encrypt username and password on Android and decrypt them on server (tomcat 6, java 1.6). Android Encryption:
PublicKey pubKey = readPublicKeyFromFile(mod, ex);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
Java Tomcat 解密:
Java Tomcat Decryption:
PrivateKey pubKey = readPrivateKeyFromFile(mod, ex);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
如果我在 android 之外使用 android 部分(只是在一个主要方法中),它工作正常.但不在我的 android(模拟器)中.在服务器端,我收到以下错误:
If I use the android part OUTSIDE android (Just in a main method) it works fine. But not inside my android (Emulator). On de server side I get the following error:
javax.crypto.BadPaddingException: Blocktype mismatch: 0
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:311)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:255)
at com.sun.crypto.provider.RSACipher.a(DashoA13*..)
at com.sun.crypto.provider.RSACipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
我将 mod 和 ex 保留为 BigIntegers 常量,因此我不会将它们写入文件.我知道java1.6和java 1.5加密有区别,所以都是用java 1.6编译的.
I keep the mod and ex as BigIntegers constants so I don't write them in to a file. I know that there are difference between java1.6 and java 1.5 encryption, so both are compiled with java 1.6.
一些调试信息:
在 android 中调试期间,我可以看到 pubKey 包含十六进制的模数和指数.如果我在 main 方法中调试(同样的代码),我可以看到 pubKey 包含十进制的模数和指数.
During debug in android I can see that pubKey contains modulus and exponent in hexadecimal. And if I debug in a main method (again the same code) I can see that pubKey contains modulus and exponent in decimal.
我做错了什么?
谢谢
推荐答案
我在 Android 2.2+ 中进行 RSA 加密并在 tomcat 6 java 1.6 服务器上解密.
Im doing RSA Encrypt in Android 2.2+ and decrypt on a tomcat 6 java 1.6 server.
我遇到了这个确切的问题,到处阅读,部分感谢 @Femi 的回答,我找到了我需要的东西.
I was getting this exact problem, reading all over the place and in part thanks to @Femi 's answer I came across what I needed.
解决方案是对密码使用以下算法规范:
The solution was to use the folowing algorithm specification for the Cipher:
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
这适用于从 Android 和 BlackBerry 智能手机进行加密.我知道这个问题已经过去四个月了,但以防万一其他人遇到这个问题.
This works doing encryption from both Android and BlackBerry smartphones. I know its been four months since the question was asked, but just in case someone else goes through this problem.
这篇关于RSA 加密:Java 和 Android 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!