我已经尝试了几天没有成功。
StackOverflow中有很多类似的问题,甚至其中两个与我的完全相同,但未得到解答和未解决:
1)Convert PHP RSA PublicKey into Android PublicKey
2)Android: how to decrypt an openssl encrypted file with RSA key?
我的情况是:
我有一些使用RSA加密的文本(本人未加密)。我在res/raw文件夹中有一个“public.key”文件,其中包含解密该文件所需的公钥(与用于加密邮件的私钥有关的公钥),格式类似于以下示例:
我看到了许多有关如何解密RSA文本的示例,例如以下示例:
public static byte[] decryptRSA( PublicKey key, byte[] text) throws Exception
{
byte[] dectyptedText = null;
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
return dectyptedText;
}
但是我的问题是,如何从文件中获取正确的PublicKey实例?没有任何例子。
如果我只是尝试:
InputStream is = getResources().openRawResource(R.raw.public);
DataInputStream dis = new DataInputStream(is);
byte [] keyBytes = new byte [(int) is.available()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(spec);
我在返回语句中收到InvalidKeyException。
我需要解码Hex或Base64吗?公钥的第一行和最后一行不是问题(带有“---- BEGIN PUBLIC KEY ----”的行等等)吗?
也许我们可以在StackOverflow中第一次得到正确的答案:-)
最佳答案
终于解决了!!!鼓声,小号和迷人的交响声!!!
public static byte[] decryptRSA(Context mContext, byte[] message) throws Exception {
// reads the public key stored in a file
InputStream is = mContext.getResources().openRawResource(R.raw.sm_public);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = br.readLine()) != null)
lines.add(line);
// removes the first and last lines of the file (comments)
if (lines.size() > 1 && lines.get(0).startsWith("-----") && lines.get(lines.size()-1).startsWith("-----")) {
lines.remove(0);
lines.remove(lines.size()-1);
}
// concats the remaining lines to a single String
StringBuilder sb = new StringBuilder();
for (String aLine: lines)
sb.append(aLine);
String keyString = sb.toString();
Log.d("log", "keyString:"+keyString);
// converts the String to a PublicKey instance
byte[] keyBytes = Base64.decodeBase64(keyString.getBytes("utf-8"));
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey key = keyFactory.generatePublic(spec);
// decrypts the message
byte[] dectyptedText = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(Base64.decodeBase64(message));
return dectyptedText;
}
解决方案是对Base64进行解码,不仅解码从文件读取的公钥,还解码已加密的消息本身!
顺便说一句,我以@Nikolay建议的方式从文件中读取了公钥(再次为tnx)。
非常感谢大家的帮助。 StackOverflow令人毛骨悚然!
关于android - Android:使用存储在文件中的公钥解密RSA文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11532989/