【发布时间】:2013-04-04 22:51:46
【问题描述】:
我有一个函数可以成功读取 openssl 格式的私钥:
static AsymmetricKeyParameter readPrivateKey(string privateKeyFileName)
{
AsymmetricCipherKeyPair keyPair;
using (var reader = File.OpenText(privateKeyFileName))
keyPair = (AsymmetricCipherKeyPair)new PemReader(reader).ReadObject();
return keyPair.Private;
}
并返回一个非对称密钥参数,然后用于解密加密文本。
下面是解密代码:
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# 中使用 bouncy castle 库工作,我得到正确的解密文本。但是,当我将它添加到 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;
}
}
【问题讨论】:
标签: java openssl rsa bouncycastle private-key