使用C#从我的Java证书中获取公钥

时间:2013-01-21 17:35:33

标签: c# x509certificate

没有BounceyCastle

我有我的证书,GetPublicKey()值不是家庭所需的Java方面。

使用DSA加密的X509Certificate2对象的证书。使用makecert创建

Convert.ToBase64String(cert.GetPublicKey())返回

AoGAeaKLPS4ktxULg3YQL0ePphF08tKsddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9Lg
JU4JOA27snO3fCsPAVkmJ0O2pbxn+wzT7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx9
2UyuDzoQTGxgCrPccQPjUgY=

Convert.ToBase64String(cert.RawData)返回

MIICxjCCAoagAwIBAgIQbdIpaaU9rZdA+wJKA+mUfDAJBgcqhkjOOAQDMBYxFDASBgNVBAMTC0RT
QSBSb290IENBMB4XDTEzMDExMDE3MTAzNVoXDTM5MTIzMTIzNTk1OVowFDESMBAGA1UEAxMJVXNl
ciBOYW1lMIIBtzCCASwGByqGSM44BAEwggEfAoGBALWn4Iyvn7LFkV9ULoZtwJ8J1c+ibsbhjPiw
+xUgRW2LAZV2/Lv89W1jCprNkf87tN/ogMT/1VSIOo7ff/tqVRTWPVJ1ZMrR9VOnF2k/Sorg8Cmr
sAClsSWrACKIwK2XKJGWTU4oMLxvYcu85+yQ4nWLofgA/+WARrJ/rk2aUSZ3AhUAlqPLNh6JZkpD
G/OXKzhsZFUiDrkCgYEAoICjHltWOgN8/2uyAaMTNrBuJfi/HM9AWe5B8m9HDfl1K6Qx2Ni6tbYP
uFtvHdGnoqqn46l7eY+xjpi5GEydvkPtAQKmTDGcSh6vtnTeNV15Hafg5pXUKw1OisIr/bpx/KIk
cgCtSo6qC5IhDzeZXnfJYcE+8U+O6hEr5dwByN4DgYQAAoGAeaKLPS4ktxULg3YQL0ePphF08tKs
ddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9LgJU4JOA27snO3fCsPAVkmJ0O2pbxn+wzT
7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx92UyuDzoQTGxgCrPccQPjUgajWTBXMAwG
A1UdEwEB/wQCMAAwRwYDVR0BBEAwPoAQmhMLkJ/cPXGitvGMB81tZaEYMBYxFDASBgNVBAMTC0RT
QSBSb290IENBghDCpMJ75zgZokJVlZmNq/LTMAkGByqGSM44BAMDLwAwLAIUYUALM9WhgwzRMj1y
MSdoparmYvICFFxLgFr2ow3NGTkqWvHIXtjO9R0G

但是,当我的Java副本获取公钥时,使用相同的cert文件,获取

$ cat david-509.cer | openssl x509 -pubkey
-----BEGIN PUBLIC KEY-----
MIIBtzCCASwGByqGSM44BAEwggEfAoGBALWn4Iyvn7LFkV9ULoZtwJ8J1c+ibsbh
jPiw+xUgRW2LAZV2/Lv89W1jCprNkf87tN/ogMT/1VSIOo7ff/tqVRTWPVJ1ZMrR
9VOnF2k/Sorg8CmrsAClsSWrACKIwK2XKJGWTU4oMLxvYcu85+yQ4nWLofgA/+WA
RrJ/rk2aUSZ3AhUAlqPLNh6JZkpDG/OXKzhsZFUiDrkCgYEAoICjHltWOgN8/2uy
AaMTNrBuJfi/HM9AWe5B8m9HDfl1K6Qx2Ni6tbYPuFtvHdGnoqqn46l7eY+xjpi5
GEydvkPtAQKmTDGcSh6vtnTeNV15Hafg5pXUKw1OisIr/bpx/KIkcgCtSo6qC5Ih
DzeZXnfJYcE+8U+O6hEr5dwByN4DgYQAAoGAeaKLPS4ktxULg3YQL0ePphF08tKs
ddZtv3SDERa8b8go5h3AxmWjuDd8y9dIzZFe8KDjY9LgJU4JOA27snO3fCsPAVkm
J0O2pbxn+wzT7oij2FOLcCAjnFNNsoaWrtMv+I4XXl18DyDQLFkZiPx92UyuDzoQ
TGxgCrPccQPjUgY=
-----END PUBLIC KEY-----

因此我的问题。如何从我的证书中获得此值?

谢谢!

2 个答案:

答案 0 :(得分:1)

Ian Boyd's answer。它只是提供了您正在寻找的有关编码的所有答案。请注意,它与RSA有关,而与DSA无关,但它为您提供了有关PEM / DER / ASN.1编码的所有信息,这是您的问题。

答案 1 :(得分:1)

您应该使用cert.PublicKey.EncodedKeyValue代替cert.GetPublicKey()

EncodedKeyValue提供ASN1编码值,而非原始密钥数据GetPublicKey()

所以你可以使用这段代码

void ExportPublicKey(X509Certificate2 cert, string filePath)
{
    byte[] encodedPublicKey = cert.PublicKey.EncodedKeyValue.RawData;
    File.WriteAllLines(filePath, new[] {
        "-----BEGIN PUBLIC KEY-----",
        Convert.ToBase64String(encodedPublicKey, Base64FormattingOptions.InsertLineBreaks),
        "-----END PUBLIC KEY-----",
    });
}