我正在尝试(但失败)创建一个从PEM编码的私钥构造AsymmetricKeyParameter
的方法。我该如何完成这个方法?
似乎较早版本的BouncyCastle
有一个pemReader.ReadObject()
方法,其结果可以投放,但不再存在。
我尝试了使用PrivateKeyFactory
,PrivateKeyInfo
,Asn1Object
以及其他10种其他类型的各种组合,但都在某些时候抛出异常。
static AsymmetricKeyParameter ReadPrivateKeyFromPemEncodedString(string pemEncodedKey)
{
AsymmetricKeyParameter result = null;
using (var stringReader = new StringReader(pemEncodedKey))
{
var pemReader = new PemReader(stringReader);
var pemObject = pemReader.ReadPemObject();
// WHAT NEXT???
}
return result;
}
以下是我正在测试的PEM编码密钥:
-----BEGIN RSA PRIVATE KEY-----
MIIEoAIBAAKCAQEAk0AmagKx285Ufbri/olc+f3WagL1Ho+DrYdDSbuU7cJAq+uD
9xGvvP9m2JavSP4wO9i9pB/cmCFMPoIj3oGJt1/cnLb/U2juneOw6Uo0N3F8TXdy
XfZNAIPhq/jw0YfIypTFTTvFkKXfTArIwW/bQBW8/dujFR8i5CxPjRKRDOBEy0PP
OLJDD0iUr9GX/h/EO4jQ7B/GszjhPiPx+gJCilaMY+jrSczjxpsKOXzpZEdT1NqM
rzgvIZPHYhQzAiw9vQzov3vezDwKgKcRrUixZ2B8uiEQNn7Wa2QzWF3vL+6CGflF
NYQcc0leDQBe86baYhCollouP4jfaH9KcMkYYwIBJQKCAQA7sjkWOHGeTLp4KSuX
n3i4X/z6i5POHoF9s2B31mzPF2ZTiP4l5JNadWELsrXDpVHTEq2/E9X4fDOqo3ZT
SUWrNLNiIKyzHLPDd/uc2OS8h/QfZ8aUy6KtLovrxclps5aXURG3hu86pBxBbCff
t7nACNAT42ugx28CjoEdhBFKaCNcw/S3gZOkcotVdDUTCB+epveXNybAoZcuVNtu
Y84hx+st8i0sXY+vpIJ8HOanbpdS/Q9UqDGNvg1zBlvnJ7PGOO4Jnc0EOa1Eoym2
vJNItDAkK59KPKjuBLWTvTz/XLrZirkY57BQgUKnXHU6YGI7bvu8+iDnNAP1C90U
/MllAoGBANstq/L7WOgcOhfbWEmcd59/vBtDbgf0pNwYyhmpIrG2SD6XaljQvOvo
2/2oqNzCG+xZbTnbdkODRIXMDGcCzVkQAEkNvwWYHxb2XHUOhUPr+4zNfGtnJ1gv
o7w6FVI3tD4buSmhcFZUGpNyzSbS+6FdXD37qjOFCPKcJMCY4BSPAoGBAKv9CdXw
Ksyhr62sWqlU2F9FhjDNS9afJ5A7mZjrPraAusVsOkUtwsij9g74SH5agQNIUnFH
NBwNenW+kbYahX6Q5pjNN5s6weG+2kbK8kZyuYo+Fuix0u6bTnL2IH35zP+hYWQS
YM7yNDdBpH1deTWlTVL7vnZeEK/WTldw8PDtAoGAZLQekjwh7hrOlVbxNpP/nE9y
Gl1AZIUpJtr1ErV+pK2yfZ+D454tScvastDzo7MhlhtABdOJXUomZvzjGpKVs0yK
gm4ZfxxhT71NEzAvZGWBajTmI4JsBexf/Iljvf3rB8eMbRLSv+Fz/o6xSTCBc6dv
khmvEMCVaIzuSqca2QMCgYAue714F2WDafghGdNQXB7NpBZuDfjSONpCqFMGvB7J
ipNX87y4wEJ7apWHgV+zcmgOuZm9wDeY4QxXLJYViqCev2DrBwgcHbfcJb5z/3/A
A1S9lD2K/6DK3d3Z4afqsjdnrxNnJ4/JOoqnJn971BLr53yupOdeQu/A0iMC4EEe
hQKBgBCJteVdDk/0gK5c/++q88VIYplEDeDCiO2nIjXK7kHrm0q3DuUsr3D6VOjL
VUViiU2nBKn40R8tNnxagPkL/uec0kZMGnnFsJLLKd48DGr34nQjsrGare0Pr8yo
3uwlkKwtDUg5Zf2vLIIKqcX6tvHSQ2Zc57dAdAPvhpM5TtDJ
-----END RSA PRIVATE KEY-----
答案 0 :(得分:0)
这是一个有效的解决方案:
using Org.BouncyCastle.OpenSsl;
private static AsymmetricKeyParameter ReadPrivateKeyFromPemEncodedString(string pemEncodedKey)
{
AsymmetricKeyParameter result;
using (var stringReader = new StringReader(pemEncodedKey))
{
var pemReader = new PemReader(stringReader);
var pemObject = pemReader.ReadObject();
result = ((AsymmetricCipherKeyPair)pemObject).Private;
}
return result;
}