我有一个Java Web服务,它从其他服务接收X509证书。在 Java Web Service 上,X509证书使用此代码截图序列化为字节数组
for (X509Certificate certificate : certs) {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
try (ObjectOutput out = new ObjectOutputStream(bos)) {
out.writeObject(certificate);
wrapper = new CustomMapCertificateWrapper();
wrapper.setCustomValue(bos.toByteArray());
response.getCustomMapCertificateWrapper().add(wrapper);
}
}
这里的 CustomMapCertificateWrapper 是具有 byte[] 值命名字段的类,它将 x509Certificate 存储为字节数组。我的 .NET 服务接收此对象 CustomMapCertificateWrapper,我尝试使用此代码片段在 C# 端生成 X509证书
//Do array reverse because of BigEndian difference between Java and c# languages
Array.Reverse(customMapCertificateWrapper.value);
var certificate = new X509Certificate(customMapCertificateWrapper.value);
这段代码给我带来了如下的经历
System.Security.Cryptography.CryptographicException: Cannot find the requested object.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
at System.Security.Cryptography.X509Certificates.X509Utils._QueryCertBlobType(Byte[] rawData)
at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags)
at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData)
Java的ObjectOutputStream
生成旨在由Java的ObjectInputStream
读入的输出。它不会生成与语言无关的标准结果。
为了便于移植,您应该使用Certificate.getEncoded()
方法序列化 JavaX509Certificate
。然后,可以在 C# 端将输出用作X509Certificate()
或X509Certificate2()
构造函数的byte[]
参数。