我有一个功能,成功读取的OpenSSL格式的私钥:RSA - BouncyCastle的PEMReader返回PEMKeyPair代替AsymmetricCipherKeyPair阅读私钥
static AsymmetricKeyParameter readPrivateKey(string privateKeyFileName)
{
AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(privateKeyFileName))
keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
return keyPair.Private;
}
,并返回一个AsymmetricKeyParameter然后用于解密的加密文本。
下面是解密代码:
public static byte[] Decrypt3(byte[] data, string pemFilename)
{
string result = "";
try {
AsymmetricKeyParameter key = readPrivateKey(pemFilename);
RsaEngine e = new RsaEngine();
e.Init(false, key);
//byte[] cipheredBytes = GetBytes(encryptedMsg);
//Debug.Log (encryptedMsg);
byte[] cipheredBytes = e.ProcessBlock(data, 0, data.Length);
//result = Encoding.UTF8.GetString(cipheredBytes);
//return result;
return cipheredBytes;
} catch (Exception e) {
Debug.Log ("Exception in Decrypt3: " + e.Message);
return GetBytes(e.Message);
}
}
使用充气城堡库C#这些工作,我得到正确的解密文本。然而,当我将它添加到Java时,PEMParser.readObject()返回一个类型为PEMKeyPair的对象,而不是AsymmetricCipherKeyPair,并且java抛出一个异常,试图强制转换它。我检查了C#,它实际上返回了AsymmetricCipherKeyPair。
我不知道为什么Java的行为不同,但我希望这里的某个人可以帮助如何投射这个对象或读取私钥文件并成功解密。我在C#和Java代码中使用了相同的公钥和私钥文件,所以我不认为这些错误来自他们。
这里引用的Java版本的我怎么读专用密钥:
public static String readPrivateKey3(String pemFilename) throws FileNotFoundException, IOException
{
AsymmetricCipherKeyPair keyParam = null;
AsymmetricKeyParameter keyPair = null;
PEMKeyPair kp = null;
//PrivateKeyInfo pi = null;
try {
//var fileStream = System.IO.File.OpenText(pemFilename);
String absolutePath = "";
absolutePath = Encryption.class.getProtectionDomain().getCodeSource().getLocation().getPath();
absolutePath = absolutePath.substring(0, (absolutePath.lastIndexOf("/")+1));
String filePath = "";
filePath = absolutePath + pemFilename;
File f = new File(filePath);
//return filePath;
FileReader fileReader = new FileReader(f);
PEMParser r = new PEMParser(fileReader);
keyParam = (AsymmetricCipherKeyPair) r.readObject();
return keyParam.toString();
}
catch (Exception e) {
return "hello: " + e.getMessage() + e.getLocalizedMessage() + e.toString();
//return e.toString();
//return pi;
}
}
我会尽力谢谢 – c0d3Junk13 2013-04-05 11:58:09
是的,那绝对奏效!非常感谢。你几乎救了我的命! :) – c0d3Junk13 2013-04-05 17:42:53